@mux/mux-video 0.31.3 → 0.31.4-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mux-video.js +49 -47
- package/dist/mux-video.js.map +4 -4
- package/dist/mux-video.mjs +49 -47
- package/dist/mux-video.mjs.map +4 -4
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/ads/react.d.ts +1 -1
- package/dist/types/react.d.ts +1 -1
- package/dist/types-ts3.4/ads/react.d.ts +1 -1
- package/dist/types-ts3.4/react.d.ts +1 -1
- package/package.json +2 -2
package/dist/mux-video.js
CHANGED
|
@@ -1,61 +1,63 @@
|
|
|
1
|
-
"use strict";(()=>{var Ff=Object.defineProperty;var Uf=Object.getPrototypeOf;var Bf=Reflect.get;var zl=s=>{throw TypeError(s)};var $f=(s,e,t)=>e in s?Ff(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var ne=(s,e,t)=>$f(s,typeof e!="symbol"?e+"":e,t),Gn=(s,e,t)=>e.has(s)||zl("Cannot "+t);var D=(s,e,t)=>(Gn(s,e,"read from private field"),t?t.call(s):e.get(s)),X=(s,e,t)=>e.has(s)?zl("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),j=(s,e,t,i)=>(Gn(s,e,"write to private field"),i?i.call(s,t):e.set(s,t),t),me=(s,e,t)=>(Gn(s,e,"access private method"),t);var sr=(s,e,t)=>Bf(Uf(s),t,e);var Ni=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class s extends Ni{}globalThis.DocumentFragment=s}var hs=class extends Ni{},Kn=class extends Ni{},Gf={get(s){},define(s,e,t){},getName(s){return null},upgrade(s){},whenDefined(s){return Promise.resolve(hs)}},fs,Vn=class{constructor(e,t={}){X(this,fs);j(this,fs,t==null?void 0:t.detail)}get detail(){return D(this,fs)}initCustomEvent(){}};fs=new WeakMap;function Kf(s,e){return new hs}var Xl={document:{createElement:Kf},DocumentFragment,customElements:Gf,CustomEvent:Vn,EventTarget:Ni,HTMLElement:hs,HTMLVideoElement:Kn},Ql=typeof window=="undefined"||typeof globalThis.customElements=="undefined",rr=Ql?Xl:globalThis,HT=Ql?Xl.document:globalThis.document;var Vf=Object.create,au=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,qf=Object.getOwnPropertyNames,Wf=Object.getPrototypeOf,Yf=Object.prototype.hasOwnProperty,ou=function(s,e){return function(){return s&&(e=s(s=0)),e}},ze=function(s,e){return function(){return e||s((e={exports:{}}).exports,e),e.exports}},jf=function(s,e,t,i){if(e&&typeof e=="object"||typeof e=="function")for(var r=qf(e),n=0,a=r.length,o;n<a;n++)o=r[n],!Yf.call(s,o)&&o!==t&&au(s,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(i=Hf(e,o))||i.enumerable});return s},at=function(s,e,t){return t=s!=null?Vf(Wf(s)):{},jf(e||!s||!s.__esModule?au(t,"default",{value:s,enumerable:!0}):t,s)},Tt=ze(function(s,e){var t;typeof window!="undefined"?t=window:typeof global!="undefined"?t=global:typeof self!="undefined"?t=self:t={},e.exports=t});function gi(s,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](s):gi(s,e)}var pi=ou(function(){pi()});function lu(s){"@swc/helpers - typeof";return s&&typeof Symbol!="undefined"&&s.constructor===Symbol?"symbol":typeof s}var uu=ou(function(){}),du=ze(function(s,e){var t=Array.prototype.slice;e.exports=i;function i(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),zf=ze(function(s,e){pi(),e.exports=t;function t(i,r){if(!gi(this,t))return new t(i,r);this.data=i,this.nodeValue=i,this.length=i.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),Xf=ze(function(s,e){pi(),e.exports=t;function t(i,r){if(!gi(this,t))return new t(i);this.data=i||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(i,r,n){var a=this.data,o=a.substring(0,i),l=a.substring(i+r,a.length);this.data=o+n+l,this.length=this.data.length}}),cu=ze(function(s,e){e.exports=t;function t(i){var r=this,n=i.type;i.target||(i.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){i.currentTarget=r,typeof o=="function"?o(i):o.handleEvent(i)});r.parentNode&&r.parentNode.dispatchEvent(i)}}),hu=ze(function(s,e){e.exports=t;function t(i,r){var n=this;n.listeners||(n.listeners={}),n.listeners[i]||(n.listeners[i]=[]),n.listeners[i].indexOf(r)===-1&&n.listeners[i].push(r)}}),fu=ze(function(s,e){e.exports=t;function t(i,r){var n=this;if(n.listeners&&n.listeners[i]){var a=n.listeners[i],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),Qf=ze(function(s,e){uu(),e.exports=i;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function i(h){switch(h.nodeType){case 3:return d(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+u(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(i)):h.textContent||h.innerText?f.push(d(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=lu(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var p=h[m];m=m.replace(/[A-Z]/g,function(g){return"-"+g.toLowerCase()}),f+=m+":"+p+";"}),f}function o(h){var f=h.dataset,m=[];for(var p in f)m.push({name:"data-"+p,value:f[p]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var p=m.name,g=m.value;p==="style"&&(g=a(g)),f.push(p+'="'+c(g)+'"')}),f.length?" "+f.join(" "):""}function u(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var p in h._attributes)for(var g in h._attributes[p]){var v=h._attributes[p][g],T=(v.prefix?v.prefix+":":"")+g;f.push({name:T,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function d(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return d(h).replace(/"/g,""")}}),mu=ze(function(s,e){pi();var t=du(),i=cu(),r=hu(),n=fu(),a=Qf(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(u,d,c){if(!gi(this,l))return new l(u);var h=c===void 0?o:c||null;this.tagName=h===o?String(u).toUpperCase():u,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=d||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(u){return u.parentNode&&u.parentNode.removeChild(u),this.childNodes.push(u),u.parentNode=this,u},l.prototype.replaceChild=function(u,d){u.parentNode&&u.parentNode.removeChild(u);var c=this.childNodes.indexOf(d);return d.parentNode=null,this.childNodes[c]=u,u.parentNode=this,d},l.prototype.removeChild=function(u){var d=this.childNodes.indexOf(u);return this.childNodes.splice(d,1),u.parentNode=null,u},l.prototype.insertBefore=function(u,d){u.parentNode&&u.parentNode.removeChild(u);var c=d==null?-1:this.childNodes.indexOf(d);return c>-1?this.childNodes.splice(c,0,u):this.childNodes.push(u),u.parentNode=this,u},l.prototype.setAttributeNS=function(u,d,c){var h=null,f=d,m=d.indexOf(":");if(m>-1&&(h=d.substr(0,m),f=d.substr(m+1)),this.tagName==="INPUT"&&d==="type")this.type=c;else{var p=this._attributes[u]||(this._attributes[u]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(u,d){var c=this._attributes[u],h=c&&c[d]&&c[d].value;return this.tagName==="INPUT"&&d==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(u,d){var c=this._attributes[u];c&&delete c[d]},l.prototype.hasAttributeNS=function(u,d){var c=this._attributes[u];return!!c&&d in c},l.prototype.setAttribute=function(u,d){return this.setAttributeNS(null,u,d)},l.prototype.getAttribute=function(u){return this.getAttributeNS(null,u)},l.prototype.removeAttribute=function(u){return this.removeAttributeNS(null,u)},l.prototype.hasAttribute=function(u){return this.hasAttributeNS(null,u)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=i,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(u){var d=u.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");d.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(u){u=u.toLowerCase();var d=[];return t(this.childNodes,function(c){c.nodeType===1&&(u==="*"||c.tagName.toLowerCase()===u)&&d.push(c)}),d},l.prototype.contains=function(u){return t(this,function(d){return u===d})||!1}}),Jf=ze(function(s,e){pi();var t=mu();e.exports=i;function i(r){if(!gi(this,i))return new i;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}i.prototype.type="DocumentFragment",i.prototype.nodeType=11,i.prototype.nodeName="#document-fragment",i.prototype.appendChild=t.prototype.appendChild,i.prototype.replaceChild=t.prototype.replaceChild,i.prototype.removeChild=t.prototype.removeChild,i.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),Zf=ze(function(s,e){e.exports=t;function t(i){}t.prototype.initEvent=function(i,r,n){this.type=i,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),em=ze(function(s,e){pi();var t=du(),i=zf(),r=Xf(),n=mu(),a=Jf(),o=Zf(),l=cu(),u=hu(),d=fu();e.exports=c;function c(){if(!gi(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var p=f===null?null:String(f);return new n(m,this,p)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new i(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(p){if(String(p.id)===f)return p});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=d,h.addEventListener=u,h.dispatchEvent=l}),tm=ze(function(s,e){var t=em();e.exports=new t}),gu=ze(function(s,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},i=tm(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=i)),e.exports=r});function im(s){if(Array.isArray(s))return s}function sm(s,e){var t=s==null?null:typeof Symbol!="undefined"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var i=[],r=!0,n=!1,a,o;try{for(t=t.call(s);!(r=(a=t.next()).done)&&(i.push(a.value),!(e&&i.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return i}}function rm(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function
|
|
3
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ct(s){return om(s)||lm(s)||pu(s)||um()}var fi={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},dm=function(s){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,i,r,n,a,o=s?[console,s]:[console],l=(t=console.trace).bind.apply(t,ct(o)),u=(i=console.info).bind.apply(i,ct(o)),d=(r=console.debug).bind.apply(r,ct(o)),c=(n=console.warn).bind.apply(n,ct(o)),h=(a=console.error).bind.apply(a,ct(o)),f=e;return{trace:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>fi.TRACE))return l.apply(void 0,ct(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>fi.DEBUG))return d.apply(void 0,ct(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>fi.INFO))return u.apply(void 0,ct(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>fi.WARN))return c.apply(void 0,ct(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>fi.ERROR))return h.apply(void 0,ct(p))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},Te=dm("[mux]"),Hn=at(Tt());function Qn(){var s=Hn.default.doNotTrack||Hn.default.navigator&&Hn.default.navigator.doNotTrack;return s==="1"}function J(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}pi();function Pe(s,e){if(!gi(s,e))throw new TypeError("Cannot call a class as a function")}function Zl(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(s,i.key,i)}}function ft(s,e,t){return e&&Zl(s.prototype,e),t&&Zl(s,t),s}function B(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Ui(s){return Ui=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Ui(s)}function cm(s,e){for(;!Object.prototype.hasOwnProperty.call(s,e)&&(s=Ui(s),s!==null););return s}function ar(s,e,t){return typeof Reflect!="undefined"&&Reflect.get?ar=Reflect.get:ar=function(i,r,n){var a=cm(i,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||i):o.value}},ar(s,e,t||s)}function Jn(s,e){return Jn=Object.setPrototypeOf||function(t,i){return t.__proto__=i,t},Jn(s,e)}function hm(s,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(e&&e.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),e&&Jn(s,e)}function fm(s,e){if(s==null)return{};var t={},i=Object.keys(s),r,n;for(n=0;n<i.length;n++)r=i[n],!(e.indexOf(r)>=0)&&(t[r]=s[r]);return t}function mm(s,e){if(s==null)return{};var t=fm(s,e),i,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);for(r=0;r<n.length;r++)i=n[r],!(e.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(t[i]=s[i])}return t}function gm(){if(typeof Reflect=="undefined"||!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}}uu();function pm(s,e){return e&&(lu(e)==="object"||typeof e=="function")?e:J(s)}function ym(s){var e=gm();return function(){var t=Ui(s),i;if(e){var r=Ui(this).constructor;i=Reflect.construct(t,arguments,r)}else i=t.apply(this,arguments);return pm(this,i)}}var ht=function(s){return Es(s)[0]},Es=function(s){if(typeof s!="string"||s==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=s.match(e)||[],i=t[4],r;return i&&(r=(i.match(/[^\.]+\.[^\.]+$/)||[])[0]),[i,r]},qn=at(Tt()),vm={exists:function(){var s=qn.default.performance,e=s&&s.timing;return e!==void 0},domContentLoadedEventEnd:function(){var s=qn.default.performance,e=s&&s.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var s=qn.default.performance,e=s&&s.timing;return e&&e.navigationStart}},lr=vm;function we(s,e,t){t=t===void 0?1:t,s[e]=s[e]||0,s[e]+=t}function ur(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},i=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(i=i.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),i.forEach(function(r){B(s,r,t[r])})}return s}function Em(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function ea(s,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Em(Object(e)).forEach(function(t){Object.defineProperty(s,t,Object.getOwnPropertyDescriptor(e,t))}),s}var Tm=["x-cdn","content-type"],vu=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],_m=Tm.concat(vu);function ta(s){s=s||"";var e={},t=s.trim().split(/[\r\n]+/);return t.forEach(function(i){if(i){var r=i.split(": "),n=r.shift();n&&(_m.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function dr(s){if(s){var e=vu.find(function(t){return s[t]!==void 0});return e?s[e]:void 0}}var Sm=function(s){var e={};for(var t in s){var i=s[t],r=i["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=i["DATA-ID"].replace("io.litix.data.","");e[n]=i.VALUE}}return e},Eu=Sm,nr=function(s){if(!s)return{};var e=lr.navigationStart(),t=s.loading,i=t?t.start:s.trequest,r=t?t.first:s.tfirst,n=t?t.end:s.tload;return{bytesLoaded:s.total,requestStart:Math.round(e+i),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},ms=function(s){if(!(!s||typeof s.getAllResponseHeaders!="function"))return ta(s.getAllResponseHeaders())},bm=function(s,e,t){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=s.log,a=s.utils.secondsToMs,o=function(v){var T=parseInt(r.version),E;return T===1&&v.programDateTime!==null&&(E=v.programDateTime),T===0&&v.pdt!==null&&(E=v.pdt),E};if(!lr.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,T){return s.emit(e,v,T)},u=function(v,T){var E=T.levels,_=T.audioTracks,b=T.url,x=T.stats,S=T.networkDetails,R=T.sessionData,I={},A={};E.forEach(function(M,G){I[G]={width:M.width,height:M.height,bitrate:M.bitrate,attrs:M.attrs}}),_.forEach(function(M,G){A[G]={name:M.name,language:M.lang,bitrate:M.bitrate}});var L=nr(x),P=L.bytesLoaded,O=L.requestStart,N=L.responseStart,F=L.responseEnd;l("requestcompleted",ea(ur({},Eu(R)),{request_event_type:v,request_bytes_loaded:P,request_start:O,request_response_start:N,request_response_end:F,request_type:"manifest",request_hostname:ht(b),request_response_headers:ms(S),request_rendition_lists:{media:I,audio:A,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,u);var d=function(v,T){var E=T.details,_=T.level,b=T.networkDetails,x=T.stats,S=nr(x),R=S.bytesLoaded,I=S.requestStart,A=S.responseStart,L=S.responseEnd,P=E.fragments[E.fragments.length-1],O=o(P)+a(P.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:R,request_start:I,request_response_start:A,request_response_end:L,request_current_level:_,request_type:"manifest",request_hostname:ht(E.url),request_response_headers:ms(b),video_holdback:E.holdBack&&a(E.holdBack),video_part_holdback:E.partHoldBack&&a(E.partHoldBack),video_part_target_duration:E.partTarget&&a(E.partTarget),video_target_duration:E.targetduration&&a(E.targetduration),video_source_is_live:E.live,player_manifest_newest_program_time:isNaN(O)?void 0:O})};t.on(r.Events.LEVEL_LOADED,d);var c=function(v,T){var E=T.details,_=T.networkDetails,b=T.stats,x=nr(b),S=x.bytesLoaded,R=x.requestStart,I=x.responseStart,A=x.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:S,request_start:R,request_response_start:I,request_response_end:A,request_type:"manifest",request_hostname:ht(E.url),request_response_headers:ms(_)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(v,T){var E=T.stats,_=T.networkDetails,b=T.frag;E=E||b.stats;var x=nr(E),S=x.bytesLoaded,R=x.requestStart,I=x.responseStart,A=x.responseEnd,L=_?ms(_):void 0,P={request_event_type:v,request_bytes_loaded:S,request_start:R,request_response_start:I,request_response_end:A,request_hostname:_?ht(_.responseURL):void 0,request_id:L?dr(L):void 0,request_response_headers:L,request_media_duration:b.duration,request_url:_==null?void 0:_.responseURL};b.type==="main"?(P.request_type="media",P.request_current_level=b.level,P.request_video_width=(t.levels[b.level]||{}).width,P.request_video_height=(t.levels[b.level]||{}).height,P.request_labeled_bitrate=(t.levels[b.level]||{}).bitrate):P.request_type=b.type,l("requestcompleted",P)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,T){var E=T.frag,_=E.start,b=o(E),x={currentFragmentPDT:b,currentFragmentStart:a(_)};l("fragmentchange",x)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,T){var E=T.type,_=T.details,b=T.response,x=T.fatal,S=T.frag,R=T.networkDetails,I=(S==null?void 0:S.url)||T.url||"",A=R?ms(R):void 0;if((_===r.ErrorDetails.MANIFEST_LOAD_ERROR||_===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||_===r.ErrorDetails.FRAG_LOAD_ERROR||_===r.ErrorDetails.FRAG_LOAD_TIMEOUT||_===r.ErrorDetails.LEVEL_LOAD_ERROR||_===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||_===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||_===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||_===r.ErrorDetails.SUBTITLE_LOAD_ERROR||_===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||_===r.ErrorDetails.KEY_LOAD_ERROR||_===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:_,request_url:I,request_hostname:ht(I),request_id:A?dr(A):void 0,request_type:_===r.ErrorDetails.FRAG_LOAD_ERROR||_===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":_===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||_===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":_===r.ErrorDetails.SUBTITLE_LOAD_ERROR||_===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":_===r.ErrorDetails.KEY_LOAD_ERROR||_===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:b==null?void 0:b.code,request_error_text:b==null?void 0:b.text}),x){var L,P="".concat(I?"url: ".concat(I,`
|
|
4
|
-
`):"")+"".concat(
|
|
1
|
+
"use strict";(()=>{var lm=Object.defineProperty;var um=Object.getPrototypeOf;var dm=Reflect.get;var Vu=s=>{throw TypeError(s)};var cm=(s,e,t)=>e in s?lm(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var fe=(s,e,t)=>cm(s,typeof e!="symbol"?e+"":e,t),_a=(s,e,t)=>e.has(s)||Vu("Cannot "+t);var D=(s,e,t)=>(_a(s,e,"read from private field"),t?t.call(s):e.get(s)),te=(s,e,t)=>e.has(s)?Vu("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),Z=(s,e,t,i)=>(_a(s,e,"write to private field"),i?i.call(s,t):e.set(s,t),t),Ae=(s,e,t)=>(_a(s,e,"access private method"),t);var kr=(s,e,t)=>dm(um(s),t,e);var ss=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class s extends ss{}globalThis.DocumentFragment=s}var Ds=class extends ss{},Sa=class extends ss{},hm={get(s){},define(s,e,t){},getName(s){return null},upgrade(s){},whenDefined(s){return Promise.resolve(Ds)}},ks,ba=class{constructor(e,t={}){te(this,ks);Z(this,ks,t==null?void 0:t.detail)}get detail(){return D(this,ks)}initCustomEvent(){}};ks=new WeakMap;function fm(s,e){return new Ds}var Hu={document:{createElement:fm},DocumentFragment,customElements:hm,CustomEvent:ba,EventTarget:ss,HTMLElement:Ds,HTMLVideoElement:Sa},qu=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Pr=qu?Hu:globalThis,ib=qu?Hu.document:globalThis.document;var gm=Object.create,ed=Object.defineProperty,mm=Object.getOwnPropertyDescriptor,pm=Object.getOwnPropertyNames,vm=Object.getPrototypeOf,ym=Object.prototype.hasOwnProperty,td=function(s,e){return function(){return s&&(e=s(s=0)),e}},ut=function(s,e){return function(){return e||s((e={exports:{}}).exports,e),e.exports}},Em=function(s,e,t,i){if(e&&typeof e=="object"||typeof e=="function")for(var r=pm(e),n=0,a=r.length,o;n<a;n++)o=r[n],!ym.call(s,o)&&o!==t&&ed(s,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(i=mm(e,o))||i.enumerable});return s},Tt=function(s,e,t){return t=s!=null?gm(vm(s)):{},Em(e||!s||!s.__esModule?ed(t,"default",{value:s,enumerable:!0}):t,s)},Bt=ut(function(s,e){var t;typeof window!="undefined"?t=window:typeof global!="undefined"?t=global:typeof self!="undefined"?t=self:t={},e.exports=t});function Fi(s,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](s):Fi(s,e)}var Bi=td(function(){Bi()});function id(s){"@swc/helpers - typeof";return s&&typeof Symbol!="undefined"&&s.constructor===Symbol?"symbol":typeof s}var sd=td(function(){}),rd=ut(function(s,e){var t=Array.prototype.slice;e.exports=i;function i(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),Tm=ut(function(s,e){Bi(),e.exports=t;function t(i,r){if(!Fi(this,t))return new t(i,r);this.data=i,this.nodeValue=i,this.length=i.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),_m=ut(function(s,e){Bi(),e.exports=t;function t(i,r){if(!Fi(this,t))return new t(i);this.data=i||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(i,r,n){var a=this.data,o=a.substring(0,i),l=a.substring(i+r,a.length);this.data=o+n+l,this.length=this.data.length}}),nd=ut(function(s,e){e.exports=t;function t(i){var r=this,n=i.type;i.target||(i.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){i.currentTarget=r,typeof o=="function"?o(i):o.handleEvent(i)});r.parentNode&&r.parentNode.dispatchEvent(i)}}),ad=ut(function(s,e){e.exports=t;function t(i,r){var n=this;n.listeners||(n.listeners={}),n.listeners[i]||(n.listeners[i]=[]),n.listeners[i].indexOf(r)===-1&&n.listeners[i].push(r)}}),od=ut(function(s,e){e.exports=t;function t(i,r){var n=this;if(n.listeners&&n.listeners[i]){var a=n.listeners[i],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),Sm=ut(function(s,e){sd(),e.exports=i;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function i(h){switch(h.nodeType){case 3:return d(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],g=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(g=g.toLowerCase()),f.push("<"+g+u(h)+o(h)),t.indexOf(g)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(i)):h.textContent||h.innerText?f.push(d(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+g+">")),f.join("")}function n(h,f){var g=id(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(g==="string"||g==="boolean"||g==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(g){var m=h[g];g=g.replace(/[A-Z]/g,function(p){return"-"+p.toLowerCase()}),f+=g+":"+m+";"}),f}function o(h){var f=h.dataset,g=[];for(var m in f)g.push({name:"data-"+m,value:f[m]});return g.length?l(g):""}function l(h){var f=[];return h.forEach(function(g){var m=g.name,p=g.value;m==="style"&&(p=a(p)),f.push(m+'="'+c(p)+'"')}),f.length?" "+f.join(" "):""}function u(h){var f=[];for(var g in h)n(h,g)&&f.push({name:g,value:h[g]});for(var m in h._attributes)for(var p in h._attributes[m]){var y=h._attributes[m][p],T=(y.prefix?y.prefix+":":"")+p;f.push({name:T,value:y.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function d(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return d(h).replace(/"/g,""")}}),ld=ut(function(s,e){Bi();var t=rd(),i=nd(),r=ad(),n=od(),a=Sm(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(u,d,c){if(!Fi(this,l))return new l(u);var h=c===void 0?o:c||null;this.tagName=h===o?String(u).toUpperCase():u,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=d||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(u){return u.parentNode&&u.parentNode.removeChild(u),this.childNodes.push(u),u.parentNode=this,u},l.prototype.replaceChild=function(u,d){u.parentNode&&u.parentNode.removeChild(u);var c=this.childNodes.indexOf(d);return d.parentNode=null,this.childNodes[c]=u,u.parentNode=this,d},l.prototype.removeChild=function(u){var d=this.childNodes.indexOf(u);return this.childNodes.splice(d,1),u.parentNode=null,u},l.prototype.insertBefore=function(u,d){u.parentNode&&u.parentNode.removeChild(u);var c=d==null?-1:this.childNodes.indexOf(d);return c>-1?this.childNodes.splice(c,0,u):this.childNodes.push(u),u.parentNode=this,u},l.prototype.setAttributeNS=function(u,d,c){var h=null,f=d,g=d.indexOf(":");if(g>-1&&(h=d.substr(0,g),f=d.substr(g+1)),this.tagName==="INPUT"&&d==="type")this.type=c;else{var m=this._attributes[u]||(this._attributes[u]={});m[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(u,d){var c=this._attributes[u],h=c&&c[d]&&c[d].value;return this.tagName==="INPUT"&&d==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(u,d){var c=this._attributes[u];c&&delete c[d]},l.prototype.hasAttributeNS=function(u,d){var c=this._attributes[u];return!!c&&d in c},l.prototype.setAttribute=function(u,d){return this.setAttributeNS(null,u,d)},l.prototype.getAttribute=function(u){return this.getAttributeNS(null,u)},l.prototype.removeAttribute=function(u){return this.removeAttributeNS(null,u)},l.prototype.hasAttribute=function(u){return this.hasAttributeNS(null,u)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=i,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(u){var d=u.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",g=f.split(" ");d.every(function(m){return g.indexOf(m)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(u){u=u.toLowerCase();var d=[];return t(this.childNodes,function(c){c.nodeType===1&&(u==="*"||c.tagName.toLowerCase()===u)&&d.push(c)}),d},l.prototype.contains=function(u){return t(this,function(d){return u===d})||!1}}),bm=ut(function(s,e){Bi();var t=ld();e.exports=i;function i(r){if(!Fi(this,i))return new i;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}i.prototype.type="DocumentFragment",i.prototype.nodeType=11,i.prototype.nodeName="#document-fragment",i.prototype.appendChild=t.prototype.appendChild,i.prototype.replaceChild=t.prototype.replaceChild,i.prototype.removeChild=t.prototype.removeChild,i.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),Am=ut(function(s,e){e.exports=t;function t(i){}t.prototype.initEvent=function(i,r,n){this.type=i,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),Rm=ut(function(s,e){Bi();var t=rd(),i=Tm(),r=_m(),n=ld(),a=bm(),o=Am(),l=nd(),u=ad(),d=od();e.exports=c;function c(){if(!Fi(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,g){var m=f===null?null:String(f);return new n(g,this,m)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new i(f,this)},h.getElementById=function(f){f=String(f);var g=t(this.childNodes,function(m){if(String(m.id)===f)return m});return g||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=d,h.addEventListener=u,h.dispatchEvent=l}),xm=ut(function(s,e){var t=Rm();e.exports=new t}),ud=ut(function(s,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},i=xm(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=i)),e.exports=r});function Im(s){if(Array.isArray(s))return s}function Lm(s,e){var t=s==null?null:typeof Symbol!="undefined"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var i=[],r=!0,n=!1,a,o;try{for(t=t.call(s);!(r=(a=t.next()).done)&&(i.push(a.value),!(e&&i.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return i}}function Dm(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ka(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t<e;t++)i[t]=s[t];return i}function dd(s,e){if(s){if(typeof s=="string")return ka(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(t);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return ka(s,e)}}function zt(s,e){return Im(s)||Lm(s,e)||dd(s,e)||Dm()}var ws=Tt(Bt()),Wu=Tt(Bt()),km=Tt(Bt()),Pm={now:function(){var s=km.default.performance,e=s&&s.timing,t=e&&e.navigationStart,i=typeof t=="number"&&typeof s.now=="function"?t+s.now():Date.now();return Math.round(i)}},ze=Pm,Ms=function(){var s,e,t;if(typeof((s=Wu.default.crypto)===null||s===void 0?void 0:s.getRandomValues)=="function"){t=new Uint8Array(32),Wu.default.crypto.getRandomValues(t);for(var i=0;i<32;i++)t[i]=t[i]%16}else{t=[];for(var r=0;r<32;r++)t[r]=Math.random()*16|0}var n=0;e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(l){var u=l==="x"?t[n]:t[n]&3|8;return n++,u.toString(16)});var a=ze.now(),o=a==null?void 0:a.toString(16).substring(3);return o?e.substring(0,28)+o:e},cd=function(){return("000000"+(Math.random()*Math.pow(36,6)<<0).toString(36)).slice(-6)},xt=function(s){if(s&&typeof s.nodeName!="undefined")return s.muxId||(s.muxId=cd()),s.muxId;var e;try{e=document.querySelector(s)}catch{}return e&&!e.muxId&&(e.muxId=s),(e==null?void 0:e.muxId)||s},Or=function(s){var e;s&&typeof s.nodeName!="undefined"?(e=s,s=xt(e)):e=document.querySelector(s);var t=e&&e.nodeName?e.nodeName.toLowerCase():"";return[e,s,t]};function Cm(s){if(Array.isArray(s))return ka(s)}function wm(s){if(typeof Symbol!="undefined"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Om(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
3
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function It(s){return Cm(s)||wm(s)||dd(s)||Om()}var Mi={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},Mm=function(s){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,i,r,n,a,o=s?[console,s]:[console],l=(t=console.trace).bind.apply(t,It(o)),u=(i=console.info).bind.apply(i,It(o)),d=(r=console.debug).bind.apply(r,It(o)),c=(n=console.warn).bind.apply(n,It(o)),h=(a=console.error).bind.apply(a,It(o)),f=e;return{trace:function(){for(var g=arguments.length,m=new Array(g),p=0;p<g;p++)m[p]=arguments[p];if(!(f>Mi.TRACE))return l.apply(void 0,It(m))},debug:function(){for(var g=arguments.length,m=new Array(g),p=0;p<g;p++)m[p]=arguments[p];if(!(f>Mi.DEBUG))return d.apply(void 0,It(m))},info:function(){for(var g=arguments.length,m=new Array(g),p=0;p<g;p++)m[p]=arguments[p];if(!(f>Mi.INFO))return u.apply(void 0,It(m))},warn:function(){for(var g=arguments.length,m=new Array(g),p=0;p<g;p++)m[p]=arguments[p];if(!(f>Mi.WARN))return c.apply(void 0,It(m))},error:function(){for(var g=arguments.length,m=new Array(g),p=0;p<g;p++)m[p]=arguments[p];if(!(f>Mi.ERROR))return h.apply(void 0,It(m))},get level(){return f},set level(g){g!==this.level&&(f=g!=null?g:e)}}},De=Mm("[mux]"),Aa=Tt(Bt());function Pa(){var s=Aa.default.doNotTrack||Aa.default.navigator&&Aa.default.navigator.doNotTrack;return s==="1"}function ae(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}Bi();function He(s,e){if(!Fi(s,e))throw new TypeError("Cannot call a class as a function")}function Yu(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(s,i.key,i)}}function Dt(s,e,t){return e&&Yu(s.prototype,e),t&&Yu(s,t),s}function V(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function ns(s){return ns=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},ns(s)}function Nm(s,e){for(;!Object.prototype.hasOwnProperty.call(s,e)&&(s=ns(s),s!==null););return s}function wr(s,e,t){return typeof Reflect!="undefined"&&Reflect.get?wr=Reflect.get:wr=function(i,r,n){var a=Nm(i,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||i):o.value}},wr(s,e,t||s)}function Ca(s,e){return Ca=Object.setPrototypeOf||function(t,i){return t.__proto__=i,t},Ca(s,e)}function Fm(s,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(e&&e.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),e&&Ca(s,e)}function Bm(s,e){if(s==null)return{};var t={},i=Object.keys(s),r,n;for(n=0;n<i.length;n++)r=i[n],!(e.indexOf(r)>=0)&&(t[r]=s[r]);return t}function Um(s,e){if(s==null)return{};var t=Bm(s,e),i,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);for(r=0;r<n.length;r++)i=n[r],!(e.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(t[i]=s[i])}return t}function $m(){if(typeof Reflect=="undefined"||!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}}sd();function Gm(s,e){return e&&(id(e)==="object"||typeof e=="function")?e:ae(s)}function Km(s){var e=$m();return function(){var t=ns(s),i;if(e){var r=ns(this).constructor;i=Reflect.construct(t,arguments,r)}else i=t.apply(this,arguments);return Gm(this,i)}}var Lt=function(s){return Ns(s)[0]},Ns=function(s){if(typeof s!="string"||s==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=s.match(e)||[],i=t[4],r;return i&&(r=(i.match(/[^\.]+\.[^\.]+$/)||[])[0]),[i,r]},Ra=Tt(Bt()),Vm={exists:function(){var s=Ra.default.performance,e=s&&s.timing;return e!==void 0},domContentLoadedEventEnd:function(){var s=Ra.default.performance,e=s&&s.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var s=Ra.default.performance,e=s&&s.timing;return e&&e.navigationStart}},Mr=Vm;function Ye(s,e,t){t=t===void 0?1:t,s[e]=s[e]||0,s[e]+=t}function Nr(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},i=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(i=i.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),i.forEach(function(r){V(s,r,t[r])})}return s}function Hm(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function Oa(s,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Hm(Object(e)).forEach(function(t){Object.defineProperty(s,t,Object.getOwnPropertyDescriptor(e,t))}),s}var qm=["x-cdn","content-type"],hd=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],Wm=qm.concat(hd);function Ma(s){s=s||"";var e={},t=s.trim().split(/[\r\n]+/);return t.forEach(function(i){if(i){var r=i.split(": "),n=r.shift();n&&(Wm.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function Fr(s){if(s){var e=hd.find(function(t){return s[t]!==void 0});return e?s[e]:void 0}}var Ym=function(s){var e={};for(var t in s){var i=s[t],r=i["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=i["DATA-ID"].replace("io.litix.data.","");e[n]=i.VALUE}}return e},fd=Ym,Cr=function(s){if(!s)return{};var e=Mr.navigationStart(),t=s.loading,i=t?t.start:s.trequest,r=t?t.first:s.tfirst,n=t?t.end:s.tload;return{bytesLoaded:s.total,requestStart:Math.round(e+i),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Ps=function(s){if(!(!s||typeof s.getAllResponseHeaders!="function"))return Ma(s.getAllResponseHeaders())},jm=function(s,e,t){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=s.log,a=s.utils.secondsToMs,o=function(y){var T=parseInt(r.version),v;return T===1&&y.programDateTime!==null&&(v=y.programDateTime),T===0&&y.pdt!==null&&(v=y.pdt),v};if(!Mr.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(y,T){return s.emit(e,y,T)},u=function(y,T){var v=T.levels,_=T.audioTracks,S=T.url,A=T.stats,b=T.networkDetails,x=T.sessionData,L={},R={};v.forEach(function(C,N){L[N]={width:C.width,height:C.height,bitrate:C.bitrate,attrs:C.attrs}}),_.forEach(function(C,N){R[N]={name:C.name,language:C.lang,bitrate:C.bitrate}});var I=Cr(A),P=I.bytesLoaded,w=I.requestStart,B=I.responseStart,U=I.responseEnd;l("requestcompleted",Oa(Nr({},fd(x)),{request_event_type:y,request_bytes_loaded:P,request_start:w,request_response_start:B,request_response_end:U,request_type:"manifest",request_hostname:Lt(S),request_response_headers:Ps(b),request_rendition_lists:{media:L,audio:R,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,u);var d=function(y,T){var v=T.details,_=T.level,S=T.networkDetails,A=T.stats,b=Cr(A),x=b.bytesLoaded,L=b.requestStart,R=b.responseStart,I=b.responseEnd,P=v.fragments[v.fragments.length-1],w=o(P)+a(P.duration);l("requestcompleted",{request_event_type:y,request_bytes_loaded:x,request_start:L,request_response_start:R,request_response_end:I,request_current_level:_,request_type:"manifest",request_hostname:Lt(v.url),request_response_headers:Ps(S),video_holdback:v.holdBack&&a(v.holdBack),video_part_holdback:v.partHoldBack&&a(v.partHoldBack),video_part_target_duration:v.partTarget&&a(v.partTarget),video_target_duration:v.targetduration&&a(v.targetduration),video_source_is_live:v.live,player_manifest_newest_program_time:isNaN(w)?void 0:w})};t.on(r.Events.LEVEL_LOADED,d);var c=function(y,T){var v=T.details,_=T.networkDetails,S=T.stats,A=Cr(S),b=A.bytesLoaded,x=A.requestStart,L=A.responseStart,R=A.responseEnd;l("requestcompleted",{request_event_type:y,request_bytes_loaded:b,request_start:x,request_response_start:L,request_response_end:R,request_type:"manifest",request_hostname:Lt(v.url),request_response_headers:Ps(_)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(y,T){var v=T.stats,_=T.networkDetails,S=T.frag;v=v||S.stats;var A=Cr(v),b=A.bytesLoaded,x=A.requestStart,L=A.responseStart,R=A.responseEnd,I=_?Ps(_):void 0,P={request_event_type:y,request_bytes_loaded:b,request_start:x,request_response_start:L,request_response_end:R,request_hostname:_?Lt(_.responseURL):void 0,request_id:I?Fr(I):void 0,request_response_headers:I,request_media_duration:S.duration,request_url:_==null?void 0:_.responseURL};S.type==="main"?(P.request_type="media",P.request_current_level=S.level,P.request_video_width=(t.levels[S.level]||{}).width,P.request_video_height=(t.levels[S.level]||{}).height,P.request_labeled_bitrate=(t.levels[S.level]||{}).bitrate):P.request_type=S.type,l("requestcompleted",P)};t.on(r.Events.FRAG_LOADED,h);var f=function(y,T){var v=T.frag,_=v.start,S=o(v),A={currentFragmentPDT:S,currentFragmentStart:a(_)};l("fragmentchange",A)};t.on(r.Events.FRAG_CHANGED,f);var g=function(y,T){var v=T.type,_=T.details,S=T.response,A=T.fatal,b=T.frag,x=T.networkDetails,L=(b==null?void 0:b.url)||T.url||"",R=x?Ps(x):void 0;if((_===r.ErrorDetails.MANIFEST_LOAD_ERROR||_===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||_===r.ErrorDetails.FRAG_LOAD_ERROR||_===r.ErrorDetails.FRAG_LOAD_TIMEOUT||_===r.ErrorDetails.LEVEL_LOAD_ERROR||_===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||_===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||_===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||_===r.ErrorDetails.SUBTITLE_LOAD_ERROR||_===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||_===r.ErrorDetails.KEY_LOAD_ERROR||_===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:_,request_url:L,request_hostname:Lt(L),request_id:R?Fr(R):void 0,request_type:_===r.ErrorDetails.FRAG_LOAD_ERROR||_===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":_===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||_===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":_===r.ErrorDetails.SUBTITLE_LOAD_ERROR||_===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":_===r.ErrorDetails.KEY_LOAD_ERROR||_===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:S==null?void 0:S.code,request_error_text:S==null?void 0:S.text}),A){var I,P="".concat(L?"url: ".concat(L,`
|
|
4
|
+
`):"")+"".concat(S&&(S.code||S.text)?"response: ".concat(S.code,", ").concat(S.text,`
|
|
5
5
|
`):"")+"".concat(T.reason?"failure reason: ".concat(T.reason,`
|
|
6
6
|
`):"")+"".concat(T.level?"level: ".concat(T.level,`
|
|
7
7
|
`):"")+"".concat(T.parent?"parent stream controller: ".concat(T.parent,`
|
|
8
8
|
`):"")+"".concat(T.buffer?"buffer length: ".concat(T.buffer,`
|
|
9
9
|
`):"")+"".concat(T.error?"error: ".concat(T.error,`
|
|
10
10
|
`):"")+"".concat(T.event?"event: ".concat(T.event,`
|
|
11
|
-
`):"")+"".concat(T.err?"error message: ".concat((
|
|
12
|
-
`):"");l("error",{player_error_code:
|
|
13
|
-
`):"")+"".concat(
|
|
14
|
-
`):"");a("error",{player_error_code:_==null?void 0:_.code,player_error_message:_==null?void 0:_.message,player_error_context:I})};t.on("error",T),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",g),t.off("error",T),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},Dm=function(s){s&&typeof s._stopMuxMonitor=="function"&&s._stopMuxMonitor()},tu=0,km=function(){"use strict";function s(){Pe(this,s),B(this,"_listeners",void 0)}return ft(s,[{key:"on",value:function(e,t,i){return t._eventEmitterGuid=t._eventEmitterGuid||++tu,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],i&&(t=t.bind(i)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var i=this._listeners&&this._listeners[e];i&&i.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&i.splice(n,1)})}},{key:"one",value:function(e,t,i){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++tu;var n=function(){r.off(e,n),t.apply(i||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var i=this;if(this._listeners){t=t||{};var r=this._listeners["before"+e]||[],n=this._listeners["before*"]||[],a=this._listeners[e]||[],o=this._listeners["after"+e]||[],l=function(u,d){u=u.slice(),u.forEach(function(c){c.call(i,{type:e},d)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),s}(),Pm=km,Wn=at(Tt()),wm=function(){"use strict";function s(e){var t=this;Pe(this,s),B(this,"_playbackHeartbeatInterval",void 0),B(this,"_playheadShouldBeProgressing",void 0),B(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(i,r){t._playbackHeartbeatInterval!==null&&(Wn.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return ft(s,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Wn.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Wn.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),s}(),Cm=wm,Om=function s(e){"use strict";var t=this;Pe(this,s),B(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(i,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var i,r,n,a,o;(i=e.data)===null||i===void 0||delete i.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},Mm=Om,Nm=function(){"use strict";function s(e){Pe(this,s),B(this,"_watchTimeTrackerLastCheckedTime",void 0),B(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return ft(s,[{key:"_updateWatchTime",value:function(e,t){var i=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=i),we(this.pm.data,"view_watch_time",i-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=i}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),s}(),Fm=Nm,Um=function(){"use strict";function s(e){var t=this;Pe(this,s),B(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),B(this,"_lastTime",void 0),B(this,"_isAdPlaying",void 0),B(this,"_callbackUpdatePlaybackTime",void 0),B(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=Fe.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var i=this._startPlaybackTimeTracking.bind(this);e.on("playing",i),e.on("adplaying",i),e.on("seeked",i),e.on("rebufferend",i);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("rebufferstart",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=Fe.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return ft(s,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=Fe.now(),this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time||0,t=Fe.now(),i=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=i),r>0&&r<=1e3&&we(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&i>0&&i<=1e3&&(this._isAdPlaying&&we(this.pm.data,"ad_playing_time_ms_cumulative",i),we(this.pm.data,"view_playing_time_ms_cumulative",i)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),s}(),Bm=Um,$m=function(){"use strict";function s(e){Pe(this,s),B(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return ft(s,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position=="undefined"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var i=this,r=function(){i.pm.currentFragmentPDT&&i.pm.currentFragmentStart&&(i.pm.data.player_program_time=i.pm.currentFragmentPDT+i.pm.data.player_playhead_time-i.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n!="undefined"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),s}(),Gm=$m,iu=5*60*1e3,Km=function s(e){"use strict";if(Pe(this,s),!e.disableRebufferTracking){var t,i=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;we(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>iu&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(iu,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(we(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",i))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",i)})}},Vm=Km,Hm=function(){"use strict";function s(e){var t=this;Pe(this,s),B(this,"_lastCheckedTime",void 0),B(this,"_lastPlayheadTime",void 0),B(this,"_lastPlayheadTimeUpdatedTime",void 0),B(this,"_rebuffering",void 0),B(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:Fe.now()})}))}return ft(s,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var i=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&i>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}i?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),s}(),qm=Hm,Wm=function(){"use strict";function s(e){var t=this;Pe(this,s),B(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var i=e.data,r=i.view_id;if(!i.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame=="undefined"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame=="undefined"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||Fe.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return ft(s,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.pm.pageLoadInitTime&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.pm.pageLoadInitTime))}}]),s}(),Ym=Wm,jm=function s(e){"use strict";var t=this;Pe(this,s),B(this,"_lastPlayerHeight",void 0),B(this,"_lastPlayerWidth",void 0),B(this,"_lastPlayheadPosition",void 0),B(this,"_lastSourceHeight",void 0),B(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var i=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];i.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),u=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,u),we(e.data,"view_total_content_playback_time",a),we(e.data,"view_total_upscaling",l*a),we(e.data,"view_total_downscaling",u*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},zm=jm,Xm=2e3,Qm=function s(e){"use strict";var t=this;Pe(this,s),B(this,"isSeeking",void 0),this.isSeeking=!1;var i=-1,r=function(){var n=Fe.now(),a=(e.data.viewer_time||n)-(i||n);we(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,i=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-i<=Xm){i=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,i=a.viewer_time,we(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,i=-1})},Jm=Qm,su=function(s,e){s.push(e),s.sort(function(t,i){return t.viewer_time-i.viewer_time})},Zm=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],eg=function(){"use strict";function s(e){var t=this;Pe(this,s),B(this,"_adHasPlayed",void 0),B(this,"_adRequests",void 0),B(this,"_adResponses",void 0),B(this,"_currentAdRequestNumber",void 0),B(this,"_currentAdResponseNumber",void 0),B(this,"_prerollPlayTime",void 0),B(this,"_wouldBeNewAdPlay",void 0),B(this,"isAdBreak",void 0),B(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),Zm.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var i=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",i),e.on("playing",i),e.on("viewend",i),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),su(t._adRequests,n),we(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||we(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),su(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&we(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,we(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time=="undefined"&&typeof t._prerollPlayTime!="undefined"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||we(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||we(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return ft(s,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var i=Lt(Es(t.ad_tag_url),2),r=i[0],n=i[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=Lt(Es(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}this.pm.data.ad_type="preroll"}this.pm.data.ad_asset_url=t==null?void 0:t.ad_asset_url,this.pm.data.ad_tag_url=t==null?void 0:t.ad_tag_url,this.pm.data.ad_creative_id=t==null?void 0:t.ad_creative_id,this.pm.data.ad_id=t==null?void 0:t.ad_id,this.pm.data.ad_universal_id=t==null?void 0:t.ad_universal_id,t!=null&&t.ad_type&&(this.pm.data.ad_type=t==null?void 0:t.ad_type)}}]),s}(),tg=eg,ig=function s(e){"use strict";var t=this;Pe(this,s),B(this,"lastWallClockTime",void 0);var i=function(){t.lastWallClockTime=Fe.now(),e.on("before*",r)},r=function(n){var a=Fe.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",i),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",i)})},sg=ig,Yn=at(Tt()),Tu=function(s){return s()}(function(){var s=function(){for(var t=0,i={};t<arguments.length;t++){var r=arguments[t];for(var n in r)i[n]=r[n]}return i};function e(t){function i(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=s({path:"/"},i.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var u=document.cookie?document.cookie.split("; "):[],d=/(%[0-9A-Z]{2})+/g,c=0;c<u.length;c++){var h=u[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(d,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(d,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return i.set=i,i.get=function(r){return i.call(i,r)},i.getJSON=function(){return i.apply({json:!0},[].slice.call(arguments))},i.defaults={},i.remove=function(r,n){i(r,"",s(n,{expires:-1}))},i.withConverter=e,i}return e(function(){})}),_u="muxData",rg=function(s){return Object.entries(s).map(function(e){var t=Lt(e,2),i=t[0],r=t[1];return"".concat(i,"=").concat(r)}).join("&")},ng=function(s){return s.split("&").reduce(function(e,t){var i=Lt(t.split("="),2),r=i[0],n=i[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},Su=function(){var s;try{s=ng(Tu.get(_u)||"")}catch{s={}}return s},bu=function(s){try{Tu.set(_u,rg(s),{expires:365})}catch{}},ag=function(){var s=Su();return s.mux_viewer_id=s.mux_viewer_id||vs(),s.msn=s.msn||Math.random(),bu(s),{mux_viewer_id:s.mux_viewer_id,mux_sample_number:s.msn}},og=function(){var s=Su(),e=Fe.now();return s.session_start&&(s.sst=s.session_start,delete s.session_start),s.session_id&&(s.sid=s.session_id,delete s.session_id),s.session_expires&&(s.sex=s.session_expires,delete s.session_expires),(!s.sex||s.sex<e)&&(s.sid=vs(),s.sst=e),s.sex=e+25*60*1e3,bu(s),{session_id:s.sid,session_start:s.sst,session_expires:s.sex}};function lg(s,e){var t=e.beaconCollectionDomain,i=e.beaconDomain;if(t)return"https://"+t;s=s||"inferred";var r=i||"litix.io";return s.match(/^[a-z0-9]+$/)?"https://"+s+"."+r:"https://img.litix.io/a.gif"}var ug=at(Tt()),Au=function(){var s;switch(xu()){case"cellular":s="cellular";break;case"ethernet":s="wired";break;case"wifi":s="wifi";break;case void 0:break;default:s="other"}return s},xu=function(){var s=ug.default.navigator,e=s&&(s.connection||s.mozConnection||s.webkitConnection);return e&&e.type};Au.getConnectionFromAPI=xu;var dg=Au,cg={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},hg=Ru(cg),fg={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cm:"cmcd",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cv:"cumulative",cx:"connection",cz:"context",da:"data",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mp:"mode",ms:"ms",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",pv:"previous",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},ru=Ru(fg);function Ru(s){var e={};for(var t in s)s.hasOwnProperty(t)&&(e[s[t]]=t);return e}function Zn(s){var e={},t={};return Object.keys(s).forEach(function(i){var r=!1;if(s.hasOwnProperty(i)&&s[i]!==void 0){var n=i.split("_"),a=n[0],o=hg[a];o||(Te.info("Data key word `"+n[0]+"` not expected in "+i),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),ru[l]?o+=ru[l]:Number.isInteger(Number(l))?o+=l:(Te.info("Data key word `"+l+"` not expected in "+i),o+="_"+l+"_")}),r?t[o]=s[i]:e[o]=s[i]}}),Object.assign(e,t)}var mi=at(Tt()),mg=at(gu()),gg={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},pg=56*1024,yg=["hb","requestcompleted","requestfailed","requestcanceled"],vg="https://img.litix.io",Dt=function(s){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=s||vg,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},gg,e)};Dt.prototype.queueEvent=function(s,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||s==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Dt.prototype.flushEvents=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(s&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Dt.prototype.destroy=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,s?this._clearBeaconQueue():this.flushEvents(),mi.default.clearTimeout(this._sendTimeout)};Dt.prototype._clearBeaconQueue=function(){var s=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(s);s>0&&Object.assign(e[e.length-1],Zn({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);Iu(this._beaconUrl,t,!0,function(){})};Dt.prototype._sendBeaconQueue=function(){var s=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),i=Fe.now();Iu(this._beaconUrl,t,!1,function(r,n){n?(s._eventQueue=e.concat(s._eventQueue),s._failureCount+=1,Te.info("Error sending beacon: "+n)):s._failureCount=0,s._roundTripTime=Fe.now()-i,s._postInFlight=!1,s._resendAfterPost&&(s._resendAfterPost=!1,s._eventQueue.length>0&&s._sendBeaconQueue())})};Dt.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var s=Math.pow(2,this._failureCount-1);return s=s*Math.random(),(1+s)*this._options.baseTimeBetweenBeacons};Dt.prototype._startBeaconSending=function(){var s=this;mi.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=mi.default.setTimeout(function(){s._eventQueue.length&&s._sendBeaconQueue(),s._startBeaconSending()},this._getNextBeaconTime()))};Dt.prototype._createPayload=function(s){var e=this,t={transmission_timestamp:Math.round(Fe.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var i,r,n,a=function(){i=JSON.stringify({metadata:t,events:r||s}),n=i.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(Te.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=s.filter(function(l){return yg.indexOf(l.e)===-1}),a()),o()||(Te.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var u in l){var d=l[u],c=50*1024;typeof d=="string"&&d.length>c&&(l[u]=d.substring(0,c))}}),a()),i};var Eg=typeof mg.default.exitPictureInPicture=="function"?function(s){return s.length<=pg}:function(s){return!1},Iu=function(s,e,t,i){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(s,e)){i();return}if(mi.default.fetch){mi.default.fetch(s,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:Eg(e)}).then(function(n){return i(null,n.ok?null:"Error")}).catch(function(n){return i(null,n)});return}if(mi.default.XMLHttpRequest){var r=new mi.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return i(null,r.status!==200?"error":void 0)},r.open("POST",s),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}i()},Tg=Dt,_g=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception","view_playing_time_ms_cumulative","ad_playing_time_ms_cumulative"],Sg=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],bg=["ad_id","ad_creative_id","ad_universal_id"],Ag=["viewstart","error","ended","viewend"],xg=10*60*1e3,Rg=function(){"use strict";function s(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Pe(this,s);var r,n,a,o,l,u,d,c,h,f,m,p;B(this,"mux",void 0),B(this,"envKey",void 0),B(this,"options",void 0),B(this,"eventQueue",void 0),B(this,"sampleRate",void 0),B(this,"disableCookies",void 0),B(this,"respectDoNotTrack",void 0),B(this,"previousBeaconData",void 0),B(this,"lastEventTime",void 0),B(this,"rateLimited",void 0),B(this,"pageLevelData",void 0),B(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=i,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new Tg(lg(this.envKey,this.options));var g;this.sampleRate=(g=this.options.sampleRate)!==null&&g!==void 0?g:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var T;this.respectDoNotTrack=(T=this.options.respectDoNotTrack)!==null&&T!==void 0?T:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(d=this.options.platform)===null||d===void 0||(u=d.os)===null||u===void 0?void 0:u.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:dg(),page_url:Yn.default===null||Yn.default===void 0||(p=Yn.default.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:ag()}return ft(s,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Qn())return Te.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return Te.error("A data object was expected in send() but was not provided");var i=this.disableCookies?{}:og(),r=ea(ur({},this.pageLevelData,t,i,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=Zn(o);if(this.lastEventTime=this.mux.utils.now(),a)return Te.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||Te.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited)if(Te.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else{if(this.mux.WINDOW_HIDDEN&&e==="hb")this.eventQueue.flushEvents(!0);else if(Ag.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=Zn(r),this.eventQueue.queueEvent(r.event,l),Te.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var i=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=xg)r=ur({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=Lt(o,2),u=l[0],d=l[1];i.previousBeaconData&&(d!==i.previousBeaconData[u]||_g.indexOf(u)>-1||i.objectHasChanged(a,u,d,i.previousBeaconData[u])||i.eventRequiresKey(e,u))&&(r[u]=d,i.previousBeaconData[u]=d)})}return r}},{key:"objectHasChanged",value:function(e,t,i,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof i!="object"||typeof r!="object"?!0:Object.keys(i||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||bg.includes(t)&&Sg.includes(e))}}]),s}(),Ig=function s(e){"use strict";Pe(this,s);var t=0,i=0,r=0,n=0,a=0,o=0,l=0,u=function(h,f){var m=f.request_start,p=f.request_response_start,g=f.request_response_end,v=f.request_bytes_loaded;n++;var T,E;if(p?(T=p-(m!=null?m:0),E=(g!=null?g:0)-p):E=(g!=null?g:0)-(m!=null?m:0),E>0&&v&&v>0){var _=v/E*8e3;a++,i+=v,r+=E,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,_),e.data.view_average_request_throughput=i/r*8e3,e.data.view_request_count=n,T>0&&(t+=T,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,T),e.data.view_average_request_latency=t/a)}},d=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",u),e.on("requestfailed",d),e.on("requestcanceled",c)},Lg=Ig,Dg=60*60*1e3,kg=function s(e){"use strict";var t=this;Pe(this,s),B(this,"_lastEventTime",void 0),e.on("before*",function(i,r){var n=r.viewer_time,a=Fe.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>Dg){var l=Object.keys(e.data).reduce(function(d,c){return c.indexOf("video_")===0?Object.assign(d,B({},c,e.data[c])):d},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var u=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=u,e.playbackHeartbeat._playheadShouldBeProgressing&&i.type!=="play"&&i.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),i.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},Pg=kg,wg=function s(e){"use strict";Pe(this,s);var t=function(o){var l=Cg(o),u=Og(o);if(l!=null&&!nu(l,n)&&a<=u){n=l,a=u;var d={video_cdn:l};e.emit("cdnchange",d)}},i=null,r=null,n=null,a=0;e.on("viewinit",function(){i=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var u=l==null?void 0:l.video_cdn;u&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(nu(u,r)?l.video_previous_cdn=i!=null?i:void 0:(l.video_previous_cdn=r!=null?r:void 0,i=r,r=u))}),e.on("requestcompleted",function(o,l){t(l)})};function nu(s,e){return(s==null?void 0:s.toLowerCase())===(e==null?void 0:e.toLowerCase())}function Cg(s){var e;return s!=null&&s.request_type&&(s.request_type==="media"||s.request_type==="video")&&!((e=s.request_response_headers)===null||e===void 0)&&e["x-cdn"]?s.request_response_headers["x-cdn"]:s!=null&&s.video_cdn?s.video_cdn:null}function Og(s){return s!=null&&s.request_start?s.request_start:s!=null&&s.viewer_time?s.viewer_time:Date.now()}var Mg=wg,Ng=function(s){try{return JSON.parse(s),!0}catch{return!1}},Fg=function s(e){"use strict";var t=this;Pe(this,s),B(this,"_emittingAutomaticEvent",!1),B(this,"_hasInitialized",!1),B(this,"_currentMode","standard"),e.on("viewstart",function(){t._hasInitialized||(t._hasInitialized=!0,t._currentMode=e.data.player_playback_mode||"standard",t._emittingAutomaticEvent=!0,e.emit("playbackmodechange",{player_playback_mode:t._currentMode,player_playback_mode_data:"{}"}),t._emittingAutomaticEvent=!1)}),e.on("viewend",function(){t._hasInitialized=!1}),e.on("playbackmodechange",function(i,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?Ng(r.player_playback_mode_data)||(e.mux.log.warn("Invalid JSON string for player_playback_mode_data"),r.player_playback_mode_data="{}"):r.player_playback_mode_data="{}",e.data.player_playback_mode_data=r.player_playback_mode_data,e.data.player_playback_mode=r.player_playback_mode,t._currentMode=r.player_playback_mode)})},Ug=Fg,Bg=function(){"use strict";function s(e){Pe(this,s),B(this,"pm",void 0),B(this,"_currentRangeStart",void 0),B(this,"_lastPlayheadTime",void 0),this.pm=e,this._currentRangeStart=null,this._lastPlayheadTime=null,e.on("playbackheartbeat",this._updatePlaybackRange.bind(this)),e.on("playbackheartbeatend",this._endPlaybackRange.bind(this))}return ft(s,[{key:"_updateLastRangeEnd",value:function(){var e=this.pm.data.video_playback_ranges;if(e&&e.length>0){var t=this.pm.data.player_playhead_time||0;e[e.length-1][1]=t}}},{key:"_updatePlaybackRange",value:function(){var e,t=this.pm.data.player_playhead_time||0;if(!(!this.pm.disableAdPlaybackRangeFiltering&&!((e=this.pm.adTracker)===null||e===void 0)&&e.isAdBreak&&this._lastPlayheadTime!==null&&t<this._lastPlayheadTime)){if(this._lastPlayheadTime!==null&&this._currentRangeStart!==null){var i=Math.abs(t-this._lastPlayheadTime);if(i>1e3){var r=this.pm.data.video_playback_ranges;r&&r.length>0&&(r[r.length-1][1]=this._lastPlayheadTime),this._currentRangeStart=null}}if(this._currentRangeStart===null){var n=this.pm.data.video_playback_ranges||[];n.length>0&&n[n.length-1][1]===t?this._currentRangeStart=n[n.length-1][0]:(this._currentRangeStart=t,n.push([t,t])),this.pm.data.video_playback_ranges=n}else this._updateLastRangeEnd();this._lastPlayheadTime=t}}},{key:"_endPlaybackRange",value:function(){this._currentRangeStart!==null&&(this._updateLastRangeEnd(),this._currentRangeStart=null,this._lastPlayheadTime=null)}}]),s}(),$g=Bg,Gg=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange","cdnchange","playbackmodechange"],Kg=new Set(["requestcompleted","requestfailed","requestcanceled"]),Vg=function(s){"use strict";hm(t,s);var e=ym(t);function t(i,r,n){Pe(this,t);var a;a=e.call(this),B(J(a),"pageLoadEndTime",void 0),B(J(a),"pageLoadInitTime",void 0),B(J(a),"_destroyed",void 0),B(J(a),"_heartBeatTimeout",void 0),B(J(a),"adTracker",void 0),B(J(a),"dashjs",void 0),B(J(a),"data",void 0),B(J(a),"disablePlayheadRebufferTracking",void 0),B(J(a),"disableRebufferTracking",void 0),B(J(a),"disableAdPlaybackRangeFiltering",void 0),B(J(a),"errorTracker",void 0),B(J(a),"errorTranslator",void 0),B(J(a),"emitTranslator",void 0),B(J(a),"getAdData",void 0),B(J(a),"getPlayheadTime",void 0),B(J(a),"getStateData",void 0),B(J(a),"stateDataTranslator",void 0),B(J(a),"hlsjs",void 0),B(J(a),"id",void 0),B(J(a),"longResumeTracker",void 0),B(J(a),"minimumRebufferDuration",void 0),B(J(a),"mux",void 0),B(J(a),"playbackEventDispatcher",void 0),B(J(a),"playbackHeartbeat",void 0),B(J(a),"playbackHeartbeatTime",void 0),B(J(a),"playheadTime",void 0),B(J(a),"seekingTracker",void 0),B(J(a),"sustainedRebufferThreshold",void 0),B(J(a),"watchTimeTracker",void 0),B(J(a),"currentFragmentPDT",void 0),B(J(a),"currentFragmentStart",void 0),a.pageLoadInitTime=lr.navigationStart(),a.pageLoadEndTime=lr.domContentLoadedEventEnd();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,disableAdPlaybackRangeFiltering:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),m=0;m<h;m++)f[m]=arguments[m];return f},stateDataTranslator:function(h){return h}};a.mux=i,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),Te.level=n.debug?fi.DEBUG:fi.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.disableAdPlaybackRangeFiltering=n.disableAdPlaybackRangeFiltering,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new Rg(i,n.data.env_key,n),a.data={player_instance_id:vs(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(J(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var u=function(){var h=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",u,!1);var d=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",d,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",u),window.removeEventListener("pagehide",d)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),Gg.forEach(function(h){a.on(h,function(f,m){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,m),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),this.pageLoadInitTime=this.data.page_load_init_time||this.pageLoadInitTime,this.pageLoadEndTime=this.data.page_load_end_time||this.pageLoadEndTime,!this.mux.PLAYER_TRACKED&&this.pageLoadInitTime&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.pageLoadEndTime)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.pageLoadEndTime||1/0)-this.pageLoadInitTime)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new Pg(J(a)),a.errorTracker=new Mm(J(a)),new sg(J(a)),a.seekingTracker=new Jm(J(a)),a.playheadTime=new Gm(J(a)),a.playbackHeartbeat=new Cm(J(a)),new zm(J(a)),a.watchTimeTracker=new Fm(J(a)),new Bm(J(a)),new $g(J(a)),a.adTracker=new tg(J(a)),new qm(J(a)),new Vm(J(a)),new Ym(J(a)),new Lg(J(a)),new Mg(J(a)),new Ug(J(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return ft(t,[{key:"emit",value:function(i,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[i,a];if(this.emitTranslator)try{o=this.emitTranslator(i,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=ar(Ui(t.prototype),"emit",this)).call.apply(n,[this].concat(ct(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start!="undefined"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(i){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(u){r[u]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=Lt(Es(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,r.video_playback_ranges&&(r.video_playback_range=JSON.stringify(r.video_playback_ranges.filter(function(u){return u[0]!==u[1]}).map(function(u){return"".concat(u[0],":").concat(u[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(i,r),this.data.view_sequence_number++,this.data.player_sequence_number++,Kg.has(i)||this._restartHeartBeat(),i==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(i){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",i)}},{key:"_updateStateData",value:function(){var i,r=this.getStateData();if(typeof this.stateDataTranslator=="function")try{r=this.stateDataTranslator(r)}catch(o){this.mux.log.warn("Exception in stateDataTranslator translator callback.",o)}if(!((i=this.data)===null||i===void 0)&&i.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=mm(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var i=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(i.data[a],10);i.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(i.data[a]){var o=i.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(i.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete i.data[r]})}},{key:"_resetViewData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete i.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var i=this,r=this.data.view_id=vs(),n=function(){r===i.data.view_id&&we(i.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var i=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){i.data.player_is_paused||i.emit("hb")},1e4)}},{key:"addHLSJS",value:function(i){if(!i.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=i.hlsjs,bm(this.mux,this.id,i.hlsjs,{},i.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(Am(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(i){if(!i.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=i.dashjs,Lm(this.mux,this.id,i.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(Dm(this.dashjs),this.dashjs=void 0)}}]),t}(Pm),Hg=Vg,gs=at(gu());function jn(){return gs.default&&!!(gs.default.fullscreenElement||gs.default.webkitFullscreenElement||gs.default.mozFullScreenElement||gs.default.msFullscreenElement)}var qg=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],Wg={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function Yg(s,e,t){var i=Lt(or(e),3),r=i[0],n=i[1],a=i[2],o=s.log,l=s.utils.getComputedStyle,u=s.utils.secondsToMs,d={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return u(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||u(r.currentTime),v=this.hlsjs&&this.hlsjs.url,T=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),E={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:jn(),video_poster_url:r.poster,video_source_url:v||T||r.currentSrc,video_source_duration:u(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(p=r.getVideoPlaybackQuality)===null||p===void 0?void 0:p.call(r).droppedVideoFrames};if(r.getStartDate&&g>0){var _=r.getStartDate();if(_&&typeof _.getTime=="function"&&_.getTime()){var b=_.getTime();if(E.player_program_time=b+g,r.seekable.length>0){var x=b+r.seekable.end(r.seekable.length-1);E.player_live_edge_program_time=x}}}return E}};t=Object.assign(d,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:s.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){s.emit(n,f,m)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.fullscreenChangeListener&&(document.removeEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1),delete r.mux.fullscreenChangeListener),r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,s.emit(n,"destroy")},r.mux.swapElement=function(f){var m=Lt(or(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return s.log.error("The element of `"+g+"` was not a media element.")}else return s.log.error("No element was found with the `"+g+"` query selector.");p.muxId=r.muxId,delete r.muxId,p.mux=p.mux||{},p.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(p.mux.listeners).forEach(function(T){r.removeEventListener(T,p.mux.listeners[T],!1),p.addEventListener(T,p.mux.listeners[T],!1)}),p.mux.fullscreenChangeListener=r.mux.fullscreenChangeListener,delete r.mux.fullscreenChangeListener,p.mux.swapElement=r.mux.swapElement,p.mux.destroy=r.mux.destroy,delete r.mux,r=p},r.mux.addHLSJS=function(f){s.addHLSJS(n,f)},r.mux.addDashJS=function(f){s.addDashJS(n,f)},r.mux.removeHLSJS=function(){s.removeHLSJS(n)},r.mux.removeDashJS=function(){s.removeDashJS(n)},r.mux.setEmitTranslator=function(f){s.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){s.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),s.setGetPlayheadTime(n,f)},s.init(n,t),s.emit(n,"playerready"),r.paused||(s.emit(n,"play"),r.readyState>2&&s.emit(n,"playing")),r.mux.listeners={},qg.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var m={};if(f==="error"){if(!r.error||r.error.code===1)return;m.player_error_code=r.error.code,m.player_error_message=Wg[r.error.code]||r.error.message}s.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){s.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=jn()?"fullscreen":"standard";s.emit(n,"playbackmodechange",{player_playback_mode:f,player_playback_mode_data:"{}"})},r.addEventListener("enterpictureinpicture",r.mux.listeners.enterpictureinpicture,!1),r.addEventListener("leavepictureinpicture",r.mux.listeners.leavepictureinpicture,!1),r.mux.fullscreenChangeListener=function(){var f=jn(),m=document.fullscreenElement;if(f&&(m===r||m!=null&&m.contains(r)))s.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var p=document.pictureInPictureElement===r,g=p?"pip":"standard";s.emit(n,"playbackmodechange",{player_playback_mode:g,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function jg(s,e,t,i){var r=i;if(s&&typeof s[e]=="function")try{r=s[e].apply(s,t)}catch(n){Te.info("safeCall error",n)}return r}var ys=at(Tt()),Fi;ys.default&&ys.default.WeakMap&&(Fi=new WeakMap);function zg(s,e){if(!s||!e||!ys.default||typeof ys.default.getComputedStyle!="function")return"";var t;return Fi&&Fi.has(s)&&(t=Fi.get(s)),t||(t=ys.default.getComputedStyle(s,null),Fi&&Fi.set(s,t)),t.getPropertyValue(e)}function Xg(s){return Math.floor(s*1e3)}var hi={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},cr=function(s){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(s),this.manifest};cr.prototype.process=function(s){var e;for(this.buffer+=s,e=this.buffer.indexOf(`
|
|
11
|
+
`):"")+"".concat(T.err?"error message: ".concat((I=T.err)===null||I===void 0?void 0:I.message,`
|
|
12
|
+
`):"");l("error",{player_error_code:v,player_error_message:_,player_error_context:P})}};t.on(r.Events.ERROR,g);var m=function(y,T){var v=T.frag,_=v&&v._url||"";l("requestcanceled",{request_event_type:y,request_url:_,request_type:"media",request_hostname:Lt(_)})};t.on(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,m);var p=function(y,T){var v=T.level,_=t.levels[v];if(_&&_.attrs&&_.attrs.BANDWIDTH){var S=_.attrs.BANDWIDTH,A,b=parseFloat(_.attrs["FRAME-RATE"]);isNaN(b)||(A=b),S?l("renditionchange",{video_source_fps:A,video_source_bitrate:S,video_source_width:_.width,video_source_height:_.height,video_source_rendition_name:_.name,video_source_codec:_==null?void 0:_.videoCodec}):n.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(r.Events.LEVEL_SWITCHED,p),t._stopMuxMonitor=function(){t.off(r.Events.MANIFEST_LOADED,u),t.off(r.Events.LEVEL_LOADED,d),t.off(r.Events.AUDIO_TRACK_LOADED,c),t.off(r.Events.FRAG_LOADED,h),t.off(r.Events.FRAG_CHANGED,f),t.off(r.Events.ERROR,g),t.off(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,m),t.off(r.Events.LEVEL_SWITCHED,p),t.off(r.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(r.Events.DESTROYING,t._stopMuxMonitor)},zm=function(s){s&&typeof s._stopMuxMonitor=="function"&&s._stopMuxMonitor()},ju=function(s,e){if(!s||!s.requestEndDate)return{};var t=Lt(s.url),i=s.url,r=s.bytesLoaded,n=new Date(s.requestStartDate).getTime(),a=new Date(s.firstByteDate).getTime(),o=new Date(s.requestEndDate).getTime(),l=isNaN(s.duration)?0:s.duration,u=typeof e.getMetricsFor=="function"?e.getMetricsFor(s.mediaType).HttpList:e.getDashMetrics().getHttpRequests(s.mediaType),d;u.length>0&&(d=Ma(u[u.length-1]._responseHeaders||""));var c=d?Fr(d):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:d,requestMediaDuration:l,requestHostname:t,requestUrl:i,requestId:c}},Xm=function(s,e){var t=e.getQualityFor(s),i=e.getCurrentTrackFor(s).bitrateList;return i?{currentLevel:t,renditionWidth:i[t].width||null,renditionHeight:i[t].height||null,renditionBitrate:i[t].bandwidth}:{}},Qm=function(s){var e;return(e=s.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},Jm=function(s){try{var e,t,i=(t=s.getVersion)===null||t===void 0||(e=t.call(s))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return i}catch{return!1}},Zm=function(s,e,t){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=s.log;if(!t||!t.on){r.warn("Invalid dash.js player reference. Monitoring blocked.");return}var n=Jm(t),a=function(v,_){return s.emit(e,v,_)},o=function(v){var _=v.type,S=v.data,A=(S||{}).url;a("requestcompleted",{request_event_type:_,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:Lt(A),request_url:A})};t.on("manifestLoaded",o);var l={},u=function(v){if(typeof v.getRequests!="function")return null;var _=v.getRequests({state:"executed"});return _.length===0?null:_[_.length-1]},d=function(v){var _=v.type,S=v.fragmentModel,A=v.chunk,b=u(S);c({type:_,request:b,chunk:A})},c=function(v){var _=v.type,S=v.chunk,A=v.request,b=(S||{}).mediaInfo,x=b||{},L=x.type,R=x.bitrateList;R=R||[];var I={};R.forEach(function($,K){I[K]={},I[K].width=$.width,I[K].height=$.height,I[K].bitrate=$.bandwidth,I[K].attrs={}}),L==="video"?l.video=I:L==="audio"?l.audio=I:l.media=I;var P=ju(A,t),w=P.requestStart,B=P.requestResponseStart,U=P.requestResponseEnd,C=P.requestResponseHeaders,N=P.requestMediaDuration,F=P.requestHostname,G=P.requestUrl,W=P.requestId;a("requestcompleted",{request_event_type:_,request_start:w,request_response_start:B,request_response_end:U,request_bytes_loaded:-1,request_type:L+"_init",request_response_headers:C,request_hostname:F,request_id:W,request_url:G,request_media_duration:N,request_rendition_lists:l})};n>=4?t.on("initFragmentLoaded",c):t.on("initFragmentLoaded",d);var h=function(v){var _=v.type,S=v.fragmentModel,A=v.chunk,b=u(S);f({type:_,request:b,chunk:A})},f=function(v){var _=v.type,S=v.chunk,A=v.request,b=S||{},x=b.mediaInfo,L=b.start,R=x||{},I=R.type,P=ju(A,t),w=P.requestStart,B=P.requestResponseStart,U=P.requestResponseEnd,C=P.requestBytesLoaded,N=P.requestResponseHeaders,F=P.requestMediaDuration,G=P.requestHostname,W=P.requestUrl,$=P.requestId,K=Xm(I,t),se=K.currentLevel,ee=K.renditionWidth,ue=K.renditionHeight,ie=K.renditionBitrate;a("requestcompleted",{request_event_type:_,request_start:w,request_response_start:B,request_response_end:U,request_bytes_loaded:C,request_type:I,request_response_headers:N,request_hostname:G,request_id:$,request_url:W,request_media_start_time:L,request_media_duration:F,request_current_level:se,request_labeled_bitrate:ie,request_video_width:ee,request_video_height:ue})};n>=4?t.on("mediaFragmentLoaded",f):t.on("mediaFragmentLoaded",h);var g={video:void 0,audio:void 0,totalBitrate:void 0},m=function(){if(g.video&&typeof g.video.bitrate=="number"){if(!(g.video.width&&g.video.height)){r.warn("have bitrate info for video but missing width/height");return}var v=g.video.bitrate;if(g.audio&&typeof g.audio.bitrate=="number"&&(v+=g.audio.bitrate),v!==g.totalBitrate)return g.totalBitrate=v,{video_source_bitrate:v,video_source_height:g.video.height,video_source_width:g.video.width,video_source_codec:Qm(g.video.codec)}}},p=function(v,_,S){if(typeof v.newQuality!="number"){r.warn("missing evt.newQuality in qualityChangeRendered event",v);return}var A=v.mediaType;if(A==="audio"||A==="video"){var b=t.getBitrateInfoListFor(A).find(function(L){var R=L.qualityIndex;return R===v.newQuality});if(!(b&&typeof b.bitrate=="number")){r.warn("missing bitrate info for ".concat(A));return}g[A]=Oa(Nr({},b),{codec:t.getCurrentTrackFor(A).codec});var x=m();x&&a("renditionchange",x)}};t.on("qualityChangeRendered",p);var y=function(v){var _=v.request,S=v.mediaType;_=_||{},a("requestcanceled",{request_event_type:_.type+"_"+_.action,request_url:_.url,request_type:S,request_hostname:Lt(_.url)})};t.on("fragmentLoadingAbandoned",y);var T=function(v){var _=v.error,S,A,b=(_==null||(S=_.data)===null||S===void 0?void 0:S.request)||{},x=(_==null||(A=_.data)===null||A===void 0?void 0:A.response)||{};(_==null?void 0:_.code)===27&&a("requestfailed",{request_error:b.type+"_"+b.action,request_url:b.url,request_hostname:Lt(b.url),request_type:b.mediaType,request_error_code:x.status,request_error_text:x.statusText});var L="".concat(b!=null&&b.url?"url: ".concat(b.url,`
|
|
13
|
+
`):"")+"".concat(x!=null&&x.status||x!=null&&x.statusText?"response: ".concat(x==null?void 0:x.status,", ").concat(x==null?void 0:x.statusText,`
|
|
14
|
+
`):"");a("error",{player_error_code:_==null?void 0:_.code,player_error_message:_==null?void 0:_.message,player_error_context:L})};t.on("error",T),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",p),t.off("error",T),t.off("fragmentLoadingAbandoned",y),delete t._stopMuxMonitor}},ep=function(s){s&&typeof s._stopMuxMonitor=="function"&&s._stopMuxMonitor()},zu=0,tp=function(){"use strict";function s(){He(this,s),V(this,"_listeners",void 0)}return Dt(s,[{key:"on",value:function(e,t,i){return t._eventEmitterGuid=t._eventEmitterGuid||++zu,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],i&&(t=t.bind(i)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var i=this._listeners&&this._listeners[e];i&&i.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&i.splice(n,1)})}},{key:"one",value:function(e,t,i){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++zu;var n=function(){r.off(e,n),t.apply(i||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var i=this;if(this._listeners){t=t||{};var r=this._listeners["before"+e]||[],n=this._listeners["before*"]||[],a=this._listeners[e]||[],o=this._listeners["after"+e]||[],l=function(u,d){u=u.slice(),u.forEach(function(c){c.call(i,{type:e},d)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),s}(),ip=tp,xa=Tt(Bt()),sp=function(){"use strict";function s(e){var t=this;He(this,s),V(this,"_playbackHeartbeatInterval",void 0),V(this,"_playheadShouldBeProgressing",void 0),V(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(i,r){t._playbackHeartbeatInterval!==null&&(xa.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return Dt(s,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=xa.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(xa.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),s}(),rp=sp,np=function s(e){"use strict";var t=this;He(this,s),V(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(i,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var i,r,n,a,o;(i=e.data)===null||i===void 0||delete i.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},ap=np,op=function(){"use strict";function s(e){He(this,s),V(this,"_watchTimeTrackerLastCheckedTime",void 0),V(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return Dt(s,[{key:"_updateWatchTime",value:function(e,t){var i=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=i),Ye(this.pm.data,"view_watch_time",i-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=i}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),s}(),lp=op,up=function(){"use strict";function s(e){var t=this;He(this,s),V(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),V(this,"_lastTime",void 0),V(this,"_isAdPlaying",void 0),V(this,"_callbackUpdatePlaybackTime",void 0),V(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=ze.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var i=this._startPlaybackTimeTracking.bind(this);e.on("playing",i),e.on("adplaying",i),e.on("seeked",i),e.on("rebufferend",i);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("rebufferstart",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=ze.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return Dt(s,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=ze.now(),this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time||0,t=ze.now(),i=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=i),r>0&&r<=1e3&&Ye(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&i>0&&i<=1e3&&(this._isAdPlaying&&Ye(this.pm.data,"ad_playing_time_ms_cumulative",i),Ye(this.pm.data,"view_playing_time_ms_cumulative",i)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),s}(),dp=up,cp=function(){"use strict";function s(e){He(this,s),V(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return Dt(s,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position=="undefined"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var i=this,r=function(){i.pm.currentFragmentPDT&&i.pm.currentFragmentStart&&(i.pm.data.player_program_time=i.pm.currentFragmentPDT+i.pm.data.player_playhead_time-i.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n!="undefined"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),s}(),hp=cp,Xu=5*60*1e3,fp=function s(e){"use strict";if(He(this,s),!e.disableRebufferTracking){var t,i=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;Ye(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>Xu&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(Xu,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(Ye(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",i))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",i)})}},gp=fp,mp=function(){"use strict";function s(e){var t=this;He(this,s),V(this,"_lastCheckedTime",void 0),V(this,"_lastPlayheadTime",void 0),V(this,"_lastPlayheadTimeUpdatedTime",void 0),V(this,"_rebuffering",void 0),V(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:ze.now()})}))}return Dt(s,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var i=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&i>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}i?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),s}(),pp=mp,vp=function(){"use strict";function s(e){var t=this;He(this,s),V(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var i=e.data,r=i.view_id;if(!i.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame=="undefined"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame=="undefined"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||ze.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return Dt(s,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.pm.pageLoadInitTime&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.pm.pageLoadInitTime))}}]),s}(),yp=vp,Ep=function s(e){"use strict";var t=this;He(this,s),V(this,"_lastPlayerHeight",void 0),V(this,"_lastPlayerWidth",void 0),V(this,"_lastPlayheadPosition",void 0),V(this,"_lastSourceHeight",void 0),V(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var i=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];i.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),u=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,u),Ye(e.data,"view_total_content_playback_time",a),Ye(e.data,"view_total_upscaling",l*a),Ye(e.data,"view_total_downscaling",u*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},Tp=Ep,_p=2e3,Sp=function s(e){"use strict";var t=this;He(this,s),V(this,"isSeeking",void 0),this.isSeeking=!1;var i=-1,r=function(){var n=ze.now(),a=(e.data.viewer_time||n)-(i||n);Ye(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,i=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-i<=_p){i=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,i=a.viewer_time,Ye(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,i=-1})},bp=Sp,Qu=function(s,e){s.push(e),s.sort(function(t,i){return t.viewer_time-i.viewer_time})},Ap=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],Rp=function(){"use strict";function s(e){var t=this;He(this,s),V(this,"_adHasPlayed",void 0),V(this,"_adRequests",void 0),V(this,"_adResponses",void 0),V(this,"_currentAdRequestNumber",void 0),V(this,"_currentAdResponseNumber",void 0),V(this,"_prerollPlayTime",void 0),V(this,"_wouldBeNewAdPlay",void 0),V(this,"isAdBreak",void 0),V(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),Ap.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var i=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",i),e.on("playing",i),e.on("viewend",i),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),Qu(t._adRequests,n),Ye(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||Ye(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),Qu(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&Ye(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,Ye(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time=="undefined"&&typeof t._prerollPlayTime!="undefined"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||Ye(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||Ye(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return Dt(s,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var i=zt(Ns(t.ad_tag_url),2),r=i[0],n=i[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=zt(Ns(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}this.pm.data.ad_type="preroll"}this.pm.data.ad_asset_url=t==null?void 0:t.ad_asset_url,this.pm.data.ad_tag_url=t==null?void 0:t.ad_tag_url,this.pm.data.ad_creative_id=t==null?void 0:t.ad_creative_id,this.pm.data.ad_id=t==null?void 0:t.ad_id,this.pm.data.ad_universal_id=t==null?void 0:t.ad_universal_id,t!=null&&t.ad_type&&(this.pm.data.ad_type=t==null?void 0:t.ad_type)}}]),s}(),xp=Rp,Ip=function s(e){"use strict";var t=this;He(this,s),V(this,"lastWallClockTime",void 0);var i=function(){t.lastWallClockTime=ze.now(),e.on("before*",r)},r=function(n){var a=ze.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",i),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",i)})},Lp=Ip,Ia=Tt(Bt()),gd=function(s){return s()}(function(){var s=function(){for(var t=0,i={};t<arguments.length;t++){var r=arguments[t];for(var n in r)i[n]=r[n]}return i};function e(t){function i(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=s({path:"/"},i.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var u=document.cookie?document.cookie.split("; "):[],d=/(%[0-9A-Z]{2})+/g,c=0;c<u.length;c++){var h=u[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var g=h[0].replace(d,decodeURIComponent);if(f=t.read?t.read(f,g):t(f,g)||f.replace(d,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===g){o=f;break}r||(o[g]=f)}catch{}}return o}}return i.set=i,i.get=function(r){return i.call(i,r)},i.getJSON=function(){return i.apply({json:!0},[].slice.call(arguments))},i.defaults={},i.remove=function(r,n){i(r,"",s(n,{expires:-1}))},i.withConverter=e,i}return e(function(){})}),md="muxData",Dp=function(s){return Object.entries(s).map(function(e){var t=zt(e,2),i=t[0],r=t[1];return"".concat(i,"=").concat(r)}).join("&")},kp=function(s){return s.split("&").reduce(function(e,t){var i=zt(t.split("="),2),r=i[0],n=i[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},pd=function(){var s;try{s=kp(gd.get(md)||"")}catch{s={}}return s},vd=function(s){try{gd.set(md,Dp(s),{expires:365})}catch{}},Pp=function(){var s=pd();return s.mux_viewer_id=s.mux_viewer_id||Ms(),s.msn=s.msn||Math.random(),vd(s),{mux_viewer_id:s.mux_viewer_id,mux_sample_number:s.msn}},Cp=function(){var s=pd(),e=ze.now();return s.session_start&&(s.sst=s.session_start,delete s.session_start),s.session_id&&(s.sid=s.session_id,delete s.session_id),s.session_expires&&(s.sex=s.session_expires,delete s.session_expires),(!s.sex||s.sex<e)&&(s.sid=Ms(),s.sst=e),s.sex=e+25*60*1e3,vd(s),{session_id:s.sid,session_start:s.sst,session_expires:s.sex}};function wp(s,e){var t=e.beaconCollectionDomain,i=e.beaconDomain;if(t)return"https://"+t;s=s||"inferred";var r=i||"litix.io";return s.match(/^[a-z0-9]+$/)?"https://"+s+"."+r:"https://img.litix.io/a.gif"}var Op=Tt(Bt()),yd=function(){var s;switch(Ed()){case"cellular":s="cellular";break;case"ethernet":s="wired";break;case"wifi":s="wifi";break;case void 0:break;default:s="other"}return s},Ed=function(){var s=Op.default.navigator,e=s&&(s.connection||s.mozConnection||s.webkitConnection);return e&&e.type};yd.getConnectionFromAPI=Ed;var Mp=yd,Np={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},Fp=Td(Np),Bp={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cm:"cmcd",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cv:"cumulative",cx:"connection",cz:"context",da:"data",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mp:"mode",ms:"ms",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",pv:"previous",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},Ju=Td(Bp);function Td(s){var e={};for(var t in s)s.hasOwnProperty(t)&&(e[s[t]]=t);return e}function wa(s){var e={},t={};return Object.keys(s).forEach(function(i){var r=!1;if(s.hasOwnProperty(i)&&s[i]!==void 0){var n=i.split("_"),a=n[0],o=Fp[a];o||(De.info("Data key word `"+n[0]+"` not expected in "+i),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),Ju[l]?o+=Ju[l]:Number.isInteger(Number(l))?o+=l:(De.info("Data key word `"+l+"` not expected in "+i),o+="_"+l+"_")}),r?t[o]=s[i]:e[o]=s[i]}}),Object.assign(e,t)}var Ni=Tt(Bt()),Up=Tt(ud()),$p={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},Gp=56*1024,Kp=["hb","requestcompleted","requestfailed","requestcanceled"],Vp="https://img.litix.io",Xt=function(s){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=s||Vp,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},$p,e)};Xt.prototype.queueEvent=function(s,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||s==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Xt.prototype.flushEvents=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(s&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Xt.prototype.destroy=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,s?this._clearBeaconQueue():this.flushEvents(),Ni.default.clearTimeout(this._sendTimeout)};Xt.prototype._clearBeaconQueue=function(){var s=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(s);s>0&&Object.assign(e[e.length-1],wa({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);_d(this._beaconUrl,t,!0,function(){})};Xt.prototype._sendBeaconQueue=function(){var s=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),i=ze.now();_d(this._beaconUrl,t,!1,function(r,n){n?(s._eventQueue=e.concat(s._eventQueue),s._failureCount+=1,De.info("Error sending beacon: "+n)):s._failureCount=0,s._roundTripTime=ze.now()-i,s._postInFlight=!1,s._resendAfterPost&&(s._resendAfterPost=!1,s._eventQueue.length>0&&s._sendBeaconQueue())})};Xt.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var s=Math.pow(2,this._failureCount-1);return s=s*Math.random(),(1+s)*this._options.baseTimeBetweenBeacons};Xt.prototype._startBeaconSending=function(){var s=this;Ni.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=Ni.default.setTimeout(function(){s._eventQueue.length&&s._sendBeaconQueue(),s._startBeaconSending()},this._getNextBeaconTime()))};Xt.prototype._createPayload=function(s){var e=this,t={transmission_timestamp:Math.round(ze.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var i,r,n,a=function(){i=JSON.stringify({metadata:t,events:r||s}),n=i.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(De.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=s.filter(function(l){return Kp.indexOf(l.e)===-1}),a()),o()||(De.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var u in l){var d=l[u],c=50*1024;typeof d=="string"&&d.length>c&&(l[u]=d.substring(0,c))}}),a()),i};var Hp=typeof Up.default.exitPictureInPicture=="function"?function(s){return s.length<=Gp}:function(s){return!1},_d=function(s,e,t,i){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(s,e)){i();return}if(Ni.default.fetch){Ni.default.fetch(s,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:Hp(e)}).then(function(n){return i(null,n.ok?null:"Error")}).catch(function(n){return i(null,n)});return}if(Ni.default.XMLHttpRequest){var r=new Ni.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return i(null,r.status!==200?"error":void 0)},r.open("POST",s),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}i()},qp=Xt,Wp=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception","view_playing_time_ms_cumulative","ad_playing_time_ms_cumulative"],Yp=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],jp=["ad_id","ad_creative_id","ad_universal_id"],zp=["viewstart","error","ended","viewend"],Xp=10*60*1e3,Qp=function(){"use strict";function s(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};He(this,s);var r,n,a,o,l,u,d,c,h,f,g,m;V(this,"mux",void 0),V(this,"envKey",void 0),V(this,"options",void 0),V(this,"eventQueue",void 0),V(this,"sampleRate",void 0),V(this,"disableCookies",void 0),V(this,"respectDoNotTrack",void 0),V(this,"previousBeaconData",void 0),V(this,"lastEventTime",void 0),V(this,"rateLimited",void 0),V(this,"pageLevelData",void 0),V(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=i,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new qp(wp(this.envKey,this.options));var p;this.sampleRate=(p=this.options.sampleRate)!==null&&p!==void 0?p:1;var y;this.disableCookies=(y=this.options.disableCookies)!==null&&y!==void 0?y:!1;var T;this.respectDoNotTrack=(T=this.options.respectDoNotTrack)!==null&&T!==void 0?T:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(d=this.options.platform)===null||d===void 0||(u=d.os)===null||u===void 0?void 0:u.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(g=this.options.platform)===null||g===void 0||(f=g.os)===null||f===void 0?void 0:f.version,viewer_connection_type:Mp(),page_url:Ia.default===null||Ia.default===void 0||(m=Ia.default.location)===null||m===void 0?void 0:m.href},this.viewerData=this.disableCookies?{}:Pp()}return Dt(s,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Pa())return De.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return De.error("A data object was expected in send() but was not provided");var i=this.disableCookies?{}:Cp(),r=Oa(Nr({},this.pageLevelData,t,i,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=wa(o);if(this.lastEventTime=this.mux.utils.now(),a)return De.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||De.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited)if(De.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else{if(this.mux.WINDOW_HIDDEN&&e==="hb")this.eventQueue.flushEvents(!0);else if(zp.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=wa(r),this.eventQueue.queueEvent(r.event,l),De.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var i=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=Xp)r=Nr({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=zt(o,2),u=l[0],d=l[1];i.previousBeaconData&&(d!==i.previousBeaconData[u]||Wp.indexOf(u)>-1||i.objectHasChanged(a,u,d,i.previousBeaconData[u])||i.eventRequiresKey(e,u))&&(r[u]=d,i.previousBeaconData[u]=d)})}return r}},{key:"objectHasChanged",value:function(e,t,i,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof i!="object"||typeof r!="object"?!0:Object.keys(i||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||jp.includes(t)&&Yp.includes(e))}}]),s}(),Jp=function s(e){"use strict";He(this,s);var t=0,i=0,r=0,n=0,a=0,o=0,l=0,u=function(h,f){var g=f.request_start,m=f.request_response_start,p=f.request_response_end,y=f.request_bytes_loaded;n++;var T,v;if(m?(T=m-(g!=null?g:0),v=(p!=null?p:0)-m):v=(p!=null?p:0)-(g!=null?g:0),v>0&&y&&y>0){var _=y/v*8e3;a++,i+=y,r+=v,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,_),e.data.view_average_request_throughput=i/r*8e3,e.data.view_request_count=n,T>0&&(t+=T,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,T),e.data.view_average_request_latency=t/a)}},d=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",u),e.on("requestfailed",d),e.on("requestcanceled",c)},Zp=Jp,e0=60*60*1e3,t0=function s(e){"use strict";var t=this;He(this,s),V(this,"_lastEventTime",void 0),e.on("before*",function(i,r){var n=r.viewer_time,a=ze.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>e0){var l=Object.keys(e.data).reduce(function(d,c){return c.indexOf("video_")===0?Object.assign(d,V({},c,e.data[c])):d},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var u=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=u,e.playbackHeartbeat._playheadShouldBeProgressing&&i.type!=="play"&&i.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),i.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},i0=t0,s0=function s(e){"use strict";He(this,s);var t=function(o){var l=r0(o),u=n0(o);if(l!=null&&!Zu(l,n)&&a<=u){n=l,a=u;var d={video_cdn:l};e.emit("cdnchange",d)}},i=null,r=null,n=null,a=0;e.on("viewinit",function(){i=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var u=l==null?void 0:l.video_cdn;u&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(Zu(u,r)?l.video_previous_cdn=i!=null?i:void 0:(l.video_previous_cdn=r!=null?r:void 0,i=r,r=u))}),e.on("requestcompleted",function(o,l){t(l)})};function Zu(s,e){return(s==null?void 0:s.toLowerCase())===(e==null?void 0:e.toLowerCase())}function r0(s){var e;return s!=null&&s.request_type&&(s.request_type==="media"||s.request_type==="video")&&!((e=s.request_response_headers)===null||e===void 0)&&e["x-cdn"]?s.request_response_headers["x-cdn"]:s!=null&&s.video_cdn?s.video_cdn:null}function n0(s){return s!=null&&s.request_start?s.request_start:s!=null&&s.viewer_time?s.viewer_time:Date.now()}var a0=s0,o0=function(s){try{return JSON.parse(s),!0}catch{return!1}},l0=function s(e){"use strict";var t=this;He(this,s),V(this,"_emittingAutomaticEvent",!1),V(this,"_hasInitialized",!1),V(this,"_currentMode","standard"),e.on("viewstart",function(){t._hasInitialized||(t._hasInitialized=!0,t._currentMode=e.data.player_playback_mode||"standard",t._emittingAutomaticEvent=!0,e.emit("playbackmodechange",{player_playback_mode:t._currentMode,player_playback_mode_data:"{}"}),t._emittingAutomaticEvent=!1)}),e.on("viewend",function(){t._hasInitialized=!1}),e.on("playbackmodechange",function(i,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?o0(r.player_playback_mode_data)||(e.mux.log.warn("Invalid JSON string for player_playback_mode_data"),r.player_playback_mode_data="{}"):r.player_playback_mode_data="{}",e.data.player_playback_mode_data=r.player_playback_mode_data,e.data.player_playback_mode=r.player_playback_mode,t._currentMode=r.player_playback_mode)})},u0=l0,d0=function(){"use strict";function s(e){He(this,s),V(this,"pm",void 0),V(this,"_currentRangeStart",void 0),V(this,"_lastPlayheadTime",void 0),this.pm=e,this._currentRangeStart=null,this._lastPlayheadTime=null,e.on("playbackheartbeat",this._updatePlaybackRange.bind(this)),e.on("playbackheartbeatend",this._endPlaybackRange.bind(this))}return Dt(s,[{key:"_updateLastRangeEnd",value:function(){var e=this.pm.data.video_playback_ranges;if(e&&e.length>0){var t=this.pm.data.player_playhead_time||0;e[e.length-1][1]=t}}},{key:"_updatePlaybackRange",value:function(){var e,t=this.pm.data.player_playhead_time||0;if(!(!this.pm.disableAdPlaybackRangeFiltering&&!((e=this.pm.adTracker)===null||e===void 0)&&e.isAdBreak&&this._lastPlayheadTime!==null&&t<this._lastPlayheadTime)){if(this._lastPlayheadTime!==null&&this._currentRangeStart!==null){var i=Math.abs(t-this._lastPlayheadTime);if(i>1e3){var r=this.pm.data.video_playback_ranges;r&&r.length>0&&(r[r.length-1][1]=this._lastPlayheadTime),this._currentRangeStart=null}}if(this._currentRangeStart===null){var n=this.pm.data.video_playback_ranges||[];n.length>0&&n[n.length-1][1]===t?this._currentRangeStart=n[n.length-1][0]:(this._currentRangeStart=t,n.push([t,t])),this.pm.data.video_playback_ranges=n}else this._updateLastRangeEnd();this._lastPlayheadTime=t}}},{key:"_endPlaybackRange",value:function(){this._currentRangeStart!==null&&(this._updateLastRangeEnd(),this._currentRangeStart=null,this._lastPlayheadTime=null)}}]),s}(),c0=d0,h0=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange","cdnchange","playbackmodechange"],f0=new Set(["requestcompleted","requestfailed","requestcanceled"]),g0=function(s){"use strict";Fm(t,s);var e=Km(t);function t(i,r,n){He(this,t);var a;a=e.call(this),V(ae(a),"pageLoadEndTime",void 0),V(ae(a),"pageLoadInitTime",void 0),V(ae(a),"_destroyed",void 0),V(ae(a),"_heartBeatTimeout",void 0),V(ae(a),"adTracker",void 0),V(ae(a),"dashjs",void 0),V(ae(a),"data",void 0),V(ae(a),"disablePlayheadRebufferTracking",void 0),V(ae(a),"disableRebufferTracking",void 0),V(ae(a),"disableAdPlaybackRangeFiltering",void 0),V(ae(a),"errorTracker",void 0),V(ae(a),"errorTranslator",void 0),V(ae(a),"emitTranslator",void 0),V(ae(a),"getAdData",void 0),V(ae(a),"getPlayheadTime",void 0),V(ae(a),"getStateData",void 0),V(ae(a),"stateDataTranslator",void 0),V(ae(a),"hlsjs",void 0),V(ae(a),"id",void 0),V(ae(a),"longResumeTracker",void 0),V(ae(a),"minimumRebufferDuration",void 0),V(ae(a),"mux",void 0),V(ae(a),"playbackEventDispatcher",void 0),V(ae(a),"playbackHeartbeat",void 0),V(ae(a),"playbackHeartbeatTime",void 0),V(ae(a),"playheadTime",void 0),V(ae(a),"seekingTracker",void 0),V(ae(a),"sustainedRebufferThreshold",void 0),V(ae(a),"watchTimeTracker",void 0),V(ae(a),"currentFragmentPDT",void 0),V(ae(a),"currentFragmentStart",void 0),a.pageLoadInitTime=Mr.navigationStart(),a.pageLoadEndTime=Mr.domContentLoadedEventEnd();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,disableAdPlaybackRangeFiltering:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),g=0;g<h;g++)f[g]=arguments[g];return f},stateDataTranslator:function(h){return h}};a.mux=i,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),De.level=n.debug?Mi.DEBUG:Mi.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.disableAdPlaybackRangeFiltering=n.disableAdPlaybackRangeFiltering,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new Qp(i,n.data.env_key,n),a.data={player_instance_id:Ms(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(ae(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var u=function(){var h=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",u,!1);var d=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",d,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",u),window.removeEventListener("pagehide",d)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),h0.forEach(function(h){a.on(h,function(f,g){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,g),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),this.pageLoadInitTime=this.data.page_load_init_time||this.pageLoadInitTime,this.pageLoadEndTime=this.data.page_load_end_time||this.pageLoadEndTime,!this.mux.PLAYER_TRACKED&&this.pageLoadInitTime&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.pageLoadEndTime)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.pageLoadEndTime||1/0)-this.pageLoadInitTime)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new i0(ae(a)),a.errorTracker=new ap(ae(a)),new Lp(ae(a)),a.seekingTracker=new bp(ae(a)),a.playheadTime=new hp(ae(a)),a.playbackHeartbeat=new rp(ae(a)),new Tp(ae(a)),a.watchTimeTracker=new lp(ae(a)),new dp(ae(a)),new c0(ae(a)),a.adTracker=new xp(ae(a)),new pp(ae(a)),new gp(ae(a)),new yp(ae(a)),new Zp(ae(a)),new a0(ae(a)),new u0(ae(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return Dt(t,[{key:"emit",value:function(i,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[i,a];if(this.emitTranslator)try{o=this.emitTranslator(i,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=wr(ns(t.prototype),"emit",this)).call.apply(n,[this].concat(It(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start!="undefined"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(i){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(u){r[u]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=zt(Ns(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,r.video_playback_ranges&&(r.video_playback_range=JSON.stringify(r.video_playback_ranges.filter(function(u){return u[0]!==u[1]}).map(function(u){return"".concat(u[0],":").concat(u[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(i,r),this.data.view_sequence_number++,this.data.player_sequence_number++,f0.has(i)||this._restartHeartBeat(),i==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(i){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",i)}},{key:"_updateStateData",value:function(){var i,r=this.getStateData();if(typeof this.stateDataTranslator=="function")try{r=this.stateDataTranslator(r)}catch(o){this.mux.log.warn("Exception in stateDataTranslator translator callback.",o)}if(!((i=this.data)===null||i===void 0)&&i.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=Um(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var i=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(i.data[a],10);i.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(i.data[a]){var o=i.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(i.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete i.data[r]})}},{key:"_resetViewData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete i.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var i=this,r=this.data.view_id=Ms(),n=function(){r===i.data.view_id&&Ye(i.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var i=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){i.data.player_is_paused||i.emit("hb")},1e4)}},{key:"addHLSJS",value:function(i){if(!i.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=i.hlsjs,jm(this.mux,this.id,i.hlsjs,{},i.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(zm(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(i){if(!i.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=i.dashjs,Zm(this.mux,this.id,i.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(ep(this.dashjs),this.dashjs=void 0)}}]),t}(ip),m0=g0,Cs=Tt(ud());function La(){return Cs.default&&!!(Cs.default.fullscreenElement||Cs.default.webkitFullscreenElement||Cs.default.mozFullScreenElement||Cs.default.msFullscreenElement)}var p0=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],v0={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function y0(s,e,t){var i=zt(Or(e),3),r=i[0],n=i[1],a=i[2],o=s.log,l=s.utils.getComputedStyle,u=s.utils.secondsToMs,d={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return u(r.currentTime)},getStateData:function(){var f,g,m,p=((f=(g=this).getPlayheadTime)===null||f===void 0?void 0:f.call(g))||u(r.currentTime),y=this.hlsjs&&this.hlsjs.url,T=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),v={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:La(),video_poster_url:r.poster,video_source_url:y||T||r.currentSrc,video_source_duration:u(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(m=r.getVideoPlaybackQuality)===null||m===void 0?void 0:m.call(r).droppedVideoFrames};if(r.getStartDate&&p>0){var _=r.getStartDate();if(_&&typeof _.getTime=="function"&&_.getTime()){var S=_.getTime();if(v.player_program_time=S+p,r.seekable.length>0){var A=S+r.seekable.end(r.seekable.length-1);v.player_live_edge_program_time=A}}}return v}};t=Object.assign(d,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:s.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,g){s.emit(n,f,g)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.fullscreenChangeListener&&(document.removeEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1),delete r.mux.fullscreenChangeListener),r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,s.emit(n,"destroy")},r.mux.swapElement=function(f){var g=zt(Or(f),3),m=g[0],p=g[1],y=g[2];if(m){if(y!=="video"&&y!=="audio")return s.log.error("The element of `"+p+"` was not a media element.")}else return s.log.error("No element was found with the `"+p+"` query selector.");m.muxId=r.muxId,delete r.muxId,m.mux=m.mux||{},m.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(m.mux.listeners).forEach(function(T){r.removeEventListener(T,m.mux.listeners[T],!1),m.addEventListener(T,m.mux.listeners[T],!1)}),m.mux.fullscreenChangeListener=r.mux.fullscreenChangeListener,delete r.mux.fullscreenChangeListener,m.mux.swapElement=r.mux.swapElement,m.mux.destroy=r.mux.destroy,delete r.mux,r=m},r.mux.addHLSJS=function(f){s.addHLSJS(n,f)},r.mux.addDashJS=function(f){s.addDashJS(n,f)},r.mux.removeHLSJS=function(){s.removeHLSJS(n)},r.mux.removeDashJS=function(){s.removeDashJS(n)},r.mux.setEmitTranslator=function(f){s.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){s.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),s.setGetPlayheadTime(n,f)},s.init(n,t),s.emit(n,"playerready"),r.paused||(s.emit(n,"play"),r.readyState>2&&s.emit(n,"playing")),r.mux.listeners={},p0.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var g={};if(f==="error"){if(!r.error||r.error.code===1)return;g.player_error_code=r.error.code,g.player_error_message=v0[r.error.code]||r.error.message}s.emit(n,f,g)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){s.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=La()?"fullscreen":"standard";s.emit(n,"playbackmodechange",{player_playback_mode:f,player_playback_mode_data:"{}"})},r.addEventListener("enterpictureinpicture",r.mux.listeners.enterpictureinpicture,!1),r.addEventListener("leavepictureinpicture",r.mux.listeners.leavepictureinpicture,!1),r.mux.fullscreenChangeListener=function(){var f=La(),g=document.fullscreenElement;if(f&&(g===r||g!=null&&g.contains(r)))s.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var m=document.pictureInPictureElement===r,p=m?"pip":"standard";s.emit(n,"playbackmodechange",{player_playback_mode:p,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function E0(s,e,t,i){var r=i;if(s&&typeof s[e]=="function")try{r=s[e].apply(s,t)}catch(n){De.info("safeCall error",n)}return r}var Os=Tt(Bt()),rs;Os.default&&Os.default.WeakMap&&(rs=new WeakMap);function T0(s,e){if(!s||!e||!Os.default||typeof Os.default.getComputedStyle!="function")return"";var t;return rs&&rs.has(s)&&(t=rs.get(s)),t||(t=Os.default.getComputedStyle(s,null),rs&&rs.set(s,t)),t.getPropertyValue(e)}function _0(s){return Math.floor(s*1e3)}var Oi={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},Br=function(s){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(s),this.manifest};Br.prototype.process=function(s){var e;for(this.buffer+=s,e=this.buffer.indexOf(`
|
|
15
15
|
`);e>-1;e=this.buffer.indexOf(`
|
|
16
|
-
`))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};cr.prototype.processLine=function(s){var e=s.indexOf(":"),t=ep(s,e),i=t[0],r=t.length===2?ia(t[1]):void 0;if(i[0]!=="#")this.currentUri.uri=i,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(i){case hi.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case hi.PART_INF:{zn(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case hi.SERVER_CONTROL:{zn(this.manifest,t),this.setHoldBack();break}case hi.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case hi.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case hi.VERSION:{zn(this.manifest,t);break}case hi.SESSION_DATA:{var o=tp(t[1]),l=Eu(o);Object.assign(this.manifest.sessionData,l)}}};cr.prototype.setHoldBack=function(){var s=this.manifest,e=s.serverControl,t=s.targetDuration,i=s.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),i&&!e.hasOwnProperty(n)&&(e[n]=i*3),i&&e[n]<o&&(e[n]=o)}};var zn=function(s,e){var t=Lu(e[0].replace("#EXT-X-","")),i;Zg(e[1])?(i={},i=Object.assign(Jg(e[1]),i)):i=ia(e[1]),s[t]=i},Lu=function(s){return s.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},ia=function(s){if(s.toLowerCase()==="yes"||s.toLowerCase()==="no")return s.toLowerCase()==="yes";var e=s.indexOf(":")!==-1?s:parseFloat(s);return isNaN(e)?s:e},Qg=function(s){var e={},t=s.split("=");if(t.length>1){var i=Lu(t[0]);e[i]=ia(t[1])}return e},Jg=function(s){for(var e=s.split(","),t={},i=0;e.length>i;i++){var r=e[i],n=Qg(r);t=Object.assign(n,t)}return t},Zg=function(s){return s.indexOf("=")>-1},ep=function(s,e){return e===-1?[s]:[s.substring(0,e),s.substring(e+1)]},tp=function(s){var e={};if(s){var t=s.search(","),i=s.slice(0,t),r=s.slice(t+1),n=[i,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),u=0;u<l.length;u++)l[u]==="DATA-ID"&&(e["DATA-ID"]=l[1-u]),l[u]==="VALUE"&&(e.VALUE=l[1-u])}),{data:e}}},ip=cr,sp={safeCall:jg,safeIncrement:we,getComputedStyle:zg,secondsToMs:Xg,assign:Object.assign,headersStringToObject:ta,cdnHeadersToRequestId:dr,extractHostnameAndDomain:Es,extractHostname:ht,manifestParser:ip,generateShortID:yu,generateUUID:vs,now:Fe.now,findMediaElement:or},rp=sp,np={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",PLAYBACK_MODE_CHANGE:"playbackmodechange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},ap=np,op="mux-embed",lp="5.16.1",up="2.1",ke={},Gt=function(s){var e=arguments;typeof s=="string"?Gt.hasOwnProperty(s)?ps.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),Gt[s].apply(null,e)},0):Te.warn("`"+s+"` is an unknown task"):typeof s=="function"?ps.default.setTimeout(function(){s(Gt)},0):Te.warn("`"+s+"` is invalid.")},dp={loaded:Fe.now(),NAME:op,VERSION:lp,API_VERSION:up,PLAYER_TRACKED:!1,monitor:function(s,e){return Yg(Gt,s,e)},destroyMonitor:function(s){var e=Lt(or(s),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():Te.error("A video element monitor for `"+s+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(s,e){var t=dt(s);ke[t]?ke[t].addHLSJS(e):Te.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(s,e){var t=dt(s);ke[t]?ke[t].addDashJS(e):Te.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(s){var e=dt(s);ke[e]?ke[e].removeHLSJS():Te.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(s){var e=dt(s);ke[e]?ke[e].removeDashJS():Te.error("A monitor for `"+e+"` has not been initialized.")},init:function(s,e){Qn()&&e&&e.respectDoNotTrack&&Te.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=dt(s);ke[t]=new Hg(Gt,t,e)},emit:function(s,e,t){var i=dt(s);ke[i]?(ke[i].emit(e,t),e==="destroy"&&delete ke[i]):Te.error("A monitor for `"+i+"` has not been initialized.")},updateData:function(s,e){var t=dt(s);ke[t]?ke[t].emit("hb",e):Te.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(s,e){var t=dt(s);ke[t]?ke[t].emitTranslator=e:Te.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(s,e){var t=dt(s);ke[t]?ke[t].stateDataTranslator=e:Te.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(s,e){var t=dt(s);ke[t]?ke[t].getPlayheadTime=e:Te.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Qn,log:Te,utils:rp,events:ap,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(Gt,dp);typeof ps.default!="undefined"&&typeof ps.default.addEventListener=="function"&&ps.default.addEventListener("pagehide",function(s){s.persisted||(Gt.WINDOW_UNLOADING=!0)},!1);var hr=Gt;var V=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},cp=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=hp},hp=Number.MAX_SAFE_INTEGER||9007199254740991,z=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),k=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),y=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({}),ae={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Ht=class{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){let 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_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},xa=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ht(e),this.fast_=new Ht(t),this.defaultTTFB_=r,this.ttfb_=new Ht(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new Ht(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new Ht(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Ht(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){let 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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function fp(s,e,t){return(e=gp(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Ee(){return Ee=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},Ee.apply(null,arguments)}function Du(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function ge(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Du(Object(t),!0).forEach(function(i){fp(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Du(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function mp(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function gp(s){var e=mp(s,"string");return typeof e=="symbol"?e:e+""}var Je=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=qt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},qt=function(){},pp={trace:qt,debug:qt,log:qt,warn:qt,info:qt,error:qt};function Ra(){return Ee({},pp)}function yp(s,e){let t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):qt}function ku(s,e,t){return e[s]?e[s].bind(e):yp(s,t)}var Ia=Ra();function vp(s,e,t){let i=Ra();if(typeof console=="object"&&s===!0||typeof s=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=ku(n,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Ra()}r.forEach(n=>{Ia[n]=ku(n,s)})}else Ee(Ia,i);return i}var pe=Ia;function Wt(s=!0){return typeof self=="undefined"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ep(s){return typeof self!="undefined"&&s===self.ManagedMediaSource}function Gd(s,e){let t=Object.keys(s),i=Object.keys(e),r=t.length,n=i.length;return!r||!n||r===n&&!t.some(a=>i.indexOf(a)===-1)}function it(s,e=!1){if(typeof TextDecoder!="undefined"){let u=new TextDecoder("utf-8").decode(s);if(e){let d=u.indexOf("\0");return d!==-1?u.substring(0,d):u}return u.replace(/\0/g,"")}let t=s.length,i,r,n,a="",o=0;for(;o<t;){if(i=s[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=s[o++],a+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=s[o++],n=s[o++],a+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function Ge(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function Kd(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Tp(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var sa={exports:{}},Pu;function _p(){return Pu||(Pu=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,d){if(d=d||{},l=l.trim(),u=u.trim(),!u){if(!d.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(u);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return d.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):u;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var g=f.path,v=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var u=i.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()}(sa)),sa.exports}var Ho=_p(),Rs=class{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}}},_e={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Or=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Sp(this,"stats")}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[_e.AUDIO]:null,[_e.VIDEO]:null,[_e.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Rs),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ho.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[_e.AUDIO]=null,e[_e.VIDEO]=null,e[_e.AUDIOVIDEO]=null}};function Le(s){return s.sn!=="initSegment"}var Ss=class extends Or{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(V(e)&&V(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=V(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){var t;let i=Object.keys(this.levelkeys),r=i.length;if(r>1||r===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!V(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Le(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},La=class extends Or{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function Vd(s,e){let t=Object.getPrototypeOf(s);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||Vd(t,e)}}function Sp(s,e){let t=Vd(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}var wu=Math.pow(2,32)-1,bp=[].push,Hd={video:1,audio:2,id3:3,text:4};function Ce(s){return String.fromCharCode.apply(null,s)}function qd(s,e){let t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Z(s,e){let t=Wd(s,e);return t<0?4294967296+t:t}function Cu(s,e){let t=Z(s,e);return t*=Math.pow(2,32),t+=Z(s,e+4),t}function Wd(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function Ap(s){let e=s.byteLength;for(let t=0;t<e;){let i=Z(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function re(s,e){let t=[];if(!e.length)return t;let i=s.byteLength;for(let r=0;r<i;){let n=Z(s,r),a=Ce(s.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else{let l=re(s.subarray(r+8,o),e.slice(1));l.length&&bp.apply(t,l)}r=o}return t}function xp(s){let e=[],t=s[0],i=8,r=Z(s,i);i+=4;let n=0,a=0;t===0?(n=Z(s,i),a=Z(s,i+4),i+=8):(n=Cu(s,i),a=Cu(s,i+8),i+=16),i+=2;let o=s.length+a,l=qd(s,i);i+=2;for(let u=0;u<l;u++){let d=i,c=Z(s,d);d+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return pe.warn("SIDX has hierarchical references (not supported)"),null;let m=Z(s,d);d+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,d+=4,i=d}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function Yd(s){let e=[],t=re(s,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=re(n,["tkhd"])[0];if(a){let o=a[0],l=Z(a,o===0?12:20),u=re(n,["mdia","mdhd"])[0];if(u){o=u[0];let d=Z(u,o===0?12:20),c=re(n,["mdia","hdlr"])[0];if(c){let h=Ce(c.subarray(8,12)),f={soun:_e.AUDIO,vide:_e.VIDEO}[h],m=re(n,["mdia","minf","stbl","stsd"])[0],p=Rp(m);f?(e[l]={timescale:d,type:f,stsd:p},e[f]=ge({timescale:d,id:l},p)):e[l]={timescale:d,type:h,stsd:p}}}}}return re(s,["moov","mvex","trex"]).forEach(r=>{let n=Z(r,4),a=e[n];a&&(a.default={duration:Z(r,12),flags:Z(r,20)})}),e}function Rp(s){let e=s.subarray(8),t=e.subarray(86),i=Ce(e.subarray(4,8)),r=i,n,a=i==="enca"||i==="encv";if(a){let u=re(e,[i])[0].subarray(i==="enca"?28:78);re(u,["sinf"]).forEach(c=>{let h=re(c,["schm"])[0];if(h){let f=Ce(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=re(c,["frma"])[0];m&&(r=Ce(m))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=re(t,["avcC"])[0];l&&l.length>3&&(r+="."+mr(l[1])+mr(l[2])+mr(l[3]),n=fr(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=re(e,[i])[0],u=re(l.subarray(28),["esds"])[0];if(u&&u.length>7){let d=4;if(u[d++]!==3)break;d=ra(u,d),d+=2;let c=u[d++];if(c&128&&(d+=2),c&64&&(d+=u[d++]),u[d++]!==4)break;d=ra(u,d);let h=u[d++];if(h===64)r+="."+mr(h);else break;if(d+=12,u[d++]!==5)break;d=ra(u,d);let f=u[d++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((u[d]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{let l=re(t,["hvcC"])[0];if(l&&l.length>12){let u=l[1],d=["","A","B","C"][u>>6],c=u&31,h=Z(l,2),f=(u&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+d+c,r+="."+Ip(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){let T=p[v];(T||g)&&(g="."+T.toString(16).toUpperCase()+g)}r+=g}n=fr(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=fr(r,t)||r;break}case"vp09":{let l=re(t,["vpcC"])[0];if(l&&l.length>6){let u=l[4],d=l[5],c=l[6]>>4&15;r+="."+bt(u)+"."+bt(d)+"."+bt(c)}break}case"av01":{let l=re(t,["av1C"])[0];if(l&&l.length>2){let u=l[1]>>>5,d=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=u===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;r+="."+u+"."+bt(d)+c+"."+bt(m)+"."+p+"."+g+v+T+"."+bt(1)+"."+bt(1)+"."+bt(1)+"."+0,n=fr("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function fr(s,e){let t=re(e,["dvvC"]),i=t.length?t[0]:re(e,["dvcC"])[0];if(i){let r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return s+"."+bt(r)+"."+bt(n)}}function Ip(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function ra(s,e){let t=e+5;for(;s[e++]&128&&e<t;);return e}function mr(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function bt(s){return(s<10?"0":"")+s}function Lp(s,e){if(!s||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&jd(s,(i,r)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(pe.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Ge(n)} -> ${Ge(t)}`),i.set(t,8))})}function Dp(s){let e=[];return jd(s,t=>e.push(t.subarray(8,24))),e}function jd(s,e){re(s,["moov","trak"]).forEach(i=>{let r=re(i,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=re(n,["enca"]),o=a.length>0;o||(a=re(n,["encv"])),a.forEach(l=>{let u=o?l.subarray(28):l.subarray(78);re(u,["sinf"]).forEach(c=>{let h=zd(c);h&&e(h,o)})})})}function zd(s){let e=re(s,["schm"])[0];if(e){let t=Ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=re(s,["schi","tenc"])[0];if(i)return i}}}function kp(s,e,t){let i={},r=re(s,["moof","traf"]);for(let n=0;n<r.length;n++){let a=r[n],o=re(a,["tfhd"])[0],l=Z(o,4),u=e[l];if(!u)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});let d=i[l],c=re(a,["tfdt"])[0];if(c){let E=c[0],_=Z(c,4);E===1&&(_===wu?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(_*=wu+1,_+=Z(c,8))),V(_)&&(!V(d.start)||_<d.start)&&(d.start=_)}let h=u.default,f=Z(o,0)|(h==null?void 0:h.flags),m=(h==null?void 0:h.duration)||0;f&8&&(f&2?m=Z(o,12):m=Z(o,8));let p=re(a,["trun"]),g=d.start||0,v=0,T=m;for(let E=0;E<p.length;E++){let _=p[E],b=Z(_,4),x=d.sampleCount;d.sampleCount+=b;let S=_[3]&1,R=_[3]&4,I=_[2]&1,A=_[2]&2,L=_[2]&4,P=_[2]&8,O=8,N=b;for(S&&(O+=4),R&&b&&(!(_[O+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=x),O+=4,I?(T=Z(_,O),O+=4):T=m,A&&(O+=4),P&&(O+=4),g+=T,v+=T,N--);N--;)I?(T=Z(_,O),O+=4):T=m,A&&(O+=4),L&&(_[O+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(N+1),d.keyFrameStart=g),O+=4),P&&(O+=4),g+=T,v+=T;!v&&m&&(v+=m*b)}d.duration+=v}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,a=0,o=re(s,["sidx"]);for(let l=0;l<o.length;l++){let u=xp(o[l]);if(u!=null&&u.references){n=Math.min(n,u.earliestPresentationTime/u.timescale);let d=u.references.reduce((c,h)=>c+h.info.duration||0,0);a=Math.max(a,d+u.earliestPresentationTime/u.timescale)}}a&&V(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start)})}return i}function Pp(s){let e={valid:null,remainder:null},t=re(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function ot(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Ou(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,a=!1;return re(i,["moof"]).map(l=>{let u=l.byteOffset-8;re(l,["traf"]).map(c=>{let h=re(c,["tfdt"]).map(f=>{let m=f[0],p=Z(f,4);return m===1&&(p*=Math.pow(2,32),p+=Z(f,8)),p/r})[0];return h!==void 0&&(s=h),re(c,["tfhd"]).map(f=>{let m=Z(f,4),p=Z(f,0)&16777215,g=(p&1)!==0,v=(p&2)!==0,T=(p&8)!==0,E=0,_=(p&16)!==0,b=0,x=(p&32)!==0,S=8;m===n&&(g&&(S+=8),v&&(S+=4),T&&(E=Z(f,S),S+=4),_&&(b=Z(f,S),S+=4),x&&(S+=4),e.type==="video"&&(a=on(e.codec)),re(c,["trun"]).map(R=>{let I=R[0],A=Z(R,0)&16777215,L=(A&1)!==0,P=0,O=(A&4)!==0,N=(A&256)!==0,F=0,M=(A&512)!==0,G=0,K=(A&1024)!==0,Y=(A&2048)!==0,Q=0,$=Z(R,4),U=8;L&&(P=Z(R,U),U+=4),O&&(U+=4);let ee=P+u;for(let he=0;he<$;he++){if(N?(F=Z(R,U),U+=4):F=E,M?(G=Z(R,U),U+=4):G=b,K&&(U+=4),Y&&(I===0?Q=Z(R,U):Q=Wd(R,U),U+=4),e.type===_e.VIDEO){let te=0;for(;te<G;){let oe=Z(i,ee);if(ee+=4,wp(a,i[ee])){let Ve=i.subarray(ee,ee+oe);qo(Ve,a?2:1,s+Q/r,t)}ee+=oe,te+=oe+4}}s+=F/r}}))})})}),t}function on(s){if(!s)return!1;let e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function wp(s,e){if(s){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function qo(s,e,t,i){let r=Xd(s),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);let u=r.length-n,d=n;if(o<u)n+=o;else if(o>u){pe.error(`Malformed SEI payload. ${o} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(r[d++]===181){let h=qd(r,d);if(d+=2,h===49){let f=Z(r,d);if(d+=4,f===1195456820){let m=r[d++];if(m===3){let p=r[d++],g=31&p,v=64&p,T=v?2+g*3:0,E=new Uint8Array(T);if(v){E[0]=p;for(let _=1;_<T;_++)E[_]=r[d++]}i.push({type:m,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){let c=[];for(let m=0;m<16;m++){let p=r[d++].toString(16);c.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&c.push("-")}let h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[d++];i.push({payloadType:a,pts:t,uuid:c.join(""),userData:it(f),userDataBytes:f})}}}function Xd(s){let e=s.byteLength,t=[],i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;let r=e-t.length,n=new Uint8Array(r),a=0;for(i=0;i<r;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=s[a];return n}function Cp(s){let e=s[0],t="",i="",r=0,n=0,a=0,o=0,l=0,u=0;if(e===0){for(;Ce(s.subarray(u,u+1))!=="\0";)t+=Ce(s.subarray(u,u+1)),u+=1;for(t+=Ce(s.subarray(u,u+1)),u+=1;Ce(s.subarray(u,u+1))!=="\0";)i+=Ce(s.subarray(u,u+1)),u+=1;i+=Ce(s.subarray(u,u+1)),u+=1,r=Z(s,12),n=Z(s,16),o=Z(s,20),l=Z(s,24),u=28}else if(e===1){u+=4,r=Z(s,u),u+=4;let c=Z(s,u);u+=4;let h=Z(s,u);for(u+=4,a=2**32*c+h,cp(a)||(a=Number.MAX_SAFE_INTEGER,pe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Z(s,u),u+=4,l=Z(s,u),u+=4;Ce(s.subarray(u,u+1))!=="\0";)t+=Ce(s.subarray(u,u+1)),u+=1;for(t+=Ce(s.subarray(u,u+1)),u+=1;Ce(s.subarray(u,u+1))!=="\0";)i+=Ce(s.subarray(u,u+1)),u+=1;i+=Ce(s.subarray(u,u+1)),u+=1}let d=s.subarray(u,s.byteLength);return{schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:d}}function Op(s,...e){let t=e.length,i=8,r=t;for(;r--;)i+=e[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function Mp(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Op([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t)}function Np(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32<t;){let r=new DataView(s,i),n=Fp(r);e.push(n),i+=n.size}}return e}function Fp(s){let e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return{offset:t,size:i};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};let n=s.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=s.buffer,o=Ge(new Uint8Array(a,t+12,16)),l=null,u=null,d=0;if(n===0)d=28;else{let h=s.getUint32(28);if(!h||i<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));d=32+h*16}if(!d)return{offset:t,size:e};let c=s.getUint32(d);return e-32<c?{offset:t,size:e}:(u=new Uint8Array(a,t+d+4,c),{version:n,systemId:o,kids:l,data:u,offset:t,size:e})}var Qd=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Xi={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Wo(s,e){let t=Xi[e];return!!t&&!!t[s.slice(0,4)]}function Is(s,e,t=!0){return!s.split(",").some(i=>!Yo(i,e,t))}function Yo(s,e,t=!0){var i;let r=Wt(t);return(i=r==null?void 0:r.isTypeSupported(Ls(s,e)))!=null?i:!1}function Ls(s,e){return`${e}/mp4;codecs=${s}`}function Mu(s){if(s){let e=s.substring(0,4);return Xi.video[e]}return 2}function Mr(s){let e=Qd();return s.split(",").reduce((t,i)=>{let n=e&&on(i)?9:Xi.video[i];return n?(n*2+t)/(t?3:2):(Xi.audio[i]+t)/(t?2:1)},0)}var na={};function Up(s,e=!0){if(na[s])return na[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let r=0;r<t.length;r++){var i;if(Yo(t[r],"audio",e))return na[s]=t[r],t[r];if(t[r]==="mp3"&&(i=Wt(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return s}var Bp=/flac|opus|mp4a\.40\.34/i;function Nr(s,e=!0){return s.replace(Bp,t=>Up(t.toLowerCase(),e))}function $p(s,e){let t=[];if(s){let i=s.split(",");for(let r=0;r<i.length;r++)Wo(i[r],"video")||t.push(i[r])}return e&&t.push(e),t.join(",")}function Ir(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(Nu(s,"audio")||Nu(s,"video")))return s;if(e){let t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function Nu(s,e){return Wo(s,e)&&Yo(s,e)}function Gp(s){let e=s.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Kp(s){if(s.startsWith("av01.")){let e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function Fu(s){let e=Wt(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Da(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Vp={supported:!0,powerEfficient:!0,smooth:!0},Hp={supported:!1,smooth:!1,powerEfficient:!1},Jd={supported:!0,configurations:[],decodingInfoResults:[Vp]};function Zd(s,e){return{supported:!1,configurations:e,decodingInfoResults:[Hp],error:s}}function qp(s,e,t,i,r,n){let a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=n==null?void 0:n.audioCodec,u=n==null?void 0:n.channels,d=u?parseInt(u):l?1/0:2,c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>on(h))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!c&&V(d)&&Object.keys(c).some(h=>parseInt(h)>d)}function ec(s,e,t,i={}){let r=s.videoCodec;if(!r&&!s.audioCodec||!t)return Promise.resolve(Jd);let n=[],a=Wp(s),o=a.length,l=Yp(s,e,o>0),u=l.length;for(let d=o||1*u||1;d--;){let c={type:"media-source"};if(o&&(c.video=a[d%o]),u){c.audio=l[d%u];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let d=navigator.userAgent;if(r.split(",").some(c=>on(c))&&Qd())return Promise.resolve(Zd(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),n))}return Promise.all(n.map(d=>{let c=zp(d);return i[c]||(i[c]=t.decodingInfo(d))})).then(d=>({supported:!d.some(c=>!c.supported),configurations:n,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:n,decodingInfoResults:[],error:d}))}function Wp(s){var e;let t=(e=s.videoCodec)==null?void 0:e.split(","),i=tc(s),r=s.width||640,n=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{let u={contentType:Ls(Kp(l),"video"),width:r,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(u.transferFunction=o),u}):[]}function Yp(s,e,t){var i;let r=(i=s.audioCodec)==null?void 0:i.split(","),n=tc(s);return r&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;let u=o?(l=e.groups[o])==null?void 0:l.tracks:null;return u?u.reduce((d,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let m={contentType:Ls(f,"audio"),bitrate:t?jp(f,n):n};h&&(m.channels=""+h),d.push(m)})}return d},a):a},[]):[]}function jp(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function tc(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function zp(s){let e="",{audio:t,video:i}=s;if(i){let r=Da(i.contentType);e+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){let r=Da(t.contentType);e+=`${i?"_":""}${r}_c${t.channels}`}return e}var ka=["NONE","TYPE-0","TYPE-1",null];function Xp(s){return ka.indexOf(s)>-1}var Fr=["SDR","PQ","HLG"];function Qp(s){return!!s&&Fr.indexOf(s)>-1}var Lr={No:"",Yes:"YES",v2:"v2"};function Uu(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i<e/2;return e&&r?t?Lr.v2:Lr.Yes:Lr.No}var Ur=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},bi=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Bu(this._audioGroups,e)}hasSubtitleGroup(e){return Bu(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Bu(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function Jp(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function Zp(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Fr.slice(0);let r=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&Jp(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}var e0=s=>{let e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},Se=(s,e)=>JSON.stringify(s,e0(e));function t0(s,e,t,i,r){let n=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=r==null?void 0:r.videoCodec,u=a&&parseInt(a)===2,d=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[],{preferHDR:T,allowedVideoRanges:E}=Zp(e,r);for(let R=n.length;R--;){let I=s[n[R]];d||(d=I.channels[2]>0),h=Math.min(h,I.minHeight),f=Math.min(f,I.minFramerate),m=Math.min(m,I.minBitrate),E.filter(L=>I.videoRanges[L]>0).length>0&&(c=!0)}h=V(h)?h:0,f=V(f)?f:0;let _=Math.max(1080,h),b=Math.max(30,f);m=V(m)?m:t,t=Math.max(m,t),c||(e=void 0);let x=n.length>1;return{codecSet:n.reduce((R,I)=>{let A=s[I];if(I===R)return R;if(v=c?E.filter(L=>A.videoRanges[L]>0):[],x){if(A.minBitrate>t)return _t(I,`min bitrate of ${A.minBitrate} > current estimate of ${t}`),R;if(!A.hasDefaultAudio)return _t(I,"no renditions with default or auto-select sound found"),R;if(o&&I.indexOf(o.substring(0,4))%5!==0)return _t(I,`audio codec preference "${o}" not found`),R;if(a&&!u){if(!A.channels[a])return _t(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(A.channels)})`),R}else if((!o||u)&&d&&A.channels[2]===0)return _t(I,"no renditions with stereo sound found"),R;if(A.minHeight>_)return _t(I,`min resolution of ${A.minHeight} > maximum of ${_}`),R;if(A.minFramerate>b)return _t(I,`min framerate of ${A.minFramerate} > maximum of ${b}`),R;if(!v.some(L=>A.videoRanges[L]>0))return _t(I,`no variants with VIDEO-RANGE of ${Se(v)} found`),R;if(l&&I.indexOf(l.substring(0,4))%5!==0)return _t(I,`video codec preference "${l}" not found`),R;if(A.maxScore<g)return _t(I,`max score of ${A.maxScore} < selected max of ${g}`),R}return R&&(Mr(I)>=Mr(R)||A.fragmentError>s[R].fragmentError)?R:(p=A.minIndex,g=A.maxScore,I)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:m,minIndex:p}}function _t(s,e){pe.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function ic(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function i0(s,e,t,i){return s.slice(t,i+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let u=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,u),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(d=>{if(!d)return;let c=e.groups[d];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function $u(s){if(!s)return s;let{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}=s;return{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}}function xt(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){let r=e[i];if(_i(s,r,t))return i}return-1}function _i(s,e,t){let{groupId:i,name:r,lang:n,assocLang:a,default:o}=s,l=s.forced;return(i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||s0(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||r0(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function s0(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function r0(s,e=""){let t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function Ei(s,e){let{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function n0(s,e,t,i,r){let n=e[i],o=e.reduce((h,f,m)=>{let p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,u=n.frameRate,d=n.codecSet.substring(0,4),c=Gu(e,i,h=>{if(h.videoRange!==l||h.frameRate!==u||h.codecSet.substring(0,4)!==d)return!1;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return xt(s,m,r)>-1});return c>-1?c:Gu(e,i,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return xt(s,m,r)>-1})}function Gu(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}function Br(s,e){var t;return!!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Pa=class extends Je{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let u=performance.now(),d=n?n.stats:r.stats,c=n?n.duration:r.duration,h=u-d.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let g=p>-1&&p!==m,v=!!t||g;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let E=this.bwEstimator.getEstimateTTFB(),_=Math.abs(l.playbackRate);if(h<=Math.max(E,1e3*(c/(_*2))))return;let b=T?T.len/_:0,x=d.loading.first?d.loading.first-d.loading.start:-1,S=d.loaded&&x>-1,R=this.getBwEstimate(),I=a.levels,A=I[m],L=Math.max(d.loaded,Math.round(c*(r.bitrate||A.averageBitrate)/8)),P=S?h-x:h;P<1&&S&&(P=Math.min(h,d.loaded*8/R));let O=S?d.loaded*1e3/P:0,N=E/1e3,F=O?(L-d.loaded)/O:L*8/R+N;if(F<=b)return;let M=O?O*8:R,G=((i=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,K=this.hls.config.abrBandWidthUpFactor,Y=Number.POSITIVE_INFINITY,Q;for(Q=m-1;Q>f;Q--){let he=I[Q].maxBitrate,te=!I[Q].details||G;if(Y=this.getTimeToLoadFrag(N,M,c*he,te),Y<Math.min(b,c+N))break}if(Y>=F||Y>c*10)return;S?this.bwEstimator.sample(h-Math.min(E,x),d.loaded):this.bwEstimator.sampleTTFB(h);let $=I[Q].maxBitrate;this.getBwEstimate()*K>$&&this.resetEstimator($);let U=this.findBestLevel($,f,Q,0,b,1,1);U>-1&&(Q=U),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
|
|
16
|
+
`))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};Br.prototype.processLine=function(s){var e=s.indexOf(":"),t=R0(s,e),i=t[0],r=t.length===2?Na(t[1]):void 0;if(i[0]!=="#")this.currentUri.uri=i,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(i){case Oi.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case Oi.PART_INF:{Da(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case Oi.SERVER_CONTROL:{Da(this.manifest,t),this.setHoldBack();break}case Oi.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case Oi.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case Oi.VERSION:{Da(this.manifest,t);break}case Oi.SESSION_DATA:{var o=x0(t[1]),l=fd(o);Object.assign(this.manifest.sessionData,l)}}};Br.prototype.setHoldBack=function(){var s=this.manifest,e=s.serverControl,t=s.targetDuration,i=s.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),i&&!e.hasOwnProperty(n)&&(e[n]=i*3),i&&e[n]<o&&(e[n]=o)}};var Da=function(s,e){var t=Sd(e[0].replace("#EXT-X-","")),i;A0(e[1])?(i={},i=Object.assign(b0(e[1]),i)):i=Na(e[1]),s[t]=i},Sd=function(s){return s.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},Na=function(s){if(s.toLowerCase()==="yes"||s.toLowerCase()==="no")return s.toLowerCase()==="yes";var e=s.indexOf(":")!==-1?s:parseFloat(s);return isNaN(e)?s:e},S0=function(s){var e={},t=s.split("=");if(t.length>1){var i=Sd(t[0]);e[i]=Na(t[1])}return e},b0=function(s){for(var e=s.split(","),t={},i=0;e.length>i;i++){var r=e[i],n=S0(r);t=Object.assign(n,t)}return t},A0=function(s){return s.indexOf("=")>-1},R0=function(s,e){return e===-1?[s]:[s.substring(0,e),s.substring(e+1)]},x0=function(s){var e={};if(s){var t=s.search(","),i=s.slice(0,t),r=s.slice(t+1),n=[i,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),u=0;u<l.length;u++)l[u]==="DATA-ID"&&(e["DATA-ID"]=l[1-u]),l[u]==="VALUE"&&(e.VALUE=l[1-u])}),{data:e}}},I0=Br,L0={safeCall:E0,safeIncrement:Ye,getComputedStyle:T0,secondsToMs:_0,assign:Object.assign,headersStringToObject:Ma,cdnHeadersToRequestId:Fr,extractHostnameAndDomain:Ns,extractHostname:Lt,manifestParser:I0,generateShortID:cd,generateUUID:Ms,now:ze.now,findMediaElement:Or},D0=L0,k0={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",PLAYBACK_MODE_CHANGE:"playbackmodechange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},P0=k0,C0="mux-embed",w0="5.16.1",O0="2.1",Ve={},li=function(s){var e=arguments;typeof s=="string"?li.hasOwnProperty(s)?ws.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),li[s].apply(null,e)},0):De.warn("`"+s+"` is an unknown task"):typeof s=="function"?ws.default.setTimeout(function(){s(li)},0):De.warn("`"+s+"` is invalid.")},M0={loaded:ze.now(),NAME:C0,VERSION:w0,API_VERSION:O0,PLAYER_TRACKED:!1,monitor:function(s,e){return y0(li,s,e)},destroyMonitor:function(s){var e=zt(Or(s),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():De.error("A video element monitor for `"+s+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(s,e){var t=xt(s);Ve[t]?Ve[t].addHLSJS(e):De.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(s,e){var t=xt(s);Ve[t]?Ve[t].addDashJS(e):De.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(s){var e=xt(s);Ve[e]?Ve[e].removeHLSJS():De.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(s){var e=xt(s);Ve[e]?Ve[e].removeDashJS():De.error("A monitor for `"+e+"` has not been initialized.")},init:function(s,e){Pa()&&e&&e.respectDoNotTrack&&De.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=xt(s);Ve[t]=new m0(li,t,e)},emit:function(s,e,t){var i=xt(s);Ve[i]?(Ve[i].emit(e,t),e==="destroy"&&delete Ve[i]):De.error("A monitor for `"+i+"` has not been initialized.")},updateData:function(s,e){var t=xt(s);Ve[t]?Ve[t].emit("hb",e):De.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(s,e){var t=xt(s);Ve[t]?Ve[t].emitTranslator=e:De.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(s,e){var t=xt(s);Ve[t]?Ve[t].stateDataTranslator=e:De.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(s,e){var t=xt(s);Ve[t]?Ve[t].getPlayheadTime=e:De.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Pa,log:De,utils:D0,events:P0,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(li,M0);typeof ws.default!="undefined"&&typeof ws.default.addEventListener=="function"&&ws.default.addEventListener("pagehide",function(s){s.persisted||(li.WINDOW_UNLOADING=!0)},!1);var Ur=li;var H=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},N0=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=F0},F0=Number.MAX_SAFE_INTEGER||9007199254740991,Q=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),k=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",s.UNKNOWN="unknown",s}({}),E=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});function B0(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Fa={exports:{}},bd;function U0(){return bd||(bd=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,d){if(d=d||{},l=l.trim(),u=u.trim(),!u){if(!d.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(u);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return d.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):u;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=r.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(m.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)m.path=f.path,h.params||(m.params=f.params,h.query||(m.query=f.query));else{var p=f.path,y=p.substring(0,p.lastIndexOf("/")+1)+h.path;m.path=o.normalizePath(y)}return m.path===null&&(m.path=d.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(m)},parseURL:function(l){var u=i.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()}(Fa)),Fa.exports}var Ml=U0(),js=class{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}}},de=function(s){return s.MANIFEST="manifest",s.LEVEL="level",s.AUDIO_TRACK="audioTrack",s.SUBTITLE_TRACK="subtitleTrack",s.MEDIA_FRAGMENT="media-fragment",s.KEY="key",s.STEERING_MANIFEST="steering-manifest",s.SERVER_CERTIFICATE="server-certificate",s.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",s}({}),j=function(s){return s.MAIN="main",s.AUDIO="audio",s.SUBTITLE="subtitle",s}({}),Le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ln=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,$0(this,"stats")}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Le.AUDIO]:null,[Le.VIDEO]:null,[Le.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new js),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Ml.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Le.AUDIO]=null,e[Le.VIDEO]=null,e[Le.AUDIOVIDEO]=null,this.url=null}};function Ne(s){return s.sn!=="initSegment"}function Gs(s,e){return s.sn===(e==null?void 0:e.sn)&&s.level===e.level}function co(s,e){return s.sn===(e==null?void 0:e.sn)&&s.level===e.level&&s.cc===e.cc}var ds=class extends ln{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(H(e)&&H(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=H(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){var t;let i=Object.keys(this.levelkeys),r=i.length;if(r>1||r===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!H(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ne(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},ho=class extends ln{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===j.SUBTITLE&&this.stats.loading.end>0)}};function jc(s,e){let t=Object.getPrototypeOf(s);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||jc(t,e)}}function $0(s,e){let t=jc(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}function G0(s,e,t){return(e=H0(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Re(){return Re=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},Re.apply(null,arguments)}function Ad(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function J(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ad(Object(t),!0).forEach(function(i){G0(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Ad(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function Kn(s,e){if(s==null)return{};var t,i,r=K0(s,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);for(i=0;i<n.length;i++)t=n[i],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(s,t)&&(r[t]=s[t])}return r}function K0(s,e){if(s==null)return{};var t={};for(var i in s)if({}.hasOwnProperty.call(s,i)){if(e.indexOf(i)!==-1)continue;t[i]=s[i]}return t}function V0(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function H0(s){var e=V0(s,"string");return typeof e=="symbol"?e:e+""}function un(s){switch(s.details){case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_TIMEOUT:case k.LEVEL_LOAD_TIMEOUT:case k.MANIFEST_LOAD_TIMEOUT:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:case k.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function zc(s){return s.details.startsWith("key")}function Xc(s){return zc(s)&&!!s.frag&&!s.frag.decryptdata}function Rd(s,e){let t=un(e);return s.default[`${t?"timeout":"error"}Retry`]}function Nl(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function xd(s){return J(J({},s),{errorRetry:null,timeoutRetry:null})}function zs(s,e,t,i){if(!s)return!1;let r=i==null?void 0:i.code,n=e<s.maxNumRetry&&(q0(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function q0(s){return Xs(s)||!!s&&(s<400||s>499)}function Xs(s){return s===0&&navigator.onLine===!1}function Qc(s,e){return e>0&&s.loadError>0&&s.loadErrorTime!==0&&self.performance.now()-s.loadErrorTime>e}var di=class{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){let 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_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},fo=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new di(e),this.fast_=new di(t),this.defaultTTFB_=r,this.ttfb_=new di(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new di(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new di(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new di(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;let i=Math.min(this.minDelayMs_,t/1e5),r=8*t,n=Math.max(e,i)/1e3,a=r/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){let 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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},at=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=ci,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},ci=function(){},W0={trace:ci,debug:ci,log:ci,warn:ci,info:ci,error:ci};function go(){return Re({},W0)}function Y0(s,e){let t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):ci}function Id(s,e,t){return e[s]?e[s].bind(e):Y0(s,t)}var mo=go();function j0(s,e,t){let i=go();if(typeof console=="object"&&s===!0||typeof s=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=Id(n,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return go()}r.forEach(n=>{mo[n]=Id(n,s)})}else Re(mo,i);return i}var Te=mo;function pi(s=!0){return typeof self=="undefined"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function z0(s){return typeof self!="undefined"&&s===self.ManagedMediaSource}function Jc(s,e){let t=Object.keys(s),i=Object.keys(e),r=t.length,n=i.length;return!r||!n||r===n&&!t.some(a=>i.indexOf(a)===-1)}function X0(s){return btoa(String.fromCharCode(...s))}function Vn(s){return s instanceof ArrayBuffer||typeof SharedArrayBuffer!="undefined"&&s instanceof SharedArrayBuffer}var Q0="utf-16",Ba="utf-16be",Ld="utf-16le",tn="utf-8";function J0(s,e={}){let t;Vn(s)?t=new DataView(s):t=new DataView(s.buffer,s.byteOffset,s.byteLength);let i=0,{encoding:r}=e;if(!r){let u=t.getUint8(0),d=t.getUint8(1);u==239&&d==187&&t.getUint8(2)==191?(r=tn,i=3):u==254&&d==255?(r=Ba,i=2):u==255&&d==254?(r=Ld,i=2):r=tn}if(typeof TextDecoder!="undefined")return new TextDecoder(r).decode(t);let{byteLength:n}=t,a=r!==Ba,o="",l;for(;i<n;){switch(r){case tn:if(l=t.getUint8(i),l<128)i++;else if(l>=194&&l<=223)if(i+1<n){let u=t.getUint8(i+1);u>=128&&u<=191?(l=(l&31)<<6|u&63,i+=2):i++}else i++;else if(l>=224&&l<=239)if(i+2<=n-1){let u=t.getUint8(i+1),d=t.getUint8(i+2);u>=128&&u<=191&&d>=128&&d<=191?(l=(l&15)<<12|(u&63)<<6|d&63,i+=3):i++}else i++;else if(l>=240&&l<=244)if(i+3<=n-1){let u=t.getUint8(i+1),d=t.getUint8(i+2),c=t.getUint8(i+3);u>=128&&u<=191&&d>=128&&d<=191&&c>=128&&c<=191?(l=(l&7)<<18|(u&63)<<12|(d&63)<<6|c&63,i+=4):i++}else i++;else i++;break;case Ba:case Q0:case Ld:l=t.getUint16(i,a),i+=2;break}o+=String.fromCodePoint(l)}return o}function Z0(s){let e=typeof s=="string"?new URL(s):s;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function Zc(s,e){if(s<0)return-Zc(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let i=Math.floor(s*t);return(i%2===0?i:i+1)/t}else return Math.round(s*t)/t}function ev(s,e){let t;try{t=new URL(s)}catch{return s}let i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let o=0;o<a&&r[o]===n[o];o++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}function eh(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Fl(s,e){return 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}function Hn(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}function tv(s,e){return Fl(s,e)&&Hn(s,e+6)+10<=s.length-e}function th(s,e){return 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}function Qs(s,e){let t=e,i=0;for(;Fl(s,e);){i+=10;let r=Hn(s,e+6);i+=r,th(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)}function iv(s){return Vn(s)?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Ua(s,e=0,t=1/0){return sv(s,e,t,Uint8Array)}function sv(s,e,t,i){let r=rv(s),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=nv(s)?s.byteOffset:0,o=(a+s.byteLength)/n,l=(a+e)/n,u=Math.floor(Math.max(0,Math.min(l,o)));return new i(r,u,Math.floor(Math.min(u+Math.max(t,0),o))-u)}function rv(s){return Vn(s)?s:s.buffer}function nv(s){return s&&Vn(s.buffer)&&s.byteLength!==void 0&&s.byteOffset!==void 0}function pt(s,e=!1){let t=e?s.indexOf(0):s.length,i=J0(new DataView(s.buffer,s.byteOffset,t),{encoding:tn});return e?i:i.replace(/\0/g,"")}function av(s){let e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=s.data.subarray(1).indexOf(0);if(i===-1)return;let r=pt(Ua(s.data,1,i)),n=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=pt(Ua(s.data,3+i,a)),l;return r==="-->"?l=pt(Ua(s.data,4+i+a)):l=iv(s.data.subarray(4+i+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function ov(s){if(s.size<2)return;let e=pt(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function lv(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1,{data:i}=s,r=pt(i.subarray(t),!0);t+=r.length+1;let n=pt(i.subarray(t));return{key:s.type,info:r,data:n}}let e=pt(s.data.subarray(1));return{key:s.type,info:"",data:e}}function uv(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=pt(s.data.subarray(t),!0);t+=i.length+1;let r=pt(s.data.subarray(t));return{key:s.type,info:i,data:r}}let e=pt(s.data);return{key:s.type,info:"",data:e}}function dv(s){return s.type==="PRIV"?ov(s):s.type[0]==="W"?uv(s):s.type==="APIC"?av(s):lv(s)}function cv(s){let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Hn(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}var $r=10,hv=10;function ih(s){let e=0,t=[];for(;Fl(s,e);){let i=Hn(s,e+6);s[e+5]>>6&1&&(e+=$r),e+=$r;let r=e+i;for(;e+hv<r;){let n=cv(s.subarray(e)),a=dv(n);a&&t.push(a),e+=n.size+$r}th(s,e)&&(e+=$r)}return t}function sh(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function fv(s){if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Bl(s){let e=ih(s);for(let t of e)if(sh(t))return fv(t)}function We(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function rh(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ul(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Ot(s){return String.fromCharCode.apply(null,s)}var Gt=Math.pow(2,32)-1,re={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},nh={video:1,audio:2,id3:3,text:4};function ah(s,e){let t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Y(s,e){let t=s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3];return t<0?4294967296+t:t}function Dd(s,e){let t=Y(s,e);return t*=Math.pow(2,32),t+=Y(s,e+4),t}function Gr(s,e){let t="";for(let i=e;i<s.length;i++)if(t+=String.fromCharCode(s[i]),s[i]===0)return t;return null}function po(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function Ue(s,e,t){s[e]=t>>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function kd(s,e,t){let i=e.byteOffset-s.byteOffset-8,r=8+t,n=e.byteLength+8-r;n<8||(Ue(s,i,r),Ue(s,i+r,n),Ue(s,i+r+4,re.free))}function vo(s,e){return[s.byteOffset-e-8,s.byteOffset-e+s.byteLength]}function oh(s,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,u])=>o+u-l,0),i=new Uint8Array(s.byteLength-t),r=0,n=0;for(let o=0;o<e.length;o++){let[l,u]=e[o];i.set(s.subarray(r,l),n),n+=l-r,r=u}return i.set(s.subarray(r),n),{result:i,dropped:t,droppedBefore:o=>e.reduce((l,[u,d])=>d<=o?l+d-u:l,0)}}function gv(s){let e=ne(s,["moov"]);if(e.length!==1||ne(s,["moof"]).length)return null;let t=s.byteOffset,i=[],r=[],n=!1,a=ne(e[0],["trak"]);for(let f=0;f<a.length;f++){let g=a[f],m=ne(g,["mdia","hdlr"])[0];if((m?Ot(m.subarray(8,12)):"")==="vide"){n=!0;continue}let y=ne(g,["tkhd"])[0];if(!y)return null;let T=y[0];r.push(Y(y,T===0?12:20)),i.push(vo(g,t))}if(!n||!i.length)return null;let o=ne(e[0],["mvex"])[0],l=0;if(o){let f=ne(o,["trex"]);for(let g=0;g<f.length;g++){let m=f[g];r.indexOf(Y(m,4))!==-1&&(i.push(vo(m,t)),l+=m.byteLength+8)}}let{result:u,dropped:d,droppedBefore:c}=oh(s,i),h=e[0].byteOffset-t-8;if(Ue(u,h,e[0].byteLength+8-d),o&&l){let f=o.byteOffset-t-8;Ue(u,f-c(f),o.byteLength+8-l)}return u}function mv(s,e,t,i,r){if(t<1)return null;let n=ne(s,["moof"]);if(n.length!==1)return null;let a=n[0],o=s.byteOffset,l=[],u=[],d=ne(a,["traf"]),c=!0;for(let m=0;m<d.length;m++){let p=d[m],y=ne(p,["tfhd"])[0];if(!y)return null;Y(y,4)===e?(l.push(p),Y(y,0)&131072||(c=!1)):u.push(vo(p,o))}if(!l.length||u.length&&!c)return null;if(i!==void 0){let m=t;for(let y=0;y<l.length;y++){let T=l[y],v=0,_=ne(T,["trun"]);for(let b=0;b<_.length;b++){let x=_[b],L=Math.min(m,Y(x,4));if(L){Ue(s,x.byteOffset-o+4,L);let R=Y(x,0)&16777215,I=(R&256?4:0)+(R&512?4:0)+(R&1024?4:0)+(R&2048?4:0);kd(s,x,8+(R&1?4:0)+(R&4?4:0)+L*I)}else Ue(s,x.byteOffset-o-4,re.free);m-=L,v+=L}let S=ne(T,["senc"])[0];S&&Ue(s,S.byteOffset-o+4,v);let A=ne(T,["saiz"])[0];if(A){let b=A[1]<<16|A[2]<<8|A[3],x=4;b&1&&(x+=8);let L=A[x];x+=1,Ue(s,A.byteOffset-o+x,v),kd(s,A,x+4+(L===0?v:0))}}let p=ne(s,["mdat"]);if(p.length===1){let y=p[0].byteOffset-o-8;Ue(s,y,i-y)}}let h=s,f=0,g=()=>0;if(u.length){({result:h,dropped:f,droppedBefore:g}=oh(s,u)),Ue(h,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){let p=l[m],y=g(p.byteOffset-o),T=ne(p,["trun"]);for(let v=0;v<T.length;v++){let _=T[v];Y(_,0)&1&&Ue(h,_.byteOffset-o-y+8,Y(_,8)-f)}if(y){let v=ne(p,["saio"]);for(let _=0;_<v.length;_++){let S=v[_],A=S[0]===0?4:8,b=Y(S,0)&1?12:4,x=Y(S,b);for(b+=4;x--;b+=A){let L=b+A-4;Ue(h,S.byteOffset-o-y+L,Y(S,L)-y)}}}}}if(r){let{durationOffset:m,value:p}=r;Ue(h,m-g(m),p)}return i!==void 0?h.subarray(0,i-f):h}function pv(s,e){let t=s.byteLength;for(let i=0;i<t;){let r=Y(s,i);if(r>8&&Y(s,i+4)===re[e])return!0;i=r>1?i+r:t}return!1}function ne(s,e){let t=[];return e.length&&lh(s,e,0,0,s.byteLength,t),t}function lh(s,e,t,i,r,n){let a=e[t];if((a==null?void 0:a.length)!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),u=a.charCodeAt(2),d=a.charCodeAt(3),c=e.length-1;for(let h=i;h<r;){let f=h+8<=r,g=h+4<=r?s[h]*16777216+(s[h+1]<<16|s[h+2]<<8|s[h+3]):Y(s,h),m=g>1?h+g:r;if(f&&s[h+4]===o&&s[h+5]===l&&s[h+6]===u&&s[h+7]===d){let p=Math.min(m,r);t===c?n.push(s.subarray(h+8,p)):lh(s,e,t+1,h+8,p,n)}h=m}}function vv(s){let e=[],t=s[0],i=8,r=Y(s,i);i+=4;let n=0,a=0;t===0?(n=Y(s,i),a=Y(s,i+4),i+=8):(n=Dd(s,i),a=Dd(s,i+8),i+=16),i+=2;let o=s.length+a,l=ah(s,i);i+=2;for(let u=0;u<l;u++){let d=i,c=Y(s,d);d+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return Te.warn("SIDX has hierarchical references (not supported)"),null;let g=Y(s,d);d+=4,e.push({referenceSize:h,subsegmentDuration:g,info:{duration:g/r,start:o,end:o+h-1}}),o+=h,d+=4,i=d}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function uh(s){let e=[],t=ne(s,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=ne(n,["tkhd"])[0];if(a){let o=a[0],l=Y(a,o===0?12:20),u=ne(n,["mdia","mdhd"])[0];if(u){o=u[0];let d=Y(u,o===0?12:20),c=ne(n,["mdia","hdlr"])[0];if(c){let h=Ot(c.subarray(8,12)),f={soun:Le.AUDIO,vide:Le.VIDEO}[h],g=ne(n,["mdia","minf","stbl","stsd"])[0],m=yv(g);f?(e[l]={timescale:d,type:f,stsd:m},e[f]=J({timescale:d,id:l},m)):e[l]={timescale:d,type:h,stsd:m}}}}}return ne(s,["moov","mvex","trex"]).forEach(r=>{let n=Y(r,4),a=e[n];a&&(a.default={duration:Y(r,12),sampleSize:Y(r,16),flags:Y(r,20)})}),e}function yv(s){let e=s.subarray(8),t=e.subarray(86),i=Ot(e.subarray(4,8)),r=i,n,a=i==="enca"||i==="encv";if(a){let u=ne(e,[i])[0].subarray(i==="enca"?28:78);ne(u,["sinf"]).forEach(c=>{let h=ne(c,["schm"])[0];if(h){let f=Ot(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=ne(c,["frma"])[0];g&&(r=Ot(g))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=ne(t,["avcC"])[0];l&&l.length>3&&(r+="."+Vr(l[1])+Vr(l[2])+Vr(l[3]),n=Kr(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=ne(e,[i])[0],u=ne(l.subarray(28),["esds"])[0];if(u&&u.length>7){let d=4;if(u[d++]!==3)break;d=$a(u,d),d+=2;let c=u[d++];if(c&128&&(d+=2),c&64&&(d+=u[d++]),u[d++]!==4)break;d=$a(u,d);let h=u[d++];if(h===64)r+="."+Vr(h);else break;if(d+=12,u[d++]!==5)break;d=$a(u,d);let f=u[d++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((u[d]&224)>>5)),r+="."+g}break}case"hvc1":case"hev1":{let l=ne(t,["hvcC"])[0];if(l&&l.length>12){let u=l[1],d=["","A","B","C"][u>>6],c=u&31,h=Y(l,2),f=(u&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);r+="."+d+c,r+="."+Ev(h).toString(16).toUpperCase(),r+="."+f+g;let p="";for(let y=m.length;y--;){let T=m[y];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}r+=p}n=Kr(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Kr(r,t)||r;break}case"vp09":{let l=ne(t,["vpcC"])[0];if(l&&l.length>6){let u=l[4],d=l[5],c=l[6]>>4&15;r+="."+Kt(u)+"."+Kt(d)+"."+Kt(c)}break}case"av01":{let l=ne(t,["av1C"])[0];if(l&&l.length>2){let u=l[1]>>>5,d=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,g=u===2&&h?f?12:10:h?10:8,m=(l[2]&16)>>4,p=(l[2]&8)>>3,y=(l[2]&4)>>2,T=l[2]&3;r+="."+u+"."+Kt(d)+c+"."+Kt(g)+"."+m+"."+p+y+T+"."+Kt(1)+"."+Kt(1)+"."+Kt(1)+"."+0,n=Kr("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function Kr(s,e){let t=ne(e,["dvvC"]),i=t.length?t[0]:ne(e,["dvcC"])[0];if(i){let r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return s+"."+Kt(r)+"."+Kt(n)}}function Ev(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function $a(s,e){let t=e+5;for(;s[e++]&128&&e<t;);return e}function Vr(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function Kt(s){return(s<10?"0":"")+s}function Tv(s,e){if(!s||!e)return;let t=e.keyId;(t==null?void 0:t.byteLength)===16&&e.isCommonEncryption&&dh(s,(i,r)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(Te.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${We(n)} -> ${We(t)}`),i.set(t,8))})}function _v(s){let e=[];return dh(s,t=>e.push(t.subarray(8,24))),e}function dh(s,e){ne(s,["moov","trak"]).forEach(i=>{let r=ne(i,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=ne(n,["enca"]),o=a.length>0;o||(a=ne(n,["encv"])),a.forEach(l=>{let u=o?l.subarray(28):l.subarray(78);ne(u,["sinf"]).forEach(c=>{let h=ch(c);h&&e(h,o)})})})}function ch(s){let e=ne(s,["schm"])[0];if(e){let t=Ot(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=ne(s,["schi","tenc"])[0];if(i)return i}}}var Pd;function Sv(s){return typeof TextDecoder=="undefined"?pt(s):(Pd||(Pd=new TextDecoder("utf-8"))).decode(s).replace(/\0/g,"")}function bv(s){let e=s.byteLength,t=[];for(let i=0;i<e;){let r=i+8<=e,n=i+4<=e?s[i]*16777216+(s[i+1]<<16|s[i+2]<<8|s[i+3]):Y(s,i),a=n>1?i+n:e;if(r&&s[i+4]===109&&s[i+5]===111&&s[i+6]===111&&s[i+7]===102){let o=Math.min(a,e);for(let l=i+8;l<o;){let u=l+8<=o,d=l+4<=o?s[l]*16777216+(s[l+1]<<16|s[l+2]<<8|s[l+3]):Y(s,l),c=d>1?l+d:o;if(u&&s[l+4]===116&&s[l+5]===114&&s[l+6]===97&&s[l+7]===102){let h=Math.min(c,o),f,g,m=[];for(let p=l+8;p<h;){let y=p+8<=h,T=p+4<=h?s[p]*16777216+(s[p+1]<<16|s[p+2]<<8|s[p+3]):Y(s,p),v=T>1?p+T:h;if(y&&s[p+4]===116){let _=Math.min(v,h);s[p+5]===102&&s[p+6]===104&&s[p+7]===100?g||(g=s.subarray(p+8,_)):s[p+5]===102&&s[p+6]===100&&s[p+7]===116?f||(f=s.subarray(p+8,_)):s[p+5]===114&&s[p+6]===117&&s[p+7]===110&&m.push(s.subarray(p+8,_))}p=v}t.push({moofOffset:s.byteOffset+i,tfdt:f,tfhd:g,truns:m})}l=c}}i=a}return t}function Av(s,e,t,i,r=!0){return hh(s,e,i,r)}function Rv(s,e,t,i,r=!1){let n=[],a=e.samples,o=hh(a,t,i,r,{isHEVCFlavor:fr(e.codec),samples:n,timeOffset:s,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:r,tracks:o}}}function hh(s,e,t,i,r){let n={},a=!1,o=bv(s),l=s.byteLength;for(let c=0;c<o.length;c++){let{moofOffset:h,tfdt:f,tfhd:g,truns:m}=o[c],p=Y(g,4),y=e[p];if(!y)continue;let T=n[p]||(n[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:y.timescale,type:y.type}),v;if(f){let N=f[0];v=Y(f,4),N===1&&(v===Gt?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=Gt+1,v+=Y(f,8))),H(v)&&(!H(T.start)||v<T.start)&&(T.start=v),r&&H(v)&&(r.timeOffset=v/r.timescale)}let _=(r==null?void 0:r.trackId)===p&&y.type===Le.VIDEO,S=y.default,A=Y(g,0)&16777215,b=(S==null?void 0:S.duration)||0,x,L=(S==null?void 0:S.sampleSize)||0,R=8;A&1&&(R+=8),A&2&&(R+=4),A&8&&(b=Y(g,R),x=g.byteOffset-s.byteOffset+R,R+=4),A&16&&(L=Y(g,R));let I=0,P=(A&1)!==0,w=!P&&(A&131072)!==0;P?(I=Y(g,8),I*=Math.pow(2,32),I+=Y(g,12)):w&&(I=h);let B=v||0,U=0,C=b;for(let N=0;N<m.length;N++){let F=m[N],G=Y(F,4),W=T.sampleCount;T.sampleCount+=G;let $=F[3]&1,K=0,se=F[3]&4,ee=F[2]&1,ue=F[2]&2,ie=F[2]&4,ge=F[2]&8,le=8;$&&(K=po(F,le),le+=4),se&&(!(F[le+1]&1)&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=W),le+=4);let ve=I+K;if(!i&&F[1]===0&&F[2]===6&&F[3]===1){var u,d;let Pe=B,yt=ve,Ft=le,X=-1,he=0,pe=0,Ke=(u=r==null?void 0:r.timeOffset)!=null?u:0,Fe=b/((d=r==null?void 0:r.timescale)!=null?d:1),st=(r==null?void 0:r.isHEVCFlavor)===!0,At=st?2:1;for(let Je=0;Je<G;Je++){let rt=F[le]===0?F[le+1]<<16|F[le+2]<<8|F[le+3]:Y(F,le),Et=X===-1&&T.keyFrameIndex===void 0&&(F[le+5]&1)===0;le+=8;let ht=ve+rt;if(_){if(rt>0){let tt=ve;do{let oi=s[tt]===0?s[tt+1]<<16|s[tt+2]<<8|s[tt+3]:Y(s,tt);tt+=4;let jt=s[tt],Rt=st?jt>>1&63:jt&31;(st?Rt===39||Rt===40:Rt===6)&&Js(s.subarray(tt,tt+oi),At,Ke,r.samples),tt+=oi}while(tt<ht)}Ke+=Fe}ve=ht,Et&&(X=Je,he=ve)}if(ve<=l)pe=G;else{let Je=yt,rt=Ft;for(let Et=0;Et<G;Et++){let ht=F[rt]===0?F[rt+1]<<16|F[rt+2]<<8|F[rt+3]:Y(F,rt);if(Je+=ht,Je>l)break;pe=Et+1,rt+=8}}if(_&&(r.timeOffset=Ke),X!==-1&&he<=l&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=X,T.keyFrameStart=Pe+X*b),pe){(!H(T.ptsMin)||Pe<T.ptsMin)&&(T.ptsMin=Pe);let Je=Pe+pe*b;(!H(T.ptsMax)||Je>T.ptsMax)&&(T.ptsMax=Je)}let wi=b*G;B=Pe+wi,U+=wi;continue}let Ge,lt;i&&(Ge=[],lt={sampleOffset:ve,samples:Ge,defaultSampleDurationOffset:x},ve<=l&&T.trun.push(lt));let Yt;for(let Pe=0;Pe<G;Pe++){let yt;ee?(i&&(yt=F.byteOffset-s.byteOffset+le),C=Y(F,le),le+=4):C=b,ue?(Yt=Y(F,le),le+=4):Yt=L;let Ft,X;ie&&(X=F[le+1]&1?1:0,i&&(Ft={isNonSync:X,dependsOn:(F[le]&3)===1?1:2}),le+=4);let he=0;if(ge&&(he=F[0]===0?Y(F,le):po(F,le),le+=4),_){let pe=ve,Ke=0;for(;Ke<Yt;){let Fe=Y(s,pe);pe+=4,fh(r.isHEVCFlavor,s[pe])&&Js(s.subarray(pe,pe+Fe),r.isHEVCFlavor?2:1,r.timeOffset+he/r.timescale,r.samples),pe+=Fe,Ke+=Fe+4}r.timeOffset+=C/r.timescale}if(ve+=Yt,ve<=l){lt&&yt!==void 0&&(lt.lastSampleDurationOffset=yt),X===0&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=Pe,T.keyFrameStart=B);let pe=B+he;(!H(T.ptsMin)||pe<T.ptsMin)&&(T.ptsMin=pe),(!H(T.ptsMax)||pe+C>T.ptsMax)&&(T.ptsMax=pe+C),Ge&&(Ge[Pe]={cts:he,duration:C,flags:Ft,size:Yt})}B+=C,U+=C}!U&&b&&(U+=b*G)}T.duration+=U,T.duration&&(a=!0)}if(!a){let c=1/0,h=0,f=ne(s,["sidx"]);for(let g=0;g<f.length;g++){let m=vv(f[g]);if(m!=null&&m.references){c=Math.min(c,m.earliestPresentationTime/m.timescale);let p=m.references.reduce((y,T)=>y+T.info.duration||0,0);h=Math.max(h,p+m.earliestPresentationTime/m.timescale)}}h&&H(h)&&Object.keys(n).forEach(g=>{n[g].duration||(n[g].duration=h*n[g].timescale-n[g].start)})}return n}function xv(s){let e={valid:null,remainder:null},t=ne(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function St(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Iv(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,a=!1;return ne(i,["moof"]).map(l=>{let u=l.byteOffset-8;ne(l,["traf"]).map(c=>{let h=ne(c,["tfdt"]).map(f=>{let g=f[0],m=Y(f,4);return g===1&&(m*=Math.pow(2,32),m+=Y(f,8)),m/r})[0];return h!==void 0&&(s=h),ne(c,["tfhd"]).map(f=>{let g=Y(f,4),m=Y(f,0)&16777215,p=(m&1)!==0,y=0,T=(m&2)!==0,v=(m&8)!==0,_=0,S=(m&16)!==0,A=0,b=(m&32)!==0,x=!p&&(m&131072)!==0,L=8;g===n&&(p?(y=Y(f,L),L+=4,y*=Math.pow(2,32),y+=Y(f,L),L+=4):x&&(y=u),T&&(L+=4),v&&(_=Y(f,L),L+=4),S&&(A=Y(f,L),L+=4),b&&(L+=4),e.type==="video"&&(a=fr(e.codec)),ne(c,["trun"]).map(R=>{let I=R[0],P=Y(R,0)&16777215,w=(P&1)!==0,B=0,U=(P&4)!==0,C=(P&256)!==0,N=0,F=(P&512)!==0,G=0,W=(P&1024)!==0,$=(P&2048)!==0,K=0,se=Y(R,4),ee=8;w&&(B=Y(R,ee),ee+=4),U&&(ee+=4);let ue=y+B;for(let ie=0;ie<se;ie++){if(C?(N=Y(R,ee),ee+=4):N=_,F?(G=Y(R,ee),ee+=4):G=A,W&&(ee+=4),$&&(I===0?K=Y(R,ee):K=po(R,ee),ee+=4),e.type===Le.VIDEO){let ge=0;for(;ge<G;){let le=Y(i,ue);if(ue+=4,fh(a,i[ue])){let ve=i.subarray(ue,ue+le);Js(ve,a?2:1,s+K/r,t)}ue+=le,ge+=le+4}}s+=N/r}}))})})}),t}function fr(s){if(!s)return!1;let e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function fh(s,e){if(s){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Js(s,e,t,i){let r=gh(s),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);let u=r.length-n,d=n;if(o<u)n+=o;else if(o>u){Te.error(`Malformed SEI payload. ${o} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(r[d++]===181){let h=ah(r,d);if(d+=2,h===49){let f=Y(r,d);if(d+=4,f===1195456820){let g=r[d++];if(g===3){let m=r[d++],p=31&m,y=64&m,T=y?2+p*3:0,v=new Uint8Array(T);if(y){v[0]=m;for(let _=1;_<T;_++)v[_]=r[d++]}i.push({type:g,payloadType:a,pts:t,bytes:v})}}}}}else if(a===5&&o>16){let c=[];for(let g=0;g<16;g++){let m=r[d++].toString(16);c.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&c.push("-")}let h=o-16,f=new Uint8Array(h);for(let g=0;g<h;g++)f[g]=r[d++];i.push({payloadType:a,pts:t,uuid:c.join(""),userData:Sv(f),userDataBytes:f})}}}function gh(s){let e=s.byteLength,t,i=s.indexOf(3,3);for(;i!==-1;)s[i-1]===0&&s[i-2]===0&&(t||(t=[])).push(i),i=s.indexOf(3,i+1);if(!t)return s;let r=e-t.length,n=new Uint8Array(r),a=0,o=0;for(let l=0;l<r;o++,l++)o===t[a]&&(o++,a++),n[l]=s[o];return n}function Lv(s){let e=s[0],t="",i="",r=0,n=0,a,o=0,l=0,u=4;if(e===0){let c=Gr(s,u),h=c!==null?Gr(s,u+c.length):null;c!==null&&h!==null?(t=c,i=h,u+=c.length+h.length,r=Y(s,u),u+=4,n=Y(s,u),u+=4,o=Y(s,u),u+=4,l=Y(s,u),u+=4):(Te.warn(`Unterminated ${c===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),u=s.length)}else if(e===1){r=Y(s,u),u+=4;let c=Y(s,u);u+=4;let h=Y(s,u);u+=4,a=2**32*c+h,N0(a)||(a=Number.MAX_SAFE_INTEGER,Te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(s,u),u+=4,l=Y(s,u),u+=4;let f=Gr(s,u),g=f!==null?Gr(s,u+f.length):null;f!==null&&(t=f,u+=f.length),g!==null?(i=g,u+=g.length):(Te.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),u=s.length)}let d=s.subarray(u,s.byteLength);return{schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:d}}function Dv(s,...e){let t=e.length,i=8,r=t;for(;r--;)i+=e[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function kv(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Dv([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t)}function mh(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32<t;){let r=new DataView(s,i),n=Cv(r);e.push(n),i+=n.size}}return e}function Pv(s){let e=[];for(let t=0;t<s.length;){let i=s[t++],r=i&7;if(r===0){for(;s[t++]&128;);continue}if(r!==2){t+=r===1?8:4;continue}let n=0;for(let a=0,o=128;o&128;a+=7)n|=((o=s[t++])&127)<<a;if(i>>3===2)if(n===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(s[t+o*2],s[t+o*2+1]),16);e.push(a)}else n===16&&e.push(s.subarray(t,t+16));t+=n}return e}function Cv(s){let e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return{offset:t,size:i};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};let n=s.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=s.buffer,o=We(new Uint8Array(a,t+12,16)),l=null,u=null,d=0;if(n===0)d=28;else{let h=s.getUint32(28);if(!h||i<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));d=32+h*16}if(!d)return{offset:t,size:e};let c=s.getUint32(d);return e-32<c?{offset:t,size:e}:(u=new Uint8Array(a,t+d+4,c),n===0&&(l=Pv(u)),{version:n,systemId:o,kids:l,data:u,offset:t,size:e})}var vs=ph("userAgent"),wv=ph("vendor"),Ga,Ka,Va;function ph(s){try{return navigator[s]||""}catch{}return""}function Ov(){if(Va===void 0){let s=vs.match(/Safari\/(\d+)/i);Va=s?parseInt(s[1]):0}return Va}function Vs(){if(Ga===void 0){let s=vs.match(/Chrome\/(\d+)/i);Ga=s?parseInt(s[1]):0}return Ga}function Mv(){if(Ka===void 0){let s=vs.match(/Firefox\/(\d+)/i);Ka=s?parseInt(s[1]):0}return Ka}function vh(){return/\(Windows.+Firefox\//i.test(vs)}function Nv(){return wv.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(vs)}function Fv(){return/Android/.test(vs)}var gs={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function $l(s,e){let t=gs[e];return!!t&&!!t[s.slice(0,4)]}function Zs(s,e,t=!0){return!s.split(",").some(i=>!Gl(i,e,t))}function Gl(s,e,t=!0){var i;let r=pi(t);return(i=r==null?void 0:r.isTypeSupported(er(s,e)))!=null?i:!1}function er(s,e){return`${e}/mp4;codecs=${s}`}function Cd(s){if(s){let e=s.substring(0,4);return gs.video[e]}return 2}function dn(s){let e=vh();return s.split(",").reduce((t,i)=>{let n=e&&fr(i)?9:gs.video[i];return n?(n*2+t)/(t?3:2):(gs.audio[i]+t)/(t?2:1)},0)}var Ha={};function Bv(s,e=!0){if(Ha[s])return Ha[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let r=0;r<t.length;r++){var i;if(Gl(t[r],"audio",e))return Ha[s]=t[r],t[r];if(t[r]==="mp3"&&(i=pi(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return s}var Uv=/flac|opus|mp4a\.40\.34/i;function cn(s,e=!0){return s.replace(Uv,t=>Bv(t.toLowerCase(),e))}function $v(s,e){let t=[];if(s){let i=s.split(",");for(let r=0;r<i.length;r++)$l(i[r],"video")||t.push(i[r])}return e&&t.push(e),t.join(",")}function sn(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(wd(s,"audio")||wd(s,"video")))return s;if(e){let t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function wd(s,e){return $l(s,e)&&Gl(s,e)}function Gv(s){let e=s.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Kv(s){if(s.startsWith("av01.")){let e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function Od(s){let e=pi(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function yo(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Vv={supported:!0,powerEfficient:!0,smooth:!0},Hv={supported:!1,smooth:!1,powerEfficient:!1},yh={supported:!0,configurations:[],decodingInfoResults:[Vv]};function Eh(s,e){return{supported:!1,configurations:e,decodingInfoResults:[Hv],error:s}}function qv(s,e,t,i,r,n){let a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=n==null?void 0:n.audioCodec,u=n==null?void 0:n.channels,d=u?parseInt(u):l?1/0:2,c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){let g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{h[m]=(h[m]||0)+g.channels[m]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>fr(h))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!c&&H(d)&&Object.keys(c).some(h=>parseInt(h)>d)}function Th(s,e,t,i={}){let r=s.videoCodec;if(!r&&!s.audioCodec||!t)return Promise.resolve(yh);let n=[],a=Wv(s),o=a.length,l=Yv(s,e,o>0),u=l.length;for(let d=o||1*u||1;d--;){let c={type:"media-source"};if(o&&(c.video=a[d%o]),u){c.audio=l[d%u];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let d=navigator.userAgent;if(r.split(",").some(c=>fr(c))&&vh())return Promise.resolve(Eh(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),n))}return Promise.all(n.map(d=>{let c=jv(d);return i[c]||(i[c]=t.decodingInfo(d))})).then(d=>({supported:!d.some(c=>!c.supported),configurations:n,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:n,decodingInfoResults:[],error:d}))}function Wv(s){var e;let t=(e=s.videoCodec)==null?void 0:e.split(","),i=Sh(s),r=s.width||640,n=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{let u={contentType:er(Kv(l),"video"),width:r,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(u.transferFunction=o),u}):[]}function Yv(s,e,t){var i;let r=(i=s.audioCodec)==null?void 0:i.split(","),n=Sh(s);return r&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;let u=o?(l=e.groups[o])==null?void 0:l.tracks:null;return u?u.reduce((d,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let g={contentType:er(f,"audio"),bitrate:t?_h(f,n):n};h&&(g.channels=""+h),d.push(g)})}return d},a):a},[]):[]}function _h(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Sh(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function jv(s){let e="",{audio:t,video:i}=s;if(i){let r=yo(i.contentType);e+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){let r=yo(t.contentType);e+=`${i?"_":""}${r}_c${t.channels}`}return e}function gi(s,e,t){let i=encodeURIComponent(e),r=`${i}=${encodeURIComponent(t)}`,n=!1,a=[];s.search.substring(1).split("&").forEach(o=>{o===i||o.startsWith(i+"=")?n||(a.push(r),n=!0):o&&a.push(o)}),n||a.push(r),s.search=a.join("&")}var Eo=["NONE","TYPE-0","TYPE-1",null];function zv(s){return Eo.indexOf(s)>-1}var hn=["SDR","PQ","HLG"];function Xv(s){return!!s&&hn.indexOf(s)>-1}var rn={No:"",Yes:"YES",v2:"v2"};function Md(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i<e/2;return e&&r?t?rn.v2:rn.Yes:rn.No}var fn=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&gi(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&gi(t,"_HLS_part",this.part.toString()),this.skip&&gi(t,"_HLS_skip",this.skip),t.href}},qi=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Nd(this._audioGroups,e)}hasSubtitleGroup(e){return Nd(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Nd(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function Qv(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function Jv(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||hn.slice(0);let r=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&Qv(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}var Zv=s=>{let e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},ke=(s,e)=>JSON.stringify(s,Zv(e));function ey(s,e,t,i,r){let n=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=r==null?void 0:r.videoCodec,u=a&&parseInt(a)===2,d=!1,c=!1,h=1/0,f=1/0,g=1/0,m=1/0,p=0,y=[],{preferHDR:T,allowedVideoRanges:v}=Jv(e,r);for(let x=n.length;x--;){let L=s[n[x]];d||(d=L.channels[2]>0),h=Math.min(h,L.minHeight),f=Math.min(f,L.minFramerate),g=Math.min(g,L.minBitrate),v.filter(I=>L.videoRanges[I]>0).length>0&&(c=!0)}h=H(h)?h:0,f=H(f)?f:0;let _=Math.max(1080,h),S=Math.max(30,f);g=H(g)?g:t,t=Math.max(g,t),c||(e=void 0);let A=n.length>1;return{codecSet:n.reduce((x,L)=>{let R=s[L];if(L===x)return x;if(y=c?v.filter(I=>R.videoRanges[I]>0):[],A){if(R.minBitrate>t)return Ut(L,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),x;if(!R.hasDefaultAudio)return Ut(L,"no renditions with default or auto-select sound found"),x;if(o&&L.indexOf(o.substring(0,4))%5!==0)return Ut(L,`audio codec preference "${o}" not found`),x;if(a&&!u){if(!R.channels[a])return Ut(L,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),x}else if((!o||u)&&d&&R.channels[2]===0)return Ut(L,"no renditions with stereo sound found"),x;if(R.minHeight>_)return Ut(L,`min resolution of ${R.minHeight} > maximum of ${_}`),x;if(R.minFramerate>S)return Ut(L,`min framerate of ${R.minFramerate} > maximum of ${S}`),x;if(!y.some(I=>R.videoRanges[I]>0))return Ut(L,`no variants with VIDEO-RANGE of ${ke(y)} found`),x;if(l&&L.indexOf(l.substring(0,4))%5!==0)return Ut(L,`video codec preference "${l}" not found`),x;if(R.maxScore<p)return Ut(L,`max score of ${R.maxScore} < selected max of ${p}`),x}return x&&(dn(L)>=dn(x)||R.fragmentError>s[x].fragmentError)?x:(m=R.minIndex,p=R.maxScore,L)},void 0),videoRanges:y,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:m}}function Ut(s,e){Te.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function bh(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ty(s,e,t,i){return s.slice(t,i+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let u=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,u),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(d=>{if(!d)return;let c=e.groups[d];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function Fd(s){if(!s)return s;let{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}=s;return{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}}function Ht(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){let r=e[i];if(Vi(s,r,t))return i}return-1}function Vi(s,e,t){let{groupId:i,name:r,lang:n,assocLang:a,default:o}=s,l=s.forced;return(i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||iy(n,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||sy(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function iy(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function sy(s,e=""){let t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function Ki(s,e){let{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function ry(s,e,t,i,r){let n=e[i],o=e.reduce((h,f,g)=>{let m=f.uri;return(h[m]||(h[m]=[])).push(g),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,u=n.frameRate,d=n.codecSet.substring(0,4),c=Bd(e,i,h=>{if(h.videoRange!==l||h.frameRate!==u||h.codecSet.substring(0,4)!==d)return!1;let f=h.audioGroups,g=t.filter(m=>tr(m.groupId,f));return Ht(s,g,r)>-1});return c>-1?c:Bd(e,i,h=>{let f=h.audioGroups,g=t.filter(m=>tr(m.groupId,f));return Ht(s,g,r)>-1})}function Bd(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}function gn(s,e){var t;return!!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}function tr(s,e){return e?e.indexOf(s)!==-1:!0}function Ah(s,e){if(e||s){let t=Re({},e);return s&&(s.videoCodec&&(t.videoCodec=s.videoCodec),s.videoRange&&(t.allowedVideoRanges=[s.videoRange])),t}}var To=class extends at{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:r,partCurrent:n,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let u=performance.now(),d=n?n.stats:r.stats,c=n?n.duration:r.duration,h=u-d.loading.start,f=a.minAutoLevel,g=r.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let p=m>-1&&m!==g,y=!!t||p;if(!y&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!y&&T===null)return;let v=this.bwEstimator.getEstimateTTFB(),_=Math.abs(l.playbackRate);if(h<=Math.max(v,1e3*(c/(_*2))))return;let S=T?T.len/_:0,A=d.loading.first?d.loading.first-d.loading.start:-1,b=d.loaded&&A>-1,x=this.getBwEstimate(),L=a.levels,R=L[g],I=Math.max(d.loaded,Math.round(c*(r.bitrate||R.averageBitrate)/8)),P=b?h-A:h;P<1&&b&&(P=Math.min(h,d.loaded*8/x));let w=b?d.loaded*1e3/P:0,B=v/1e3,U=w?(I-d.loaded)/w:I*8/x+B;if(U<=S)return;let C=w?w*8:x,N=((i=(t==null?void 0:t.details)||a.latestLevelDetails)==null?void 0:i.live)===!0,F=a.config.abrBandWidthUpFactor,G=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){let ee=L[W].maxBitrate,ue=!L[W].details||N;if(G=this.getTimeToLoadFrag(B,C,c*ee,ue),G<Math.min(S,c+B))break}if(G>=U||G>c*10)return;b?this.bwEstimator.sample(h-Math.min(v,A),d.loaded):this.bwEstimator.sampleTTFB(h);let $=L[W].maxBitrate;this.getBwEstimate()*F>$&&(this.firstAutoFloor=Math.min(W,a.firstLevel),this.resetEstimator($));let K=this.findBestLevel($,f,W,0,S,1,1);K>-1&&(W=K),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
|
|
17
17
|
Fragment duration: ${r.duration.toFixed(3)}
|
|
18
|
-
Time to underbuffer: ${
|
|
19
|
-
Estimated load time for current fragment: ${
|
|
20
|
-
Estimated load time for down switch fragment: ${
|
|
21
|
-
TTFB estimate: ${
|
|
22
|
-
Current BW estimate: ${
|
|
18
|
+
Time to underbuffer: ${S.toFixed(3)} s
|
|
19
|
+
Estimated load time for current fragment: ${U.toFixed(3)} s
|
|
20
|
+
Estimated load time for down switch fragment: ${G.toFixed(3)} s
|
|
21
|
+
TTFB estimate: ${A|0} ms
|
|
22
|
+
Current BW estimate: ${H(x)?x|0:"Unknown"} bps
|
|
23
23
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
24
|
-
Switching to level ${
|
|
24
|
+
Switching to level ${W} @ ${$|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();let se=()=>{this.clearTimer();let ee=this.hls;if(this.fragCurrent===r&&ee.loadLevel===W&&W>0){let ue=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
|
|
25
25
|
Fragment duration: ${r.duration.toFixed(3)} s
|
|
26
|
-
Time to underbuffer: ${he.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Q>f){let te=this.findBestLevel(this.hls.levels[f].bitrate,f,Q,0,he,1,1);te===-1&&(te=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=te,this.resetEstimator(this.hls.levels[te].bitrate)}}};g||F>Y*2?ee():this.timer=self.setInterval(ee,Y*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new xa(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,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),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,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),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case k.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,u=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&u>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,u),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;V(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===W.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){let n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==W.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),u=this.getStarvationDelay(),d=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(u){let g=this.findBestLevel(l,a,r,u,0,d,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!u){let g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1)}let f=this.findBestLevel(l,a,r,u,h,d,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=i.levels[a],p=i.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;let u=r+n,d=this.lastLoadedFragLevel,c=d===-1?this.hls.firstLevel:d,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:v}=this.hls;if(m.length===1)return 0;let T=m[c],E=!!((l=this.hls.latestLevelDetails)!=null&&l.live),_=g===-1||d===-1,b,x="SDR",S=(T==null?void 0:T.frameRate)||0,{audioPreference:R,videoPreference:I}=v,A=this.audioTracksByGroup||(this.audioTracksByGroup=ic(p)),L=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;let M=this.codecTiers||(this.codecTiers=i0(m,A,t,i)),G=t0(M,x,e,R,I),{codecSet:K,videoRanges:Y,minFramerate:Q,minBitrate:$,minIndex:U,preferHDR:ee}=G;L=U,b=K,x=ee?Y[Y.length-1]:Y[0],S=Q,e=Math.max(e,$),this.log(`picked start tier ${Se(G)}`)}else b=T==null?void 0:T.codecSet,x=T==null?void 0:T.videoRange;let P=f?f.duration:h?h.duration:0,O=this.bwEstimator.getEstimateTTFB()/1e3,N=[];for(let M=i;M>=t;M--){var F;let G=m[M],K=M>c;if(!G)continue;if(v.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){let te=navigator.mediaCapabilities;typeof(te==null?void 0:te.decodingInfo)=="function"&&qp(G,A,x,S,e,R)?(G.supportedPromise=ec(G,A,te,this.supportedCache),G.supportedPromise.then(oe=>{if(!this.hls)return;G.supportedResult=oe;let Ve=this.hls.levels,$e=Ve.indexOf(G);oe.error?this.warn(`MediaCapabilities decodingInfo error: "${oe.error}" for level ${$e} ${Se(oe)}`):oe.supported?oe.decodingInfoResults.some(rt=>rt.smooth===!1||rt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${$e} not smooth or powerEfficient: ${Se(oe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${$e} ${Se(oe)}`),$e>-1&&Ve.length>1&&(this.log(`Removing unsupported level ${$e}`),this.hls.removeLevel($e),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(oe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${oe}`)})):G.supportedResult=Jd}if((b&&G.codecSet!==b||x&&G.videoRange!==x||K&&S>G.frameRate||!K&&S>0&&S<G.frameRate||(F=G.supportedResult)!=null&&(F=F.decodingInfoResults)!=null&&F.some(te=>te.smooth===!1))&&(!_||M!==L)){N.push(M);continue}let Y=G.details,Q=(f?Y==null?void 0:Y.partTarget:Y==null?void 0:Y.averagetargetduration)||P,$;K?$=o*e:$=a*e;let U=P&&r>=P*2&&n===0?G.averageBitrate:G.maxBitrate,ee=this.getTimeToLoadFrag(O,$,U*Q,Y===void 0);if($>=U&&(M===d||G.loadError===0&&G.fragmentError===0)&&(ee<=O||!V(ee)||E&&!this.bitrateTestDelay||ee<u)){let te=this.forcedAutoLevel;return M!==g&&(te===-1||te!==g)&&(N.length&&this.trace(`Skipped level(s) ${N.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[N[0]].codecs}" ${m[N[0]].videoRange}; not compatible with "${b}" ${x}`),this.info(`switch candidate:${c}->${M} adjustedbw(${Math.round($)})-bitrate=${Math.round($-U)} ttfb:${O.toFixed(1)} avgDuration:${Q.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${ee.toFixed(1)} firstSelection:${_} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${g}`)),_&&(this.firstSelection=M),M}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},sc={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function a0(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!V(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<s.length;++n){let a=s[n];if(l0(e,t,a))return a}return null}function Ai(s,e,t=0,i=0,r=.005){let n=null;if(s){n=e[1+s.sn-e[0].sn]||null;let o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&s.level!==n.level&&n.end<=s.end&&(n=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&Ku(t,i,n)===0||o0(n,s,Math.min(r,i))))return n;let a=sc.search(e,Ku.bind(null,t,i));return a&&(a!==s||!n)?a:n}function o0(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return!1}function Ku(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let 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 l0(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function rc(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments,{fragmentHint:r}=s;r&&(i=i.concat(r));let n;return sc.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function $r(s){switch(s.details){case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_TIMEOUT:case k.LEVEL_LOAD_TIMEOUT:case k.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function nc(s){return s.details.startsWith("key")}function ac(s){return nc(s)&&!!s.frag&&!s.frag.decryptdata}function Vu(s,e){let t=$r(e);return s.default[`${t?"timeout":"error"}Retry`]}function jo(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Hu(s){return ge(ge({},s),{errorRetry:null,timeoutRetry:null})}function Gr(s,e,t,i){if(!s)return!1;let r=i==null?void 0:i.code,n=e<s.maxNumRetry&&(u0(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function u0(s){return wa(s)||!!s&&(s<400||s>499)}function wa(s){return s===0&&navigator.onLine===!1}var Be={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ze={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Ca=class extends Je{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let 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(){let 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}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===W.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case k.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Wi();return}case k.FRAG_GAP:case k.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Be.SendAlternateToPenaltyBox;return}case k.LEVEL_EMPTY_ERROR:case k.LEVEL_PARSING_ERROR:{var a;let l=t.parent===W.MAIN?t.level:r.loadLevel;t.details===k.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_LOAD_ERROR:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===ae.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===ae.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Be.SendAlternateToPenaltyBox,t.errorAction.flags=Ze.MoveAllAlternatesMatchingHost;return}}return;case k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Be.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHDCP};return;case k.KEY_SYSTEM_SESSION_UPDATE_FAILED:case k.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case k.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Be.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingKey};return;case k.BUFFER_ADD_CODEC_ERROR:case k.REMUX_ALLOC_ERROR:case k.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel)}return;case k.INTERNAL_EXCEPTION:case k.BUFFER_APPENDING_ERROR:case k.BUFFER_FULL_ERROR:case k.LEVEL_SWITCH_ERROR:case k.BUFFER_STALLED_ERROR:case k.BUFFER_SEEK_OVER_HOLE:case k.BUFFER_NUDGE_ON_STALL:t.errorAction=Wi();return}t.type===z.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Wi())}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Vu(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Gr(r,n,$r(e),e.response))return{action:Be.RetryRequest,flags:Ze.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Vu(nc(e)?a:n,e),l=t.levels.reduce((d,c)=>d+c.fragmentError,0);if(r&&(e.details!==k.FRAG_GAP&&r.fragmentError++,!ac(e)&&Gr(o,l,$r(e),e.response)))return{action:Be.RetryRequest,flags:Ze.None,retryConfig:o,retryCount:l};let u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let u=e.details;r.loadError++,u===k.BUFFER_APPEND_ERROR&&r.fragmentError++;let d=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===W.AUDIO&&u===k.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(u===k.BUFFER_ADD_CODEC_ERROR||u===k.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:x})=>r.audioCodec!==x),E=e.sourceBufferName==="video"&&(u===k.BUFFER_ADD_CODEC_ERROR||u===k.BUFFER_APPEND_ERROR)&&c.some(({codecSet:x,audioCodec:S})=>r.codecSet!==x&&r.audioCodec===S),{type:_,groupId:b}=(a=e.context)!=null?a:{};for(let x=c.length;x--;){let S=(x+h)%c.length;if(S!==h&&S>=f&&S<=m&&c[S].loadError===0){var o,l;let R=c[S];if(u===k.FRAG_GAP&&p===W.MAIN&&e.frag){let I=c[S].details;if(I){let A=Ai(e.frag,I.fragments,e.frag.start);if(A!=null&&A.gap)continue}}else{if(_===ae.AUDIO_TRACK&&R.hasAudioGroup(b)||_===ae.SUBTITLE_TRACK&&R.hasSubtitleGroup(b))continue;if(p===W.AUDIO&&(o=r.audioGroups)!=null&&o.some(I=>R.hasAudioGroup(I))||p===W.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(I=>R.hasSubtitleGroup(I))||v&&r.audioCodec===R.audioCodec||E&&r.codecSet===R.codecSet||!v&&r.codecSet!==R.codecSet)continue}d=S;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:Be.SendAlternateToPenaltyBox,flags:Ze.None,nextAutoLevel:d}}return{action:Be.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Be.DoNothing:break;case Be.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==k.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case Be.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,n=i.nextAutoLevel;switch(r){case Ze.None:this.switchLevel(e,n);break;case Ze.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),u=t.levels[l],d=u==null?void 0:u.attrs["HDCP-LEVEL"];if(i.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=ka[ka.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ze.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let u=this.hls.levels,d=u.length;for(let h=d;h--;)if(this.variantHasKey(u[h],l)){var a,o;this.log(`Banned key found in level ${h} (${u[h].bitrate}bps) or audio group "${(a=u[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Ge(l.keyId||[])}`),u[h].fragmentError++,u[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}let c=e.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(c&&c.type!==W.MAIN){let h=c.decryptdata;h&&!l.matches(h)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(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,e.details===k.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Da(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}};function Wi(s){let e={action:Be.DoNothing,flags:Ze.None};return s&&(e.resolved=!0),e}var Oe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Oa=class{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(){let{hls:e}=this;e&&(e.on(y.MANIFEST_LOADING,this.onManifestLoading,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(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,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.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);let a=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{let l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===i&&this.removeFragment(l.body);return}let u=l.range[e];if(u){if(u.time.length===0){this.removeFragment(l.body);return}u.time.some(d=>{let c=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let i=e.frag,r=Bi(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(o=>{let l=i.elementaryStreams[o];if(!l)return;let u=t[o],d=a||l.partial===!0;n.range[o]=this.getBufferedTimes(i,e.part,d,u)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,i),gr(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=qu(i,r=>r.fragment.sn>=e))}fragBuffered(e,t){let i=Bi(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,u=e.maxStartPTS||a;for(let d=0;d<r.length;d++){let c=r.start(d)-this.bufferPadding,h=r.end(d)+this.bufferPadding;if(u>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(d)),endPTS:Math.min(o,r.end(d))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(d)),m=Math.min(o,r.end(d));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(u=>{let d=l[u];d&&gr(d)&&(r=d.body.start-o,n=d.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=d.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||gr(t))}getState(e){let t=Bi(e),i=this.fragments[t];return i?i.buffered?gr(i)?Oe.PARTIAL:Oe.OK:Oe.APPENDING:Oe.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,n=Bi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n,type:a}=t;if(i.sn==="initSegment")return;let o=i.type;if(r){let u=this.activePartLists[o];u||(this.activePartLists[o]=u=[]),u.push(r)}this.timeRanges=n;let l=n[a];this.detectEvictedFragments(a,l,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Bi(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let n=t[i[r]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=Bi(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=qu(i,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}};function gr(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Bi(s){return`${s.type}_${s.level}_${s.sn}`}function qu(s,e){return s.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Yt={cbc:0,ctr:1},Ma=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Yt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Yt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function d0(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}var Na=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,u=l[0],d=l[1],c=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let T=f[m],E=f[T],_=f[E],b=f[v]*257^v*16843008;r[m]=b<<24|b>>>8,n[m]=b<<16|b>>>16,a[m]=b<<8|b>>>24,o[m]=b,b=_*16843009^E*65537^T*257^m*16843008,u[v]=b<<24|b>>>8,d[v]=b<<16|b>>>16,c[v]=b<<8|b>>>24,h[v]=b,m?(m=T^f[f[f[_^T]]],p^=f[f[p]]):m=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,u=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],v=f[3],T,E;for(o=0;o<a;o++){if(o<n){T=u[o]=t[o];continue}E=T,o%n===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=h[o/n|0]<<24):n>6&&o%n===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),u[o]=T=(u[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=u[o]:E=u[o-4],l<4||o<=4?d[l]=E:d[l]=m[c[E>>>24]]^p[c[E>>>16&255]]^g[c[E>>>8&255]]^v[c[E&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],u=o[1],d=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(i),f=h[0],m=h[1],p=h[2],g=h[3],v=new Int32Array(e),T=new Int32Array(v.length),E,_,b,x,S,R,I,A,L,P,O,N,F,M,G=this.networkToHostOrderSwap;for(;t<v.length;){for(L=G(v[t]),P=G(v[t+1]),O=G(v[t+2]),N=G(v[t+3]),S=L^n[0],R=N^n[1],I=O^n[2],A=P^n[3],F=4,M=1;M<r;M++)E=l[S>>>24]^u[R>>16&255]^d[I>>8&255]^c[A&255]^n[F],_=l[R>>>24]^u[I>>16&255]^d[A>>8&255]^c[S&255]^n[F+1],b=l[I>>>24]^u[A>>16&255]^d[S>>8&255]^c[R&255]^n[F+2],x=l[A>>>24]^u[S>>16&255]^d[R>>8&255]^c[I&255]^n[F+3],S=E,R=_,I=b,A=x,F=F+4;E=a[S>>>24]<<24^a[R>>16&255]<<16^a[I>>8&255]<<8^a[A&255]^n[F],_=a[R>>>24]<<24^a[I>>16&255]<<16^a[A>>8&255]<<8^a[S&255]^n[F+1],b=a[I>>>24]<<24^a[A>>16&255]<<16^a[S>>8&255]<<8^a[R&255]^n[F+2],x=a[A>>>24]<<24^a[S>>16&255]<<16^a[R>>8&255]<<8^a[I&255]^n[F+3],T[t]=G(E^f),T[t+1]=G(x^m),T[t+2]=G(b^p),T[t+3]=G(_^g),f=L,m=P,p=O,g=N,t=t+4}return T.buffer}},Fa=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=c0(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function c0(s){switch(s){case Yt.cbc:return"AES-CBC";case Yt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}var h0=16,Ds=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?d0(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,r){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,r);let l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Yt.cbc||t.byteLength!==16)return pe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ot(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let u=this.softwareDecrypter;u||(u=this.softwareDecrypter=new Na),u.expandKey(t);let d=a;return this.currentResult=u.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Fa(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ma(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(pe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%h0;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(pe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Wu=Math.pow(2,17),Ua=class{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){let i=e.url;if(!i)return Promise.reject(new pt({type:z.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(ju(e));return}else e.gap=!1;let u=this.loader=n?new n(r):new a(r),d=Yu(e);e.loader=u;let c=Hu(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Wu};e.stats=u.stats;let f={onSuccess:(m,p,g,v)=>{this.resetLoader(e,u);let T=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v})},onError:(m,p,g,v)=>{this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ge({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:v}))},onAbort:(m,p,g)=>{this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}))}};t&&(f.onProgress=(m,p,g,v)=>t({frag:e,part:null,payload:g,networkDetails:v})),u.load(d,h,f)})}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ju(e,t));return}let u=this.loader=n?new n(r):new a(r),d=Yu(e,t);e.loader=u;let c=Hu(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Wu};t.stats=u.stats,u.load(d,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:g};i(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ge({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,u),l(new pt({type:z.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),u=Math.min(Math.round(i.loaded/n),l),c=(l-u)*Math.round(i.loaded/u);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=r.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 Yu(s,e=null){let t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(V(r)&&V(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&f0((a=s.decryptdata)==null?void 0:a.method)){let u=n-r;u%16&&(l=n+(16-u%16)),r!==0&&(i.resetIV=!0,o=r-16)}i.rangeStart=o,i.rangeEnd=l}return i}function ju(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:z.MEDIA_ERROR,details:k.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new pt(i)}function f0(s){return s==="AES-128"||s==="AES-256"}var pt=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Kr=class extends Je{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!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(){}},ks=class{constructor(e,t,i,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=pr(),this.buffering={audio:pr(),video:pr(),audiovideo:pr()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a}};function pr(){return{start:0,executeStart:0,executeEnd:0,end:0}}var zu={length:0,start:()=>0,end:()=>0},ie=class s{static isBuffered(e,t){if(e){let i=s.getBuffered(e);for(let r=i.length;r--;)if(t>=i.start(r)&&t<=i.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=s.getBuffered(e);return s.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=s.bufferedRanges(e);if(r.length)return s.bufferedInfo(r,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((d,c)=>d.start-c.start||c.end-d.end);let r=-1,n=[];if(i)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(r=d);let c=n.length;if(c){let h=n[c-1].end;e[d].start-h<i?e[d].end>h&&(n[c-1].end=e[d].end):n.push(e[d])}else n.push(e[d])}else n=e;let a=0,o,l=t,u=t;for(let d=0;d<n.length;d++){let c=n[d].start,h=n[d].end;if(r===-1&&t>=c&&t<=h&&(r=d),t+i>=c&&t<h)l=c,u=h,a=u-t;else if(t+i<c){o=c;break}}return{len:a,start:l||0,end:u||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||zu}catch(t){return pe.log("failed to get media.buffered",t),zu}}},oc=/\{\$([a-zA-Z0-9-_]+)\}/g;function Xu(s){return oc.test(s)}function Ba(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(oc,i=>{let r=i.substring(2,i.length-1),n=t==null?void 0:t[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function Qu(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function m0(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var g0=/^(\d+)x(\d+)$/,Ju=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ae=class s{constructor(e,t){typeof e=="string"&&(e=s.parseAttrList(e,t)),Ee(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let 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;let i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=g0.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={},n='"';for(Ju.lastIndex=0;(i=Ju.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,u=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":u=!0}if(t&&(l||u))o=Ba(t,o);else if(!u&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":pe.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},p0="com.apple.hls.interstitial";function y0(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function v0(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}var Vr=class{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){pe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Ee(new Ae({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);V(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(pe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(V(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===p0}get isValid(){return!!this.id&&!this._badValueForSameId&&V(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},E0=10,$a=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,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}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?V(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||E0}get drift(){let 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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function Hr(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function Zu(s,e){return!s&&!e?!0:!s||!e?!1:Hr(s,e)}function Yi(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function zo(s){switch(s){case"AES-128":case"AES-256":return Yt.cbc;case"AES-256-CTR":return Yt.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Xo(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Ga(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function T0(s){let e=Ga(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function lc(s){let e=function(i,r,n){let a=i[r];i[r]=i[n],i[n]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function uc(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=Xo(a)):t=T0(a)}}return t}var qr=typeof self!="undefined"?self:void 0,xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Dr(s){switch(s){case Ke.FAIRPLAY:return xe.FAIRPLAY;case Ke.PLAYREADY:return xe.PLAYREADY;case Ke.WIDEVINE:return xe.WIDEVINE;case Ke.CLEARKEY:return xe.CLEARKEY}}function aa(s){switch(s){case xe.FAIRPLAY:return Ke.FAIRPLAY;case xe.PLAYREADY:return Ke.PLAYREADY;case xe.WIDEVINE:return Ke.WIDEVINE;case xe.CLEARKEY:return Ke.CLEARKEY}}function _s(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[xe.FAIRPLAY,xe.WIDEVINE,xe.PLAYREADY,xe.CLEARKEY].filter(r=>!!e[r]):[];return!i[xe.WIDEVINE]&&t&&i.push(xe.WIDEVINE),i}var dc=function(s){return qr!=null&&(s=qr.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function _0(s,e,t,i){let r;switch(s){case xe.FAIRPLAY:r=["cenc","sinf"];break;case xe.WIDEVINE:case xe.PLAYREADY:r=["cenc"];break;case xe.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return S0(r,e,t,i)}function S0(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function b0(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function cc(s){let e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Xo(o).subarray(0,16);return lc(l),l}}return null}var $i={},Qi=class s{static clearKeyUriToKeyIdMap(){$i={}}static setKeyIdForUri(e,t){$i[e]=t}static addKeyIdForUri(e){let t=Object.keys($i).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),$i[e]=i,i}constructor(e,t,i,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Yi(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Kd(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Hr(e.keyFormatVersions,this.keyFormatVersions)&&Zu(e.iv,this.iv)&&Zu(e.keyId,this.keyId)}isSupported(){if(this.method){if(Yi(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ke.FAIRPLAY:case Ke.WIDEVINE:case Ke.PLAYREADY:case Ke.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Yi(this.method)){let n=this.iv;return n||(typeof e!="number"&&(pe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=x0(e)),new s(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=$i[this.uri];if(n&&!Hr(this.keyId,n)&&s.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=uc(this.uri);if(i)switch(this.keyFormat){case Ke.WIDEVINE:if(this.pssh=i,!this.keyId){let n=Np(i.buffer);if(n.length){var r;let a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=ed(t));break;case Ke.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Mp(n,null,i),this.keyId=cc(i);break}default:{let n=i.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=A0(t),n||(n=ed(t),n||(n=$i[this.uri])),n&&(this.keyId=n,s.setKeyIdForUri(this.uri,n))}return this}};function A0(s){let e=s==null?void 0:s[Ke.WIDEVINE];return e?e.keyId:null}function ed(s){let e=s==null?void 0:s[Ke.PLAYREADY];if(e){let t=uc(e.uri);if(t)return cc(t)}return null}function x0(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var td=/#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,id=/#EXT-X-MEDIA:(.*)/g,R0=/^#EXT(?:INF|-X-TARGETDURATION):/m,oa=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),I0=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Ti=class s{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Ho.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return R0.test(e)}static parseMasterPlaylist(e,t){let i=Xu(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(td.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=td.exec(e))!=null;)if(a[1]){var o;let u=new Ae(a[1],r),d=Ba(r,a[2]),c={attrs:u,bitrate:u.decimalInteger("BANDWIDTH")||u.decimalInteger("AVERAGE-BANDWIDTH"),name:u.NAME,url:s.resolve(d,t)},h=u.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),nd(u.CODECS,c);let f=u["SUPPLEMENTAL-CODECS"];f&&(c.supplemental={},nd(f,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),r.levels.push(c)}else if(a[3]){let u=a[3],d=a[4];switch(u){case"SESSION-DATA":{let c=new Ae(d,r),h=c["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=c);break}case"SESSION-KEY":{let c=sd(d,t,r);c.encrypted&&c.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(c)):pe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let c=new Ae(d,r);Qu(r,c,t)}break}case"CONTENT-STEERING":{let c=new Ae(d,r);r.contentSteering={uri:s.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=rd(d);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r,n={},a=i.levels,o={AUDIO:a.map(u=>({id:u.attrs.AUDIO,audioCodec:u.audioCodec})),SUBTITLES:a.map(u=>({id:u.attrs.SUBTITLES,textCodec:u.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(id.lastIndex=0;(r=id.exec(e))!==null;){let u=new Ae(r[1],i),d=u.TYPE;if(d){let c=o[d],h=n[d]||[];n[d]=h;let f=u.LANGUAGE,m=u["ASSOC-LANGUAGE"],p=u.CHANNELS,g=u.CHARACTERISTICS,v=u["INSTREAM-ID"],T={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:d,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?s.resolve(u.URI,t):""};if(m&&(T.assocLang=m),p&&(T.channels=p),g&&(T.characteristics=g),v&&(T.instreamId=v),c!=null&&c.length){let E=s.findGroup(c,T.groupId)||c[0];ad(T,E,"audioCodec"),ad(T,E,"textCodec")}h.push(T)}}return n}static parseLevelPlaylist(e,t,i,r,n,a){var o;let l={url:t},u=new $a(t),d=u.fragments,c=[],h=null,f=0,m=0,p=0,g=0,v=0,T=null,E=new Ss(r,l),_,b,x,S=-1,R=!1,I=null,A;if(oa.lastIndex=0,u.m3u8=e,u.hasVariableRefs=Xu(e),((o=oa.exec(e))==null?void 0:o[0])!=="#EXTM3U")return u.playlistParsingError=new Error("Missing format identifier #EXTM3U"),u;for(;(_=oa.exec(e))!==null;){R&&(R=!1,E=new Ss(r,l),E.playlistOffset=p,E.setStart(p),E.sn=f,E.cc=g,v&&(E.bitrate=v),E.level=i,h&&(E.initSegment=h,h.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),I&&(E.setByteRange(I),I=null)));let N=_[1];if(N){E.duration=parseFloat(N);let F=(" "+_[2]).slice(1);E.title=F||null,E.tagList.push(F?["INF",N,F]:["INF",N])}else if(_[3]){if(V(E.duration)){E.playlistOffset=p,E.setStart(p),x&&ld(E,x,u),E.sn=f,E.level=i,E.cc=g,d.push(E);let F=(" "+_[3]).slice(1);E.relurl=Ba(u,F),Ka(E,T,c),T=E,p+=E.duration,f++,m=0,R=!0}}else{if(_=_[0].match(I0),!_){pe.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<_.length&&_[b]===void 0;b++);let F=(" "+_[b]).slice(1),M=(" "+_[b+1]).slice(1),G=_[b+2]?(" "+_[b+2]).slice(1):null;switch(F){case"BYTERANGE":T?E.setByteRange(M,T):E.setByteRange(M);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=M,E.tagList.push(["PROGRAM-DATE-TIME",M]),S===-1&&(S=d.length);break;case"PLAYLIST-TYPE":u.type&&kt(u,F,_),u.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":u.startSN!==0?kt(u,F,_):d.length>0&&ud(u,F,_),f=u.startSN=parseInt(M);break;case"SKIP":{u.skippedSegments&&kt(u,F,_);let K=new Ae(M,u),Y=K.decimalInteger("SKIPPED-SEGMENTS");if(V(Y)){u.skippedSegments+=Y;for(let $=Y;$--;)d.push(null);f+=Y}let Q=K.enumeratedString("RECENTLY-REMOVED-DATERANGES");Q&&(u.recentlyRemovedDateranges=(u.recentlyRemovedDateranges||[]).concat(Q.split(" ")));break}case"TARGETDURATION":u.targetduration!==0&&kt(u,F,_),u.targetduration=Math.max(parseInt(M),1);break;case"VERSION":u.version!==null&&kt(u,F,_),u.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":u.live||kt(u,F,_),u.live=!1;break;case"#":(M||G)&&E.tagList.push(G?[M,G]:[M]);break;case"DISCONTINUITY":g++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([F]);break;case"BITRATE":E.tagList.push([F,M]),v=parseInt(M)*1e3,V(v)?E.bitrate=v:v=0;break;case"DATERANGE":{let K=new Ae(M,u),Y=new Vr(K,u.dateRanges[K.ID],u.dateRangeTagCount);u.dateRangeTagCount++,Y.isValid||u.skippedSegments?u.dateRanges[Y.id]=Y:pe.warn(`Ignoring invalid DATERANGE tag: "${M}"`),E.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{{let K=new Ae(M,u);"IMPORT"in K?m0(u,K,a):Qu(u,K,t)}break}case"DISCONTINUITY-SEQUENCE":u.startCC!==0?kt(u,F,_):d.length>0&&ud(u,F,_),u.startCC=g=parseInt(M);break;case"KEY":{let K=sd(M,t,u);if(K.isSupported()){if(K.method==="NONE"){x=void 0;break}x||(x={});let Y=x[K.keyFormat];Y!=null&&Y.matches(K)||(Y&&(x=Ee({},x)),x[K.keyFormat]=K)}else pe.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":u.startTimeOffset=rd(M);break;case"MAP":{let K=new Ae(M,u);if(E.duration){let Y=new Ss(r,l);od(Y,K,i,x),h=Y,E.initSegment=h,h.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime)}else{let Y=E.byteRangeEndOffset;if(Y){let Q=E.byteRangeStartOffset;I=`${Y-Q}@${Q}`}else I=null;od(E,K,i,x),h=E,R=!0}h.cc=g;break}case"SERVER-CONTROL":{A&&kt(u,F,_),A=new Ae(M),u.canBlockReload=A.bool("CAN-BLOCK-RELOAD"),u.canSkipUntil=A.optionalFloat("CAN-SKIP-UNTIL",0),u.canSkipDateRanges=u.canSkipUntil>0&&A.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=A.optionalFloat("PART-HOLD-BACK",0),u.holdBack=A.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{u.partTarget&&kt(u,F,_);let K=new Ae(M);u.partTarget=K.decimalFloatingPoint("PART-TARGET");break}case"PART":{let K=u.partList;K||(K=u.partList=[]);let Y=m>0?K[K.length-1]:void 0,Q=m++,$=new Ae(M,u),U=new La($,E,l,Q,Y);K.push(U),E.duration+=U.duration;break}case"PRELOAD-HINT":{let K=new Ae(M,u);u.preloadHint=K;break}case"RENDITION-REPORT":{let K=new Ae(M,u);u.renditionReports=u.renditionReports||[],u.renditionReports.push(K);break}default:pe.warn(`line parsed but not handled: ${_}`);break}}}T&&!T.relurl?(d.pop(),p-=T.duration,u.partList&&(u.fragmentHint=T)):u.partList&&(Ka(E,T,c),E.cc=g,u.fragmentHint=E,x&&ld(E,x,u)),u.targetduration||(u.playlistParsingError=new Error("Missing Target Duration"));let L=d.length,P=d[0],O=d[L-1];if(p+=u.skippedSegments*u.targetduration,p>0&&L&&O){u.averagetargetduration=p/L;let N=O.sn;u.endSN=N!=="initSegment"?N:0,u.live||(O.endList=!0),S>0&&(D0(d,S),P&&c.unshift(P))}return u.fragmentHint&&(p+=u.fragmentHint.duration),u.totalduration=p,c.length&&u.dateRangeTagCount&&P&&hc(c,u),u.endCC=g,u}};function hc(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];s.push(o),t++}else return;let i=s[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],u=l.startDate.getTime();l.tagAnchor=i.ref;for(let d=t;d--;){var a;if(((a=s[d])==null?void 0:a.sn)<e.startSN)break;let c=L0(e,u,s,d,r);if(c!==-1){l.tagAnchor=e.fragments[c].ref;break}}}}function L0(s,e,t,i,r){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let u=t[i].sn-s.startSN;if(u<0)return-1;let d=s.fragments;if(d.length>t.length){let h=(t[i+1]||d[d.length-1]).sn-s.startSN;for(let f=h;f>u;f--){let m=d[f].programDateTime;if(e>=m&&e<m+d[f].duration*1e3)return f}}return u}}}return-1}function sd(s,e,t){var i,r;let n=new Ae(s,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),u=n.KEYFORMATVERSIONS,d=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&pe.error(`Invalid IV: ${n.IV}`);let c=o?Ti.resolve(o,e):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Qi(a,c,d,h,l,n.KEYID)}function rd(s){let t=new Ae(s).decimalFloatingPoint("TIME-OFFSET");return V(t)?t:null}function nd(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let r=t.filter(n=>Wo(n,i));r.length&&(e[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function ad(s,e,t){let i=e[t];i&&(s[t]=i)}function D0(s,e){let t=s[e];for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Ka(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function od(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 ld(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s)}function kt(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ud(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function la(s,e){let t=e.startPTS;if(V(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&r.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function fc(s,e,t,i,r,n,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let l=t,u=i,d=e.startPTS,c=e.endPTS;if(V(d)){let v=Math.abs(d-t);s&&v>s.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${s.url}`):V(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,d),t=Math.min(t,d),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,u=Math.min(i,c),i=Math.max(i,c),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=u,e.endDTS=n;let f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let m,p=f-s.startSN,g=s.fragments;for(g[p]=e,m=p;m>0;m--)la(g[m],g[m-1]);for(m=p;m<g.length-1;m++)la(g[m],g[m+1]);return s.fragmentHint&&la(g[g.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,h}function k0(s,e,t){if(s===e)return;let i=null,r=s.fragments;for(let d=r.length-1;d>=0;d--){let c=r[d].initSegment;if(c){i=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;C0(s,e,(d,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==d.cc){let m=d.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}V(d.startPTS)&&V(d.endPTS)&&(c.setStart(c.startPTS=d.startPTS),c.startDTS=d.startDTS,c.maxStartPTS=d.maxStartPTS,c.endPTS=d.endPTS,c.endDTS=d.endDTS,c.minEndPTS=d.minEndPTS,c.setDuration(d.endPTS-d.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),d.hasStreams&&(c.elementaryStreams=d.elementaryStreams),c.loader=d.loader,d.hasStats&&(c.stats=d.stats),d.initSegment&&(c.initSegment=d.initSegment,i=d.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(d=>{var c;d&&(!d.initSegment||d.initSegment.relurl===((c=i)==null?void 0:c.relurl))&&(d.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(d=>!d),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=P0(s.dateRanges,e,t));let d=s.fragments.filter(c=>c.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Ka(o[c],o[c-1],d);hc(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let d=pc(s,e.startSN-1);e.startCC=(l=d==null?void 0:d.cc)!=null?l:a[0].cc}w0(s.partList,e.partList,(d,c)=>{c.elementaryStreams=d.elementaryStreams,c.stats=d.stats}),n?fc(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):mc(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let u=e.advancedDateTime;if(e.advanced&&u){let d=e.edge;e.driftStart||(e.driftStartTime=u,e.driftStart=d),e.driftEndTime=u,e.driftEnd=d}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function P0(s,e,t){let{dateRanges:i,recentlyRemovedDateranges:r}=e,n=Ee({},s);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let u=n[l],d=new Vr(i[l].attr,u);d.isValid?(n[l]=d,u||(d.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Se(i[l].attr)}"`)}),n):i}function w0(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){let a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function C0(s,e,t){let i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(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 u=r;u<=n;u++){let d=l[a+u],c=o[u];if(i&&!c&&d&&(c=e.fragments[u]=d),d&&c){t(d,c,u,o);let h=d.relurl,f=c.relurl;if(h&&O0(h,f)){e.playlistParsingError=dd(`media sequence mismatch ${c.sn}:`,s,e,d,c);return}else if(d.cc!==c.cc){e.playlistParsingError=dd(`discontinuity sequence mismatch (${d.cc}!=${c.cc})`,s,e,d,c);return}}}}function dd(s,e,t,i,r){return new Error(`${s} ${r.url}
|
|
26
|
+
Time to underbuffer: ${ue.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let ie=this.findBestLevel(ee.levels[f].bitrate,f,W,0,ue,1,1);ie===-1&&(ie=f),ee.nextLoadLevel=ee.nextAutoLevel=ie,this.firstAutoFloor=Math.min(ie,ee.firstLevel),this.resetEstimator(ee.levels[ie].bitrate)}}};p||U>G*2?se():this.timer=self.setInterval(se,G*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){let e=this.hls.config;return new fo(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case k.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&co(i,r)){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,u=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&u>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,u),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;H(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;let{frag:r,part:n}=t,a=n?n.stats:r.stats;if(r.type===j.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){let o=n?n.duration:r.duration,l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+a.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:d},l.realBitrate=Math.round(8*u/d)}if(r.bitrateTest){let o={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(E.FRAG_BUFFERED,o),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let o=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==j.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:i}=e,r=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(r,i,t,n/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,u=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,d=Math.min(Math.max(l,i),t,u);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${d}`),d}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),u=this.getStarvationDelay(),d=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(u){let p=this.findBestLevel(l,a,r,u,0,d,c);if(p>=0)return this.rebufferNotice=-1,p}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!u){let p=this.bitrateTestDelay;p&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1)}let f=this.findBestLevel(l,a,r,u,h,d,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=i.levels[a],m=i.loadLevelObj;return m&&(g==null?void 0:g.bitrate)<m.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e==null?void 0:e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,r,n,a,o){let{hls:l,lastLoadedFragLevel:u,fragCurrent:d,partCurrent:c}=this;if(!l)return-1;let h=r+n,f=u===-1?l.firstLevel:u,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:y,config:T}=l;if(g.length===1)return 0;let v=g[f],_=!!(y!=null&&y.live),S=p===-1||u===-1,A,b="SDR",x=(v==null?void 0:v.frameRate)||0,{audioPreference:L,videoPreference:R}=T,I=this.audioTracksByGroup||(this.audioTracksByGroup=bh(m)),P=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;let N=this.codecTiers||(this.codecTiers=ty(g,I,t,i)),F=ey(N,b,e,L,R),{codecSet:G,videoRanges:W,minFramerate:$,minBitrate:K,minIndex:se,preferHDR:ee}=F;P=se,A=G,b=ee?W[W.length-1]:W[0],x=$,e=Math.max(e,K),this.log(`picked start tier ${ke(F)}`)}else A=v==null?void 0:v.codecSet,b=v==null?void 0:v.videoRange;let w=c?c.duration:d?d.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,U=[];for(let N=i;N>=t;N--){var C;let F=g[N],G=N>f;if(!F)continue;if(T.useMediaCapabilities&&!F.supportedResult&&!F.supportedPromise){let ie=navigator.mediaCapabilities;typeof(ie==null?void 0:ie.decodingInfo)=="function"&&qv(F,I,b,x,e,L)?(F.supportedPromise=Th(F,I,ie,this.supportedCache),F.supportedPromise.then(ge=>{if(!this.hls)return;F.supportedResult=ge;let le=this.hls.levels,ve=le.indexOf(F);ge.error?this.warn(`MediaCapabilities decodingInfo error: "${ge.error}" for level ${ve} ${ke(ge)}`):ge.supported?ge.decodingInfoResults.some(Ge=>Ge.smooth===!1||Ge.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ve} not smooth or powerEfficient: ${ke(ge)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ve} ${ke(ge)}`),ve>-1&&le.length>1&&(this.log(`Removing unsupported level ${ve}`),this.hls.removeLevel(ve),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ge=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ge}`)})):F.supportedResult=yh}if((A&&F.codecSet!==A||b&&F.videoRange!==b||G&&x>F.frameRate||!G&&x>0&&x<F.frameRate||(C=F.supportedResult)!=null&&(C=C.decodingInfoResults)!=null&&C.some(ie=>ie.smooth===!1))&&(!S||N!==P)){U.push(N);continue}let W=F.details,$=(c?W==null?void 0:W.partTarget:W==null?void 0:W.averagetargetduration)||w||1,K;G?K=o*e:K=a*e;let se=w&&r>=w*2&&n===0?F.averageBitrate:F.maxBitrate,ee=this.getTimeToLoadFrag(B,K,se*$,!W||W.live);if(K>=se&&(N===u||F.loadError===0&&F.fragmentError===0||Qc(F,T.errorPenaltyExpireMs))&&(ee<=B||!H(ee)||_&&!this.bitrateTestDelay||ee<h)){let ie=this.forcedAutoLevel;return N!==p&&(ie===-1||ie!==p)&&(U.length&&this.trace(`Skipped level(s) ${U.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[U[0]].codecs}" ${g[U[0]].videoRange}; not compatible with "${A}" ${b}`),this.info(`switch candidate:${f}->${N} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-se)} ttfb:${B.toFixed(1)} avgDuration:${$.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${ee.toFixed(1)} firstSelection:${S} codecSet:${F.codecSet} videoRange:${F.videoRange} hls.loadLevel:${p}`)),S&&(this.firstSelection=N),N}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Rh={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function ny(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!H(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<s.length;++n){let a=s[n];if(oy(e,t,a))return a}return null}function ms(s,e,t=0,i=0,r=.005){let n=null;if(s){n=e[1+s.sn-e[0].sn]||null;let o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&s.level!==n.level&&n.end<=s.end&&(n=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&Ud(t,i,n)===0||ay(n,s,Math.min(r,i))))return n;let a=Rh.search(e,Ud.bind(null,t,i));return a&&(a!==s||!n)?a:n}function ay(s,e,t){if((e==null?void 0:e.start)===0&&e.level<s.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return!1}function Ud(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let 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 oy(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function xh(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments,{fragmentHint:r}=s;r&&(i=i.concat(r));let n;return Rh.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Ih(s,e){return e===s.endSN&&s.fragmentHint?s.fragmentHint:s.fragments[1+e-s.startSN]||null}var Qe={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Xe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},_o=class extends at{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===j.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case k.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Hs();return}case k.FRAG_GAP:case k.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Qe.SendAlternateToPenaltyBox;return}case k.PLAYLIST_UNCHANGED_ERROR:case k.LEVEL_EMPTY_ERROR:case k.LEVEL_PARSING_ERROR:{var a;let o=t.parent===j.MAIN?t.level:r.loadLevel;t.details===k.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_LOAD_ERROR:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let o=r.loadLevelObj;if(o&&(n.type===de.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===de.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Qe.SendAlternateToPenaltyBox,t.errorAction.flags=Xe.MoveAllAlternatesMatchingHost;return}}return;case k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Qe.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingHDCP};return;case k.KEY_SYSTEM_SESSION_UPDATE_FAILED:case k.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case k.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Qe.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingKey};return;case k.BUFFER_ADD_CODEC_ERROR:case k.REMUX_ALLOC_ERROR:case k.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case k.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Xe.ResetMediaSource|Xe.SwitchToSDR;return;case k.INTERNAL_EXCEPTION:case k.BUFFER_APPENDING_ERROR:case k.BUFFER_APPEND_NO_PROGRESS:case k.BUFFER_FULL_ERROR:case k.LEVEL_SWITCH_ERROR:case k.BUFFER_STALLED_ERROR:case k.BUFFER_SEEK_OVER_HOLE:case k.BUFFER_NUDGE_ON_STALL:t.errorAction=Hs();return}t.type===Q.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Hs())}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Rd(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(zs(r,n,un(e),e.response))return{action:Qe.RetryRequest,flags:Xe.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Rd(zc(e)?a:n,e),l=t.levels.reduce((d,c)=>d+c.fragmentError,0);if(r&&(e.details!==k.FRAG_GAP&&r.fragmentError++,!Xc(e)&&zs(o,l,un(e),e.response)))return{action:Qe.RetryRequest,flags:Xe.None,retryConfig:o,retryCount:l};let u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let u=e.details;r.loadError++,r.loadErrorTime=self.performance.now(),u===k.BUFFER_APPEND_ERROR&&r.fragmentError++;let d=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:g}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let m=(n=e.frag)==null?void 0:n.type,y=(m===j.AUDIO&&u===k.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&$d(e))&&c.some(({audioCodec:A})=>r.audioCodec!==A),v=e.sourceBufferName==="video"&&$d(e)&&c.some(({codecSet:A,audioCodec:b})=>r.codecSet!==A&&r.audioCodec===b),{type:_,groupId:S}=(a=e.context)!=null?a:{};for(let A=c.length;A--;){let b=(A+h)%c.length;if(b!==h&&b>=f&&b<=g&&(c[b].loadError===0||Qc(c[b],i.config.errorPenaltyExpireMs))){var o,l;let x=c[b];if(u===k.FRAG_GAP&&m===j.MAIN&&e.frag){let L=c[b].details;if(L){let R=ms(e.frag,L.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(_===de.AUDIO_TRACK&&x.hasAudioGroup(S)||_===de.SUBTITLE_TRACK&&x.hasSubtitleGroup(S))continue;if(m===j.AUDIO&&(o=r.audioGroups)!=null&&o.some(L=>x.hasAudioGroup(L))||m===j.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(L=>x.hasSubtitleGroup(L))||y&&r.audioCodec===x.audioCodec||v&&r.codecSet===x.codecSet||!y&&r.audioCodec!==x.audioCodec)continue}d=b;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:Qe.SendAlternateToPenaltyBox,flags:Xe.None,nextAutoLevel:d}}return{action:Qe.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,r;switch((i=t.errorAction)==null?void 0:i.action){case Qe.DoNothing:break;case Qe.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==k.FRAG_GAP&&t.details!==k.PLAYLIST_UNCHANGED_ERROR&&!Lh(t)&&(t.fatal=!0);break;case Qe.RetryRequest:break}if((((r=t.errorAction)==null?void 0:r.flags)||0)&Xe.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let r=i.nextAutoLevel;if(i.flags===Xe.None)this.switchLevel(e,r);else if(i.flags&Xe.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let u=l;u--;)o[u].videoRange!=="SDR"?(o[u].fragmentError++,o[u].loadError++):r===void 0&&(r=u)}else if(i.flags&Xe.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],u=l==null?void 0:l.attrs["HDCP-LEVEL"];i.hdcpLevel=u;let d=u==="NONE";u&&!d?(t.maxHdcpLevel=Eo[Eo.indexOf(u)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(d&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=Xe.MoveAllAlternatesMatchingKey)}if(i.flags&Xe.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,u=l.length;for(let c=u;c--;)if(this.variantHasKey(l[c],o)){var n,a;this.log(`Banned key found in level ${c} (${l[c].bitrate}bps) or audio group "${(n=l[c].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${We(o.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${e.error})`),this.hls.removeLevel(c)}let d=e.frag;if(this.hls.levels.length<u)i.resolved=!0;else if(d&&d.type!==j.MAIN){let c=d.decryptdata;c&&!o.matches(c)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(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,e.details===k.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=yo(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}};function $d(s){let e=s.details;return e===k.BUFFER_ADD_CODEC_ERROR||e===k.MEDIA_SOURCE_REQUIRES_RESET||e===k.BUFFER_APPEND_ERROR&&!Lh(s)}function Lh(s){return s.details===k.BUFFER_APPEND_ERROR&&(s.error.name==="QuotaExceededError"||s.error.name==="InvalidStateError")}function Hs(s){let e={action:Qe.DoNothing,flags:Xe.None};return s&&(e.resolved=!0),e}var Me={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},So=class{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(){let{hls:e}=this;e&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,r,n,a){this.timeRanges&&(this.timeRanges[e]=t);let o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(l=>{let u=this.fragments[l];if(!u||!this.hls)return;let d=u.body;if(o>=d.sn)return;if(!u.buffered&&(!u.loaded||a)){d.type===i&&this.removeFragment(d);return}let c=u.range[e];if(c){if(c.time.length===0){this.removeFragment(d);return}if(c.time.some(h=>{let f=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return f&&this.removeFragment(d),f}),r&&r!==d&&Vs()){let h=r.endPTS,f=d.startPTS;if(h&&f&&u.range.video){let g=f-h;g<0&&g>-.1&&(this.removeFragment(d),this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:h+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:r,id:n}=e;if(!t||!Ne(i))return;let a=as(i),o=this.fragments[a];if(!o||o.buffered&&i.gap)return;let l=!i.relurl;Object.keys(t).forEach(d=>{let c=i.elementaryStreams[d];if(!c)return;let h=t[d],f=l||c.partial===!0;o.range[d]=this.getBufferedTimes(i,r,f,h),this.detectEvictedFragments(d,h,n,i,r)}),o.loaded=null;let u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),Hr(o)||this.removeParts(i.sn-1,i.type),!r){let d=Math.min(.004,i.duration);u.some(c=>{var h;let f=(h=o.range[c])==null?void 0:h.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<d;return g&&this.addAsGap(i),g})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=Gd(i,r=>r.fragment.sn>=e))}fragBuffered(e,t){let i=as(e),r=this.fragments[i];return!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,u=e.maxStartPTS||a;for(let d=0;d<r.length;d++){let c=r.start(d)-this.bufferPadding,h=r.end(d)+this.bufferPadding;if(u>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(d)),endPTS:Math.min(o,r.end(d))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(d)),g=Math.min(o,r.end(d));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(u=>{let d=l[u];d&&Hr(d)&&(r=d.body.start-o,n=d.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=d.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Hr(t))}getState(e){let t=as(e),i=this.fragments[t];return i?i.buffered?Hr(i)?Me.PARTIAL:Me.OK:Me.APPENDING:Me.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Ne(t.frag)||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,n=as(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n}=t;if(!Ne(i))return;let a=i.type;if(r){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=as(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let n=t[i[r]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){let{fragments:r}=this,n=0,a=0,o=Object.keys(r);for(let l=0;l<o.length;l++){let u=r[o[l]];if(!u||!u.buffered||u.body.type!==t)continue;let d=u.body;if(d.gap)return 0;let c=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&d.bitrate*8*d.duration;if(d.end<=e&&c&&(n+=c,a=Math.max(a,d.end),n>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=as(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=Gd(i,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}};function Hr(s){var e,t,i,r;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial||(r=s.range.subs)!=null&&r.partial)}function as(s){return`${s.type}_${s.level}_${s.sn}`}function Gd(s,e){return s.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var vi={cbc:0,ctr:1},bo=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case vi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case vi.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function ly(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}var Ao=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,u=l[0],d=l[1],c=l[2],h=l[3],f=new Uint32Array(256),g=0,m=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let y=m^m<<1^m<<2^m<<3^m<<4;y=y>>>8^y&255^99,e[g]=y,t[y]=g;let T=f[g],v=f[T],_=f[v],S=f[y]*257^y*16843008;r[g]=S<<24|S>>>8,n[g]=S<<16|S>>>16,a[g]=S<<8|S>>>24,o[g]=S,S=_*16843009^v*65537^T*257^g*16843008,u[y]=S<<24|S>>>8,d[y]=S<<16|S>>>16,c[y]=S<<8|S>>>24,h[y]=S,g?(g=T^f[f[f[_^T]]],m^=f[f[m]]):g=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,u=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,g=f[0],m=f[1],p=f[2],y=f[3],T,v;for(o=0;o<a;o++){if(o<n){T=u[o]=t[o];continue}v=T,o%n===0?(v=v<<8|v>>>24,v=c[v>>>24]<<24|c[v>>>16&255]<<16|c[v>>>8&255]<<8|c[v&255],v^=h[o/n|0]<<24):n>6&&o%n===4&&(v=c[v>>>24]<<24|c[v>>>16&255]<<16|c[v>>>8&255]<<8|c[v&255]),u[o]=T=(u[o-n]^v)>>>0}for(l=0;l<a;l++)o=a-l,l&3?v=u[o]:v=u[o-4],l<4||o<=4?d[l]=v:d[l]=g[c[v>>>24]]^m[c[v>>>16&255]]^p[c[v>>>8&255]]^y[c[v&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],u=o[1],d=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(i),f=h[0],g=h[1],m=h[2],p=h[3],y=new Int32Array(e),T=new Int32Array(y.length),v,_,S,A,b,x,L,R,I,P,w,B,U,C,N=this.networkToHostOrderSwap;for(;t<y.length;){for(I=N(y[t]),P=N(y[t+1]),w=N(y[t+2]),B=N(y[t+3]),b=I^n[0],x=B^n[1],L=w^n[2],R=P^n[3],U=4,C=1;C<r;C++)v=l[b>>>24]^u[x>>16&255]^d[L>>8&255]^c[R&255]^n[U],_=l[x>>>24]^u[L>>16&255]^d[R>>8&255]^c[b&255]^n[U+1],S=l[L>>>24]^u[R>>16&255]^d[b>>8&255]^c[x&255]^n[U+2],A=l[R>>>24]^u[b>>16&255]^d[x>>8&255]^c[L&255]^n[U+3],b=v,x=_,L=S,R=A,U=U+4;v=a[b>>>24]<<24^a[x>>16&255]<<16^a[L>>8&255]<<8^a[R&255]^n[U],_=a[x>>>24]<<24^a[L>>16&255]<<16^a[R>>8&255]<<8^a[b&255]^n[U+1],S=a[L>>>24]<<24^a[R>>16&255]<<16^a[b>>8&255]<<8^a[x&255]^n[U+2],A=a[R>>>24]<<24^a[b>>16&255]<<16^a[x>>8&255]<<8^a[L&255]^n[U+3],T[t]=N(v^f),T[t+1]=N(A^g),T[t+2]=N(S^m),T[t+3]=N(_^p),f=I,g=P,m=w,p=B,t=t+4}return T.buffer}},Ro=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=uy(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function uy(s){switch(s){case vi.cbc:return"AES-CBC";case vi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}var dy=16,ir=class{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?r.start===0&&r.end>=i.length?i:i.slice(r.start,r.end):ly(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,r,n){return this.decryptRange=n,this.useSoftware||n?new Promise((a,o)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,r);let u=this.flush();u?a(u.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==vi.cbc||t.byteLength!==16)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=St(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let u=this.softwareDecrypter;u||(u=this.softwareDecrypter=new Ao),u.expandKey(t);let d=a;return this.currentResult=u.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ro(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bo(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%dy;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Te.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Kd=Math.pow(2,17),mn=class{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,i,r){let n=e.url;if(!n)return Promise.reject(new _t({type:Q.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,l=a.loader;return new Promise((u,d)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){d(Hd(e));return}else e.gap=!1;let c=this.loader=o?new o(a):new l(a),h=Vd(e,null,t);e.loader=c;let f=xd(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kd};c.stats.retry=e.stats.retry,e.stats=c.stats;let m={onSuccess:(p,y,T,v)=>{this.resetLoader(e,c);let _=p.data;T.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(_.slice(0,16)),_=_.slice(16)),u({frag:e,part:null,payload:_,networkDetails:v})},onError:(p,y,T,v)=>{this.resetLoader(e,c),d(new _t({type:Q.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:J({url:n,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:T,stats:v}))},onAbort:(p,y,T)=>{this.resetLoader(e,c),d(new _t({type:Q.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:T,stats:p}))},onTimeout:(p,y,T)=>{this.resetLoader(e,c),d(new _t({type:Q.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:T,stats:p}))}};if(i){let p=this.gateProgress(i,r);m.onProgress=(y,T,v,_)=>p({frag:e,part:null,payload:v,networkDetails:_})}c.load(h,g,m)})}gateProgress(e,t){let i=e;if(t){let r=[],n=!1;t.then(()=>{n=!0,r.forEach(a=>e(a)),r.length=0}).catch(()=>{}),i=a=>{n?e(a):r.push(a)}}return i}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Hd(e,t));return}let u=this.loader=n?new n(r):new a(r),d=Vd(e,t);e.loader=u;let c=xd(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kd};t.stats=u.stats,u.load(d,h,{onSuccess:(f,g,m,p)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,t);let y={frag:e,part:t,payload:f.data,networkDetails:p};i(y),o(y)},onError:(f,g,m,p)=>{this.resetLoader(e,u),l(new _t({type:Q.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:J({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,u),l(new _t({type:Q.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,u),l(new _t({type:Q.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),u=Math.min(Math.round(i.loaded/n),l),c=(l-u)*Math.round(i.loaded/u);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=r.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,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Vd(s,e=null,t){let i=e||s,r={type:de.MEDIA_FRAGMENT,frag:s,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=pn(s,e,t);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function pn(s,e=null,t){let i={},r=e||s,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(H(n)&&H(a)){var o;if((s.sn==="initSegment"||t)&&cy((o=s.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16,u=Math.ceil(a/16)*16;i.decryptRange={start:n-l,end:a-l},l>=16&&(i.resetIV=!0,l=l-16),i.byteRange={start:l,end:u}}else i.byteRange={start:n,end:a}}return i}function Hd(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Q.MEDIA_ERROR,details:k.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new _t(i)}function cy(s){return s==="AES-128"||s==="AES-256"}var _t=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},vn=class extends at{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!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):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},sr=class{constructor(e,t,i,r=0,n=-1,a=!1,o,l,u){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=qr(),this.buffering={audio:qr(),video:qr(),audiovideo:qr()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=u,this.iframe=l||!1}};function qr(){return{start:0,executeStart:0,executeEnd:0,end:0}}var qd={length:0,start:()=>0,end:()=>0},oe=class s{static isBuffered(e,t){if(e){let i=s.getBuffered(e);for(let r=i.length;r--;)if(t>=i.start(r)&&t<=i.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=s.getBuffered(e);return s.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=s.bufferedRanges(e);if(r.length)return s.bufferedInfo(r,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((d,c)=>d.start-c.start||c.end-d.end);let r=-1,n=[];if(i)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(r=d);let c=n.length;if(c){let h=n[c-1].end;e[d].start-h<i?e[d].end>h&&(n[c-1].end=e[d].end):n.push(e[d])}else n.push(e[d])}else n=e;let a=0,o,l=t,u=t;for(let d=0;d<n.length;d++){let c=n[d].start,h=n[d].end;if(r===-1&&t>=c&&t<=h&&(r=d),t+i>=c&&t<h)l=c,u=h,a=u-t;else if(t+i<c){o=c;break}}return{len:a,start:l||0,end:u||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||qd}catch(t){return Te.log("failed to get media.buffered",t),qd}}},xo=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wd(s){return xo.lastIndex=0,xo.test(s)}function Kl(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(xo,i=>{let r=i.substring(2,i.length-1),n=t==null?void 0:t[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function Yd(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function hy(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var fy=/^(\d+)x(\d+)$/,jd=/(.+?)=(".*?"|.*?)(?:,|$)/g,Oe=class s{constructor(e,t){typeof e=="string"&&(e=s.parseAttrList(e,t)),Re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let 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;let i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=fy.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={},n='"';for(jd.lastIndex=0;(i=jd.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,u=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":u=!0}if(t&&(l||u))o=Kl(t,o);else if(!u&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Te.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},gy="com.apple.hls.interstitial";function my(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function py(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}var yn=class{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Te.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Re(new Oe({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){let n=(t==null?void 0:t.endDate)||new Date(e["END-DATE"]);H(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(H(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===gy}get isValid(){return!!this.id&&!this._badValueForSameId&&H(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:H(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}},Dh=10,Io=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?H(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Dh}get drift(){let 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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function En(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function zd(s,e){return!s&&!e?!0:!s||!e?!1:En(s,e)}function hs(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Vl(s){switch(s){case"AES-128":case"AES-256":return vi.cbc;case"AES-256-CTR":return vi.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Lo(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function vy(s){let e=Lo(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function kh(s){let e=function(i,r,n){let a=i[r];i[r]=i[n],i[n]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function Ph(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=Ul(a)):t=vy(a)}}return t}var Tn=typeof self!="undefined"?self:void 0,we={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},et={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Wr(s){switch(s){case et.FAIRPLAY:return we.FAIRPLAY;case et.PLAYREADY:return we.PLAYREADY;case et.WIDEVINE:return we.WIDEVINE;case et.CLEARKEY:return we.CLEARKEY}}var Ch={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function qa(s){switch(s){case we.FAIRPLAY:return et.FAIRPLAY;case we.PLAYREADY:return et.PLAYREADY;case we.WIDEVINE:return et.WIDEVINE;case we.CLEARKEY:return et.CLEARKEY}}function Fs(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[we.FAIRPLAY,we.WIDEVINE,we.PLAYREADY,we.CLEARKEY].filter(r=>!!e[r]):[];return!i[we.WIDEVINE]&&t&&i.push(we.WIDEVINE),i}var wh=function(s){return Tn!=null&&(s=Tn.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function yy(s,e,t,i){let r;switch(s){case we.FAIRPLAY:r=["cenc","sinf"];break;case we.WIDEVINE:case we.PLAYREADY:r=["cenc"];break;case we.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Ey(r,e,t,i)}function Ey(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Ty(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Hl(s){let e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=Ot(e),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Ul(o).subarray(0,16);return kh(l),l}}return null}var os={},Wi=class s{static clearKeyUriToKeyIdMap(){os={}}static setKeyIdForUri(e,t){os[e]=t}static addKeyIdForUri(e){let t=Object.keys(os).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),os[e]=i,i}constructor(e,t,i,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!hs(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(rh(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&En(e.keyFormatVersions,this.keyFormatVersions)&&zd(e.iv,this.iv)&&zd(e.keyId,this.keyId)}isSupported(){if(this.method){if(hs(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case et.FAIRPLAY:case et.WIDEVINE:case et.PLAYREADY:case et.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var i;if(!this.encrypted||!this.uri)return null;if(hs(this.method)){let a=this.iv;return a||(typeof e!="number"&&(Te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=Sy(e)),new s(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=os[this.uri];if(a&&!En(this.keyId,a)&&s.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=Ph(this.uri);if(r)switch(this.keyFormat){case et.WIDEVINE:if(this.pssh=r,!this.keyId){let a=mh(r.buffer).filter(o=>o.systemId===Ch.WIDEVINE);if(a.length){var n;let o=a[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=Xd(t));break;case et.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=kv(a,null,r),this.keyId=Hl(r);break}default:{let a=r.subarray(0,16);if(a.length!==16){let o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((i=this.keyId)==null?void 0:i.byteLength)!==16){let a;a=_y(t),a||(a=Xd(t),a||(a=os[this.uri])),a&&(this.keyId=a,s.setKeyIdForUri(this.uri,a))}return this}};function _y(s){let e=s==null?void 0:s[et.WIDEVINE];return e?e.keyId:null}function Xd(s){let e=s==null?void 0:s[et.PLAYREADY];if(e){let t=Ph(e.uri);if(t)return Hl(t)}return null}function Sy(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var Qd=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Jd=/#EXT-X-MEDIA:(.*)/g,by=/^#EXT(?:INF|-X-TARGETDURATION):/m,Wa=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ay=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),fi=class s{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Ml.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return by.test(e)}static parseMasterPlaylist(e,t){let i=Wd(e),r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Qd.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=Qd.exec(e))!=null;)if(a[1]){let l=new Oe(a[1],r),u=Zd(l,a[2],t,r,n);u&&r.levels.push(u)}else if(a[3]){let l=a[3],u=a[4];switch(l){case"I-FRAME-STREAM-INF":{let d=new Oe(u,r),c=Zd(d,d.URI,t,r,n,!0);c&&r.iframeVariants.push(c)}break;case"SESSION-DATA":{let d=new Oe(u,r),c=d["DATA-ID"];c&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[c]=d);break}case"SESSION-KEY":{let d=ec(u,t,r);d.encrypted&&d.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(d)):Te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{let d=new Oe(u,r);Yd(r,d,t)}break}case"CONTENT-STEERING":{let d=new Oe(u,r);r.contentSteering={uri:s.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=tc(u);break}}}let o=n.length>0&&n.length<r.levels.length;return r.levels=o?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r,n={},a=i.levels,o={AUDIO:a.map(u=>({id:u.attrs.AUDIO,audioCodec:u.audioCodec})),SUBTITLES:a.map(u=>({id:u.attrs.SUBTITLES,textCodec:u.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(Jd.lastIndex=0;(r=Jd.exec(e))!==null;){let u=new Oe(r[1],i),d=u.TYPE;if(d){let c=o[d],h=n[d]||[];n[d]=h;let f=u.LANGUAGE,g=u["ASSOC-LANGUAGE"],m=u.CHANNELS,p=u.CHARACTERISTICS,y=u["INSTREAM-ID"],T={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:d,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?s.resolve(u.URI,t):""};if(g&&(T.assocLang=g),m&&(T.channels=m),p&&(T.characteristics=p),y&&(T.instreamId=y),c!=null&&c.length){let v=s.findGroup(c,T.groupId)||c[0];sc(T,v,"audioCodec"),sc(T,v,"textCodec")}h.push(T)}}return n}static parseLevelPlaylist(e,t,i,r,n,a){var o;let l={url:t},u=new Io(t),d=u.fragments,c=[],h=null,f=0,g=0,m=0,p=0,y=0,T=null,v=new ds(r,l),_,S,A,b=-1,x=!1,L=null,R;if(Wa.lastIndex=0,u.m3u8=e,u.hasVariableRefs=Wd(e),((o=Wa.exec(e))==null?void 0:o[0])!=="#EXTM3U")return u.playlistParsingError=new Error("Missing format identifier #EXTM3U"),u;for(;(_=Wa.exec(e))!==null;){x&&(x=!1,v=new ds(r,l),v.playlistOffset=m,v.setStart(m),v.sn=f,v.cc=p,y&&(v.bitrate=y),v.level=i,h&&(v.initSegment=h,h.rawProgramDateTime&&(v.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),L&&(v.setByteRange(L),L=null)));let U=_[1];if(U){v.duration=parseFloat(U);let C=(" "+_[2]).slice(1);v.title=C||null,v.tagList.push(C?["INF",U,C]:["INF",U])}else if(_[3]){if(H(v.duration)){var I;v.playlistOffset=m,v.setStart(m),A&&nc(v,A,u),v.sn=f,v.level=i,v.cc=p;let C=(" "+_[3]).slice(1);v.relurl=Kl(u,C),Do(v,T,c),T=v,m+=v.duration,f++,g=0;let N=v.byteRange;if(N.length===2&&(v.bitrate=(N[1]-N[0])*8/v.duration|0),u.iframesOnly&&N[0]&&((I=h)==null?void 0:I.cc)!==p){let F=new ds(r,l);F.relurl=v.relurl,F.setByteRange(`${Math.min(N[0],7*188)}@0`),F.level=i,F.sn="initSegment",A&&(F.levelkeys=A,A.identity&&(F._decryptdata=A.identity.getDecryptData(0))),h=F,v.initSegment=h}d.push(v),x=!0}}else{if(_=_[0].match(Ay),!_){Te.warn("No matches on slow regex match for level playlist!");continue}for(S=1;S<_.length&&_[S]===void 0;S++);let C=(" "+_[S]).slice(1),N=(" "+_[S+1]).slice(1),F=_[S+2]?(" "+_[S+2]).slice(1):null;switch(C){case"BYTERANGE":T?v.setByteRange(N,T):v.setByteRange(N);break;case"PROGRAM-DATE-TIME":v.rawProgramDateTime=N,v.tagList.push(["PROGRAM-DATE-TIME",N]),b===-1&&(b=d.length);break;case"PLAYLIST-TYPE":u.type&&Qt(u,C,_),u.type=N.toUpperCase();break;case"MEDIA-SEQUENCE":u.startSN!==0?Qt(u,C,_):T!==null&&Iy(u,C,_),u.startSN=parseInt(N),f=u.startSN+u.skippedSegments;break;case"SKIP":{u.skippedSegments&&Qt(u,C,_);let G=new Oe(N,u),W=G.decimalInteger("SKIPPED-SEGMENTS");if(H(W)){u.skippedSegments+=W;for(let K=W;K--;)d.push(null);f+=W}let $=G.enumeratedString("RECENTLY-REMOVED-DATERANGES");$&&(u.recentlyRemovedDateranges=(u.recentlyRemovedDateranges||[]).concat($.split(" ")));break}case"TARGETDURATION":u.targetduration!==0&&Qt(u,C,_),u.targetduration=Math.max(parseInt(N),1);break;case"VERSION":u.version!==null&&Qt(u,C,_),u.version=parseInt(N);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":u.iframesOnly=!0;break;case"ENDLIST":u.live||Qt(u,C,_),u.live=!1;break;case"#":(N||F)&&v.tagList.push(F?[N,F]:[N]);break;case"DISCONTINUITY":p++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([C]);break;case"BITRATE":v.tagList.push([C,N]),y=parseInt(N)*1e3,H(y)?v.bitrate=y:y=0;break;case"DATERANGE":{let G=new Oe(N,u),W=new yn(G,u.dateRanges[G.ID],u.dateRangeTagCount);u.dateRangeTagCount++,W.isValid||u.skippedSegments?u.dateRanges[W.id]=W:Te.log(`Ignoring invalid DATERANGE tag: ${W.invalidReason}: ${N}`),v.tagList.push(["EXT-X-DATERANGE",N]);break}case"DEFINE":{{let G=new Oe(N,u);"IMPORT"in G?hy(u,G,a):Yd(u,G,t)}break}case"DISCONTINUITY-SEQUENCE":u.startCC!==0&&Qt(u,C,_),u.startCC=p=parseInt(N),d.forEach(G=>G&&(G.cc=p));break;case"KEY":{let G=ec(N,t,u);if(G.isSupported()){if(G.method==="NONE"){A=void 0;break}A||(A={});let W=A[G.keyFormat];W!=null&&W.matches(G)||(W&&(A=Re({},A)),A[G.keyFormat]=G)}else Te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${N}"`);break}case"START":u.startTimeOffset=tc(N);break;case"MAP":{let G=new Oe(N,u);if(v.duration){let W=new ds(r,l);rc(W,G,i,A),h=W,v.initSegment=h,h.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=h.rawProgramDateTime)}else{let W=v.byteRangeEndOffset;if(W){let $=v.byteRangeStartOffset;L=`${W-$}@${$}`}else L=null;rc(v,G,i,A),h=v,x=!0}h.cc=p;break}case"SERVER-CONTROL":{R&&Qt(u,C,_),R=new Oe(N),u.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),u.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),u.canSkipDateRanges=u.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),u.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{u.partTarget&&Qt(u,C,_);let G=new Oe(N);u.partTarget=G.decimalFloatingPoint("PART-TARGET");break}case"PART":{let G=u.partList;G||(G=u.partList=[]);let W=g>0?G[G.length-1]:void 0,$=g++,K=new Oe(N,u),se=new ho(K,v,l,$,W);G.push(se),v.duration+=se.duration;break}case"PRELOAD-HINT":{let G=new Oe(N,u);u.preloadHint=G;break}case"RENDITION-REPORT":{let G=new Oe(N,u);u.renditionReports=u.renditionReports||[],u.renditionReports.push(G);break}default:Te.warn(`line parsed but not handled: ${_}`);break}}}T&&!T.relurl?(d.pop(),m-=T.duration,u.partList&&(u.fragmentHint=T)):u.partList&&(Do(v,T,c),v.cc=p,u.fragmentHint=v,A&&nc(v,A,u)),u.targetduration||(u.playlistParsingError=new Error("Missing Target Duration"));let P=d.length,w=d[0],B=d[P-1];if(m+=u.skippedSegments*u.targetduration,m>0&&P&&B){u.averagetargetduration=m/P;let U=B.sn;u.endSN=U!=="initSegment"?U:0,u.live||(B.endList=!0),b>0&&(xy(d,b,b>P-1?v:null),w&&c.unshift(w))}return u.fragmentHint&&(m+=u.fragmentHint.duration),u.totalduration=m,c.length&&u.dateRangeTagCount&&w&&Oh(c,u),u.endCC=p,u}};function Zd(s,e,t,i,r,n){var a;if(e===void 0)return null;let o=Kl(i,e),l={attrs:s,bitrate:s.decimalInteger("BANDWIDTH")||s.decimalInteger("AVERAGE-BANDWIDTH"),name:s.NAME,url:fi.resolve(o,t)},u=s.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),ic(s.CODECS,l);let d=s["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},ic(d,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||r.push(l),n&&(l.iframes=!0),l}function Oh(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];s.push(o),t++}else return;let i=s[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],u=l.startDate.getTime();l.tagAnchor=i.ref;for(let d=t;d--;){var a;if(((a=s[d])==null?void 0:a.sn)<e.startSN)break;let c=Ry(e,u,s,d,r);if(c){l.tagAnchor=c.ref;break}}}}function Ry(s,e,t,i,r){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let u=n.sn-s.startSN,d=s.fragments;if(u>=0&&u<d.length){if(d.length>t.length){let c=t[i+1]||d[d.length-1],h=Math.min(c.sn-s.startSN,d.length-1);for(let f=h;f>u;f--){let g=d[f].programDateTime;if(e>=g&&e<g+d[f].duration*1e3)return d[f]}}return d[u]}}}}return null}function ec(s,e,t){var i,r;let n=new Oe(s,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),u=n.KEYFORMATVERSIONS,d=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&Te.error(`Invalid IV: ${n.IV}`);let c=o?fi.resolve(o,e):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Wi(a,c,d,h,l,n.KEYID)}function tc(s){let t=new Oe(s).decimalFloatingPoint("TIME-OFFSET");return H(t)?t:null}function ic(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text","image"].forEach(i=>{let r=t.filter(n=>$l(n,i));r.length&&(e[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function sc(s,e,t){let i=e[t];i&&(s[t]=i)}function xy(s,e,t){if(t||(t=s[e]),!!t)for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Do(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function rc(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 nc(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s)}function Qt(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Iy(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Ya(s,e){let t=e.startPTS;if(H(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&r.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function Mh(s,e,t,i,r,n,a,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let u=t,d=i,c=e.startPTS,h=e.endPTS;if(H(c)){let T=Math.abs(c-t);s&&T>s.totalduration?o.warn(`media timestamps and playlist times differ by ${T}s for level ${e.level} ${s.url}`):H(e.deltaPTS)?e.deltaPTS=Math.max(T,e.deltaPTS):e.deltaPTS=T,u=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(i,h),i=Math.max(i,h),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=u,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;let g=e.sn;if(!s||g<s.startSN||g>s.endSN)return 0;let m,p=g-s.startSN,y=s.fragments;for(y[p]=e,m=p;m>0;m--)Ya(y[m],y[m-1]);for(m=p;m<y.length-1;m++)Ya(y[m],y[m+1]);return s.fragmentHint&&Ya(y[y.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,f}function Ly(s,e,t){if(s===e)return;let i=null,r=s.fragments;for(let d=r.length-1;d>=0;d--){let c=r[d].initSegment;if(c){i=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;Py(s,e,(d,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==d.cc){let g=d.cc-c.cc;for(let m=h;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}H(d.startPTS)&&H(d.endPTS)&&(c.setStart(c.startPTS=d.startPTS),c.startDTS=d.startDTS,c.maxStartPTS=d.maxStartPTS,c.endPTS=d.endPTS,c.endDTS=d.endDTS,c.minEndPTS=d.minEndPTS,c.setDuration(d.endPTS-d.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),d.hasStreams&&(c.elementaryStreams=d.elementaryStreams),c.loader=d.loader,d.hasStats&&(c.stats=d.stats),d.initSegment&&(c.initSegment=d.initSegment,i=d.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(d=>{var c;d&&(!d.initSegment||d.initSegment.relurl===((c=i)==null?void 0:c.relurl))&&(d.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(d=>!d),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Dy(s.dateRanges,e,t));let d=s.fragments.filter(c=>c.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Do(o[c],o[c-1],d);Oh(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let d=Bh(s,e.startSN-1);e.startCC=(l=d==null?void 0:d.cc)!=null?l:a[0].cc}if(ky(s.partList,e.partList,(d,c)=>{c.elementaryStreams=d.elementaryStreams,c.stats=d.stats,c.gap=d.gap||c.gap}),n){let d=e.iframesOnly&&n.type===j.MAIN;Mh(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,d,t)}else Nh(s,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let u=e.advancedDateTime;if(e.advanced&&u){let d=e.edge;e.driftStart||(e.driftStartTime=u,e.driftStart=d),e.driftEndTime=u,e.driftEnd=d}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function Dy(s,e,t){let{dateRanges:i,recentlyRemovedDateranges:r}=e,n=Re({},s);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let u=n[l],d=new yn(i[l].attr,u);d.isValid?(n[l]=d,u||(d.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ke(i[l].attr)}"`)}),n):i}function ky(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<n;r++){let a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Py(s,e,t){var i;let r=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,a=(s.fragmentHint?1:0)+(r?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=(i=s.fragmentHint)!=null&&i.duration?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=n;d<=a;d++){let c=u[o+d],h=l[d];if(r&&!h&&c&&(h=e.fragments[d]=c),c&&h){t(c,h,d,l);let f=c.relurl,g=h.relurl;if(f&&wy(f,g)){e.playlistParsingError=ac(`media sequence mismatch ${h.sn}:`,s,e,c,h);return}else if(c.cc!==h.cc){e.playlistParsingError=ac(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,s,e,c,h);return}}}}function ac(s,e,t,i,r){return new Error(`${s} ${r.url}
|
|
27
27
|
Playlist starting @${e.startSN}
|
|
28
28
|
${e.m3u8}
|
|
29
29
|
|
|
30
30
|
Playlist starting @${t.startSN}
|
|
31
|
-
${t.m3u8}`)}function mc(s,e,t=!0){let i=e.startSN+e.skippedSegments-s.startSN,r=s.fragments,n=i>=0,a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===s.endSN+1)a=s.fragmentEnd;else if(n&&t)a=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=s.fragmentStart;else return;Va(e,a)}function Va(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e)}}function gc(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){let i=s.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function pc(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function cd(s,e,t){return s?yc(s.partList,e,t):null}function yc(s,e,t){if(s)for(let i=s.length;i--;){let r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function vc(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function O0(s,e){return s!==e&&e?hd(s)!==hd(e):!1}function hd(s){return s.replace(/\?[^?]*$/,"")}function bs(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function M0(s,e){return!!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function fd(s,e){let t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Ec(s,e){let t=e.fragments;for(let i=0,r=t.length;i<r;i++)fd(t[i],s);e.fragmentHint&&fd(e.fragmentHint,s),e.alignedSliding=!0}function N0(s,e){s&&(Tc(e,s),e.alignedSliding||Wr(e,s),!e.alignedSliding&&!e.skippedSegments&&mc(s,e,!1))}function Tc(s,e){if(!M0(e,s))return;let t=Math.min(e.endCC,s.endCC),i=bs(e.fragments,t),r=bs(s.fragments,t);if(!i||!r)return;pe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=i.start-r.start;Ec(n,s)}function Wr(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;let t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n,a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(r=bs(i,a),n=bs(t,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=bs(t,r.cc)||t[Math.floor(t.length/2)]);let o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;let u=(l-o)/1e3-(n.start-r.start);Ec(u,s)}function Ye(s,e,t){Qe(s,e,t),s.addEventListener(e,t)}function Qe(s,e,t){s.removeEventListener(e,t)}var F0={toString:function(s){let e="",t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Ps=class extends Kr{constructor(e,t,i,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:u,state:d}=this,c=l?l.currentTime:0,h=ie.bufferInfo(u||l,c,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${V(c)?c.toFixed(3):c}, state: ${d}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,g=o.start+o.duration+m;if(f||g<h.start||p>h.end){let v=c>g;(c<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){let p=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,f&&(this.startPosition=c)),f&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new Ua(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ds(e.config)}registerListeners(){let{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_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{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_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=ie.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let d=l[l.length-1];return ie.isBuffered(this.media,d.start+d.duration/2)}let u=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(u)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;Ye(i,"seeking",this.onMediaSeeking),Ye(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Qe(r,"seeking",this.onMediaSeeking),Qe(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===Oe.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&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)===Oe.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{let r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:r}=this,{frag:n,payload:a}=i,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Yi(o.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,zo(o.method)).catch(u=>{throw r.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:n}),u}).then(u=>{let d=self.performance.now();return r.trigger(y.FRAG_DECRYPTED,{frag:n,payload:u,stats:{tstart:l,tdecrypt:d}}),i.payload=u,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,r;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?F0.toString(ie.getBuffered(i)):"(detached)"})`),Le(e)){var r;if(e.type!==W.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new ks(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(y.KEY_LOADED,h),this.state===C.KEY_LOADING&&(this.state=C.IDLE),h}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(Le(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=h)}if(i=Math.max(e.start,i||0),this.loadingParts&&Le(e)){let h=a.partList;if(h&&r){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(h,e,i);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=C.FRAG_LOADING;let p;return o?p=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(Le(e)&&this.loadingParts){var u;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(u=a.partList)==null?void 0:u.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),V(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;let d=this.config.progressive&&e.type!==W.SUBTITLE,c;return d&&o?c=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,d?r:void 0),o]).then(([h])=>(!d&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),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,r){return new Promise((n,a)=>{var o;let l=[],u=(o=i.details)==null?void 0:o.partList,d=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;let f=h.part;this.hls.trigger(y.FRAG_LOADED,h);let m=cd(i.details,e.sn,c.index+1)||yc(u,e.sn,c.index+1);if(m)d(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===k.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===z.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}let{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),u=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=u),this.updateLevelTiming(i,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;let n=e.partList[0];if(n.fragment.type===W.SUBTITLE)return!1;let a=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,u=a>-1?cd(l,n,a):null,d=u?u.fragment:pc(l,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:u,level:o}):null}bufferFragmentData(e,t,i,r,n){if(this.state!==C.PARSING)return;let{data1:a,data2:o}=e,l=a;if(o&&(l=ot(a,o)),!l.length)return;let u=this.initPTS[t.cc],d=u?-u.baseTime/u.timescale:void 0,c={type:e.type,frag:t,part:i,chunkMeta:r,offset:d,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!ie.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=ie.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;let r=this.getLoadPosition();if(!V(r))return null;let a=this.lastCurrentTime>r||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,i,r){let n=ie.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return ie.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,r);return n>=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=W.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,a=i[0].start,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var u;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(u=l)==null?void 0:u.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=a&&(l=i[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let d=this.filterReplacedPrimary(l,t);if(!d&&l){let c=l.sn-t.startSN;d=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return(i===Oe.OK||i===Oe.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(md(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(md(this.config)&&e.type!==W.SUBTITLE){let i=this.hls.interstitialsManager,r=i==null?void 0:i.bufferingItem;if(r){let a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&(t==null?void 0:t.live)===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=i==null?void 0:i.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){let u=e[o];if(a=a&&!u.independent,r>-1&&i<u.start)break;let d=u.loaded;d?r=-1:(n||(u.independent||a)&&u.fragment===t)&&(u.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${u.start}`),r=o),n=d}return r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--;){if(i=e[r],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=a0(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=rc(e,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:u}=r,d=i.partList,c=!!(this.loadingParts&&d!=null&&d.length&&l);c&&!this.bitrateTest&&d[d.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-u||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:u;h=Ai(n,a,e,p)}else h=a[a.length-1];if(h){let m=h.sn-i.startSN,p=this.fragmentTracker.getState(h);if((p===Oe.OK||p===Oe.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||d[0].fragment.sn>h.sn||!i.live)&&h.level===n.level){let v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==Oe.OK?h=v:h=null}}return h}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&V(n);if(a||!o&&!n){N0(i,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}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;i<t&&(i=-1);let r=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&V(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var e;let{media:t}=this,i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Le(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===k.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);let o=t.errorAction;if(!o){this.state=C.ERROR;return}let{action:l,flags:u,retryCount:d=0,retryConfig:c}=o,h=!!c,f=h&&l===Be.RetryRequest,m=h&&!o.resolved&&u===Ze.MoveAllAlternatesMatchingHost,p=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&m&&Le(r)&&!r.endList&&p&&!ac(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||m)&&d<c.maxNumRetry){var g;let v=wa((g=t.response)==null?void 0:g.code),T=jo(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${T}ms`)}else if(c)if(this.resetFragmentErrors(e),d<c.maxNumRetry)!a&&l!==Be.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else l===Be.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!wa(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===W.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;let r=ie.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){let n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,u)=>{let d=e.elementaryStreams[u];if(d){let c=d.endPTS-d.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${u} duration reliably (${c})`),l||!1;let h=r?0:fc(n,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:u,frag:e,start:d.startPTS,end:d.endPTS}),!0}return l},!1)){var o;let l=((o=this.transmuxer)==null?void 0:o.error)===null;if((i.fragmentError===0||l&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),l){let u=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(u.message),this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:u,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===W.MAIN?"level":"track"}fragInfo(e,t=!0,i){var r,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((r=t&&!i?e.startPTS:(i||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function md(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}var Yr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=U0(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function U0(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r<s.length;r++){let n=s[r];t.set(n,i),i+=n.length}return t}var ua={exports:{}},gd;function B0(){return gd||(gd=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,u,d){this.fn=l,this.context=u,this.once=d||!1}function n(l,u,d,c,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new r(d,c||l,h),m=t?t+u:u;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,u){--l._eventsCount===0?l._events=new i:delete l._events[u]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],d,c;if(this._eventsCount===0)return u;for(c in d=this._events)e.call(d,c)&&u.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},o.prototype.listeners=function(u){var d=t?t+u:u,c=this._events[d];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,m=new Array(f);h<f;h++)m[h]=c[h].fn;return m},o.prototype.listenerCount=function(u){var d=t?t+u:u,c=this._events[d];return c?c.fn?1:c.length:0},o.prototype.emit=function(u,d,c,h,f,m){var p=t?t+u:u;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,T,E;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,d),!0;case 3:return g.fn.call(g.context,d,c),!0;case 4:return g.fn.call(g.context,d,c,h),!0;case 5:return g.fn.call(g.context,d,c,h,f),!0;case 6:return g.fn.call(g.context,d,c,h,f,m),!0}for(E=1,T=new Array(v-1);E<v;E++)T[E-1]=arguments[E];g.fn.apply(g.context,T)}else{var _=g.length,b;for(E=0;E<_;E++)switch(g[E].once&&this.removeListener(u,g[E].fn,void 0,!0),v){case 1:g[E].fn.call(g[E].context);break;case 2:g[E].fn.call(g[E].context,d);break;case 3:g[E].fn.call(g[E].context,d,c);break;case 4:g[E].fn.call(g[E].context,d,c,h);break;default:if(!T)for(b=1,T=new Array(v-1);b<v;b++)T[b-1]=arguments[b];g[E].fn.apply(g[E].context,T)}}return!0},o.prototype.on=function(u,d,c){return n(this,u,d,c,!1)},o.prototype.once=function(u,d,c){return n(this,u,d,c,!0)},o.prototype.removeListener=function(u,d,c,h){var f=t?t+u:u;if(!this._events[f])return this;if(!d)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===d&&(!h||m.once)&&(!c||m.context===c)&&a(this,f);else{for(var p=0,g=[],v=m.length;p<v;p++)(m[p].fn!==d||h&&!m[p].once||c&&m[p].context!==c)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(u){var d;return u?(d=t?t+u:u,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o}(ua)),ua.exports}var $0=B0(),Qo=Tp($0),ws="1.6.15",Ji={};function G0(){return typeof __HLS_WORKER_BUNDLE__=="function"}function K0(){let s=Ji[ws];if(s)return s.clientCount++,s;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return Ji[ws]=r,r}function V0(s){let e=Ji[s];if(e)return e.clientCount++,e;let t=new self.URL(s,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Ji[s]=r,r}function H0(s){let e=Ji[s||ws];if(e&&e.clientCount--===1){let{worker:i,objectURL:r}=e;delete Ji[s||ws],r&&self.URL.revokeObjectURL(r),i.terminate()}}function _c(s,e){return 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}function Jo(s,e){return 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}function ln(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}function Cs(s,e){let t=e,i=0;for(;Jo(s,e);){i+=10;let r=ln(s,e+6);i+=r,_c(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)}function q0(s,e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);s.emit(y.ERROR,y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,u="mp4a.40."+o,d=r[a],c=a;(o===5||o===29)&&(c-=3);let h=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return pe.log(`manifest codec:${i}, parsed codec:${u}, channels:${l}, rate:${d} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:d,channelCount:l,codec:u,parsedCodec:u,manifestCodec:i}}function Sc(s,e){return s[e]===255&&(s[e+1]&246)===240}function bc(s,e){return s[e+1]&1?7:9}function Zo(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function W0(s,e){return e+5<s.length}function jr(s,e){return e+1<s.length&&Sc(s,e)}function Y0(s,e){return W0(s,e)&&Sc(s,e)&&Zo(s,e)<=s.length-e}function j0(s,e){if(jr(s,e)){let t=bc(s,e);if(e+t>=s.length)return!1;let i=Zo(s,e);if(i<=t)return!1;let r=e+i;return r===s.length||jr(s,r)}return!1}function Ac(s,e,t,i,r){if(!s.samplerate){let n=q0(e,t,i,r);if(!n)return;Ee(s,n)}}function xc(s){return 1024*9e4/s}function z0(s,e){let t=bc(s,e);if(e+t<=s.length){let i=Zo(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Rc(s,e,t,i,r){let n=xc(s.samplerate),a=i+r*n,o=z0(e,t),l;if(o){let{frameLength:c,headerLength:h}=o,f=h+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:a};return m||s.samples.push(p),{sample:p,length:f,missing:m}}let u=e.length-t;return l=new Uint8Array(u),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:u,missing:-1}}function X0(s,e){return Jo(s,e)&&ln(s,e+6)+10<=s.length-e}function Q0(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function da(s,e=0,t=1/0){return J0(s,e,t,Uint8Array)}function J0(s,e,t,i){let r=Z0(s),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=ey(s)?s.byteOffset:0,o=(a+s.byteLength)/n,l=(a+e)/n,u=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(u+Math.max(t,0),o));return new i(r,u,d-u)}function Z0(s){return s instanceof ArrayBuffer?s:s.buffer}function ey(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function ty(s){let e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=s.data.subarray(1).indexOf(0);if(i===-1)return;let r=it(da(s.data,1,i)),n=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=it(da(s.data,3+i,a)),l;return r==="-->"?l=it(da(s.data,4+i+a)):l=Q0(s.data.subarray(4+i+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function iy(s){if(s.size<2)return;let e=it(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function sy(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1,i=it(s.data.subarray(t),!0);t+=i.length+1;let r=it(s.data.subarray(t));return{key:s.type,info:i,data:r}}let e=it(s.data.subarray(1));return{key:s.type,info:"",data:e}}function ry(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=it(s.data.subarray(t),!0);t+=i.length+1;let r=it(s.data.subarray(t));return{key:s.type,info:i,data:r}}let e=it(s.data);return{key:s.type,info:"",data:e}}function ny(s){return s.type==="PRIV"?iy(s):s.type[0]==="W"?ry(s):s.type==="APIC"?ty(s):sy(s)}function ay(s){let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=ln(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}var yr=10,oy=10;function Ic(s){let e=0,t=[];for(;Jo(s,e);){let i=ln(s,e+6);s[e+5]>>6&1&&(e+=yr),e+=yr;let r=e+i;for(;e+oy<r;){let n=ay(s.subarray(e)),a=ny(n);a&&t.push(a),e+=n.size+yr}_c(s,e)&&(e+=yr)}return t}function Lc(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function ly(s){if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function el(s){let e=Ic(s);for(let t=0;t<e.length;t++){let i=e[t];if(Lc(i))return ly(i)}}var tt=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function At(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var Os=class{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,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=ot(this.cachedData,e),this.cachedData=null);let i=Cs(e,0),r=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?el(i):void 0,u=e.length;for((this.basePTS===null||this.frameIndex===0&&V(l))&&(this.basePTS=uy(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:tt.audioId3,duration:Number.POSITIVE_INFINITY});r<u;){if(this.canParse(e,r)){let d=this.appendFrame(a,e,r);d?(this.frameIndex++,this.lastPTS=d.sample.pts,r+=d.length,n=r):r=u}else X0(e,r)?(i=Cs(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:tt.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===u&&n!==u){let d=e.slice(n);this.cachedData?this.cachedData=ot(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:At(),id3Track:o,textTrack:At()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:At(),id3Track:this._id3Track,textTrack:At()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},uy=(s,e,t)=>{if(V(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},vr=null,dy=[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],cy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fy=[0,1,1,4];function Dc(s,e,t,i,r){if(t+24>e.length)return;let n=kc(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function kc(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,u=dy[l*14+r-1]*1e3,c=cy[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=hy[t][i],m=fy[i],p=f*8*m,g=Math.floor(f*u/c+a)*m;if(vr===null){let E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vr=E?parseInt(E[1]):0}return!!vr&&vr<=87&&i===2&&u>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function tl(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Pc(s,e){return e+1<s.length&&tl(s,e)}function my(s,e){return tl(s,e)&&4<=s.length-e}function wc(s,e){if(e+1<s.length&&tl(s,e)){let i=kc(s,e),r=4;i!=null&&i.frameLength&&(r=i.frameLength);let n=e+r;return n===s.length||Pc(s,n)}return!1}var Ha=class extends Os{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=Cs(e,0),r=(i==null?void 0:i.length)||0;if(wc(e,r))return!1;for(let n=e.length;r<n;r++)if(j0(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Y0(e,t)}appendFrame(e,t,i){Ac(e,this.observer,t,i,e.manifestCodec);let r=Rc(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},Cc=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o}return t},qa=class extends Os{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=Oc(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Cs(e,0);if(!t)return!1;let i=t.length;return e[i]===11&&e[i+1]===119&&el(t)!==void 0&&Cc(e,i)<16}};function Oc(s,e,t,i,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,d=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+d>e.length)return-1;let c=e[t+6]>>5,h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][c]+f,g=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,_=i+r*E,b=e.subarray(t,t+d);return s.config=T,s.channelCount=p,s.samplerate=o,s.samples.push({unit:b,pts:_}),d}var Wa=class extends Os{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Cs(e,0),i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&el(t)!==void 0&&Cc(e,i)<=16)return!1;for(let r=e.length;i<r;i++)if(wc(e,i))return pe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return my(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Dc(e,t,i,this.basePTS,this.frameIndex)}},gy=/\/emsg[-/]ID3/i,Ya=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){let n=this.videoTrack=At("video",1),a=this.audioTrack=At("audio",1),o=this.txtTrack=At("text",1);if(this.id3Track=At("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=Yd(e);if(l.video){let{id:u,timescale:d,codec:c,supplemental:h}=l.video;n.id=u,n.timescale=o.timescale=d,n.codec=c,n.supplemental=h}if(l.audio){let{id:u,timescale:d,codec:c}=l.audio;a.id=u,a.timescale=d,a.codec=c}o.id=Hd.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Ap(e)}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ot(this.remainderData,e));let o=Pp(i);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=i;let a=this.extractID3Track(r,t);return n.samples=Ou(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=Ou(e,t),{videoTrack:t,audioTrack:At(),id3Track:r,textTrack:At()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=re(e.samples,["emsg"]);r&&r.forEach(n=>{let a=Cp(n);if(gy.test(a.schemeIdUri)){let o=pd(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let u=a.payload;i.samples.push({data:u,len:u.byteLength,dts:o,pts:o,type:tt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=pd(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:tt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function pd(s,e){return V(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}var ja=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ds(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Yt.cbc)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(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){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){let a=Xd(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}).catch(r)}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}},zr=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let r=t.byteLength,n=e.naluState||0,a=n,o=[],l=0,u,d,c,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(u=t[l++],!n){n=u?0:1;continue}if(n===1){n=u?0:2;continue}if(!u)n=3;else if(u===1){if(d=l-n-1,h>=0){let m={data:t.subarray(h,d),type:f};o.push(m)}else{let m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),d>0&&(m.data=ot(m.data,t.subarray(0,d)),m.state=0))}l<r?(c=this.getNALuType(t,l),h=l,f=c,n=0):n=-1}else n=0}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};o.push(m)}if(o.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=ot(m.data,t))}return e.naluState=n,o}},Si=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(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),i=this.word>>>32-t;if(e>32&&pe.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<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)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(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let 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)}},za=class extends zr{parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=!1;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(u=>{var d,c;switch(u.type){case 1:{let p=!1;o=!0;let g=u.data;if(l&&g.length>4){let v=this.readSliceType(g);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,qo(u.data,1,i.pts,t.samples);break}case 7:{var f,m;o=!0,l=!0;let p=u.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];let v=p.subarray(1,4),T="avc1.";for(let E=0;E<3;E++){let _=v[E].toString(16);_.length<2&&(_="0"+_),T+=_}e.codec=T}break}case 8:o=!0,e.pps=[u.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(u)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Si(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(i+n+256)%256),i=r===0?i:r}readSPS(e){let t=new Si(e),i=0,r=0,n=0,a=0,o,l,u,d=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);d();let T=d();if(c(5),m(3),d(),g(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let R=h();if(R===3&&m(1),g(),g(),m(1),f())for(l=R!==3?8:12,u=0;u<l;u++)f()&&(u<6?v(16,t):v(64,t))}g();let E=h();if(E===0)h();else if(E===1)for(m(1),p(),p(),o=h(),u=0;u<o;u++)p();g(),m(1);let _=h(),b=h(),x=c(1);x===0&&m(1),m(1),f()&&(i=h(),r=h(),n=h(),a=h());let S=[1,1];if(f()&&f())switch(d()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((_+1)*16-i*2-r*2),height:(2-x)*(b+1)*16-(x?2:4)*(n+a),pixelRatio:S}}},Xa=class extends zr{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=!1;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(u=>{var d,c;switch(u.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,qo(u.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Ee(e.params,this.readVPS(u.data)),this.initVPS=u.data),e.vps=[u.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],u.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(u.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m]}this.pushParameterSet(e.sps,u.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(u.data);for(let m in f)e.params[m]=f[m]}this.pushParameterSet(e.pps,u.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}a&&o&&a.units.push(u)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new Si(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:r}}readSPS(e){let t=new Si(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),T=[],E=[];for(let fe=0;fe<i;fe++)T.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let fe=i;fe<8;fe++)t.readBits(2);for(let fe=0;fe<i;fe++)T[fe]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[fe]&&t.readUByte();t.readUEG();let _=t.readUEG();_==3&&t.skipBits(1);let b=t.readUEG(),x=t.readUEG(),S=t.readBoolean(),R=0,I=0,A=0,L=0;S&&(R+=t.readUEG(),I+=t.readUEG(),A+=t.readUEG(),L+=t.readUEG());let P=t.readUEG(),O=t.readUEG(),N=t.readUEG(),F=t.readBoolean();for(let fe=F?0:i;fe<=i;fe++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let He=0;He<4;He++)for(let nt=0;nt<(He===3?2:6);nt++)if(!t.readBoolean())t.readUEG();else{let ut=Math.min(64,1<<4+(He<<1));He>1&&t.readEG();for(let Mi=0;Mi<ut;Mi++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let K=t.readUEG(),Y=0;for(let fe=0;fe<K;fe++){let He=!1;if(fe!==0&&(He=t.readBoolean()),He){fe===K&&t.readUEG(),t.readBoolean(),t.readUEG();let nt=0;for(let di=0;di<=Y;di++){let ut=t.readBoolean(),Mi=!1;ut||(Mi=t.readBoolean()),(ut||Mi)&&nt++}Y=nt}else{let nt=t.readUEG(),di=t.readUEG();Y=nt+di;for(let ut=0;ut<nt;ut++)t.readUEG(),t.readBoolean();for(let ut=0;ut<di;ut++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let fe=t.readUEG();for(let He=0;He<fe;He++){for(let nt=0;nt<N+4;nt++)t.readBits(1);t.readBits(1)}}let $=0,U=1,ee=1,he=!0,te=1,oe=0;t.readBoolean(),t.readBoolean();let Ve=!1;if(t.readBoolean()){if(t.readBoolean()){let ci=t.readUByte(),Hl=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ir=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ci>0&&ci<16?(U=Hl[ci-1],ee=ir[ci-1]):ci===255&&(U=t.readBits(16),ee=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Ve=t.readBoolean(),Ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(te=t.readBits(32),oe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let ir=t.readBoolean(),ql=t.readBoolean(),ds=!1;(ir||ql)&&(ds=t.readBoolean(),ds&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ds&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Wl=0;Wl<=i;Wl++){he=t.readBoolean();let Nf=he||t.readBoolean(),Yl=!1;Nf?t.readEG():Yl=t.readBoolean();let jl=Yl?1:t.readUEG()+1;if(ir)for(let cs=0;cs<jl;cs++)t.readUEG(),t.readUEG(),ds&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ql)for(let cs=0;cs<jl;cs++)t.readUEG(),t.readUEG(),ds&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readUEG())}let rt=b,Et=x;if(S){let fe=1,He=1;_===1?fe=He=2:_==2&&(fe=2),rt=b-fe*I-fe*R,Et=x-He*L-He*A}let ui=r?["A","B","C"][r]:"",Mf=o<<24|l<<16|u<<8|d,Bn=0;for(let fe=0;fe<32;fe++)Bn=(Bn|(Mf>>fe&1)<<31-fe)>>>0;let $n=Bn.toString(16);return a===1&&$n==="2"&&($n="6"),{codecString:`hvc1.${ui}${a}.${$n}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,u,d],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:$,chroma_format_idc:_,frame_rate:{fixed:he,fps:oe/te}},width:rt,height:Et,pixelRatio:[U,ee]}}readPPS(e){let t=new Si(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Ue=188,Qa=class s{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){let i=s.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(Ue*5,t-Ue)+1,r=0;for(;r<i;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Ue)if(e[l]===71&&(t-l===Ue||e[l+Ue]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+Ue*99,e.length-Ue)+1)),n||(n=Ja(e,l)===0),n&&o>1&&(a===0&&o>2||l+Ue>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Hd[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){i||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,d=a.pid,c=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,g=null,v=this.pmtParsed,T=this._pmtId,E=e.length;if(this.remainderData&&(e=ot(this.remainderData,e),E=e.length,this.remainderData=null),E<Ue&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:u};let _=Math.max(0,s.syncOffset(e));E-=(E-_)%Ue,E<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let b=0;for(let S=_;S<E;S+=Ue)if(e[S]===71){let R=!!(e[S+1]&64),I=Ja(e,S),A=(e[S+3]&48)>>4,L;if(A>1){if(L=S+5+e[S+4],L===S+Ue)continue}else L=S+4;switch(I){case d:R&&(c&&(n=Gi(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,u,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(L,S+Ue)),c.size+=S+Ue-L);break;case h:if(R){if(m&&(n=Gi(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(L,S+Ue)),m.size+=S+Ue-L);break;case f:R&&(p&&(n=Gi(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(L,S+Ue)),p.size+=S+Ue-L);break;case 0:R&&(L+=e[L]+1),T=this._pmtId=py(e,L);break;case T:{R&&(L+=e[L]+1);let P=yy(e,L,this.typeSupported,i,this.observer,this.logger);d=P.videoPid,d>0&&(a.pid=d,a.segmentCodec=P.segmentVideoCodec),h=P.audioPid,h>0&&(o.pid=h,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),g!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${g}'. Backtracking to sync byte @${_} to parse all TS packets.`),g=null,S=_-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=I;break}}else b++;b>0&&Za(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=m,l.pesData=p;let x={audioTrack:o,videoTrack:a,id3Track:l,textTrack:u};return r&&this.extractRemainingSamples(x),x}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData,u;if(a&&(u=Gi(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,u,!0),i.pesData=null)):i.pesData=a,o&&(u=Gi(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,u);break;case"mp3":this.parseMPEGPES(t,u);break;case"ac3":this.parseAC3PES(t,u);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(u=Gi(l,this.logger))?(this.parseID3PES(r,u),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new ja(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new za:e==="hevc"&&(this.videoParser=new Xa))}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=ot(r.sample.unit,n);else{let f=h-c;r.sample.unit.set(n.subarray(0,c),f),e.samples.push(r.sample),i=r.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!jr(n,a);a++);if(a!==i){let c,h=a<o-1;if(h?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES",Za(this.observer,new Error(c),h,this.logger),!h)return}Ac(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let c=xc(e.samplerate);l=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let u=0,d;for(;a<o;)if(d=Rc(e,n,a,l,u),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(u++;a<o-1&&!jr(n,a);a++);}parseMPEGPES(e,t){let i=t.data,r=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(Pc(i,a)){let l=Dc(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=Oc(e,i,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=Ee({},t,{type:this._videoTrack?tt.emsg:tt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}};function Ja(s,e){return((s[e+1]&31)<<8)+s[e+2]}function py(s,e){return(s[e+10]&31)<<8|s[e+11]}function yy(s,e,t,i,r,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],l=e+3+o-4,u=(s[e+10]&15)<<8|s[e+11];for(e+=12+u;e<l;){let d=Ja(s,e),c=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){ca("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=d);break;case 21:a.id3Pid===-1&&(a.id3Pid=d);break;case 219:if(!i){ca("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="mp3");break;case 193:if(!i){ca("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&c>0){let h=e+5,f=c;for(;f>2;){switch(s[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=d,a.segmentAudioCodec="ac3");break}let p=s[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return Za(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=d,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=c+5}return a}function Za(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(y.ERROR,y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ca(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Gi(s,e){let t=0,i,r,n,a,o,l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=ot(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>s.size-6)return null;let d=i[7];d&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,d&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let c=n+9;if(s.size<=c)return null;s.size-=c;let h=new Uint8Array(s.size);for(let f=0,m=l.length;f<m;f++){i=l[f];let p=i.byteLength;if(c)if(c>p){c-=p;continue}else i=i.subarray(c),p-=c,c=0;h.set(i,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var eo=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Kt=Math.pow(2,32)-1,Me=class s{static init(){s.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in s.types)s.types.hasOwnProperty(e)&&(s.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);s.HDLR_TYPES={video:t,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);s.STTS=s.STSC=s.STCO=n,s.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),s.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),s.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),s.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);s.FTYP=s.box(s.types.ftyp,a,l,a,o),s.DINF=s.box(s.types.dinf,s.box(s.types.dref,r))}static box(e,...t){let i=8,r=t.length,n=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return s.box(s.types.hdlr,s.HDLR_TYPES[e])}static mdat(e){return s.box(s.types.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(Kt+1)),r=Math.floor(t%(Kt+1));return s.box(s.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(s.types.mdia,s.mdhd(e.timescale||0,e.duration||0),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(s.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"?s.box(s.types.minf,s.box(s.types.smhd,s.SMHD),s.DINF,s.stbl(e)):s.box(s.types.minf,s.box(s.types.vmhd,s.VMHD),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(s.types.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[s.types.moov,s.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[s.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Kt+1)),r=Math.floor(t%(Kt+1)),n=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,r>>24,r>>16&255,r>>8&255,r&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 s.box(s.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return s.box(s.types.sdtp,i)}static stbl(e){return s.box(s.types.stbl,s.stsd(e),s.box(s.types.stts,s.STTS),s.box(s.types.stsc,s.STSC),s.box(s.types.stsz,s.STSZ),s.box(s.types.stco,s.STCO))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=s.box(s.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,u=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return s.box(s.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,u>>8&255,u&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,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(s.types.mp4a,s.audioStsd(e),s.box(s.types.esds,s.esds(e)))}static mp3(e){return s.box(s.types[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(s.types["ac-3"],s.audioStsd(e),s.box(s.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return s.box(s.types.stsd,s.STSD,s.mp4a(e));if(t==="ac3"&&e.config)return s.box(s.types.stsd,s.STSD,s.ac3(e));if(t==="mp3"&&e.codec==="mp3")return s.box(s.types.stsd,s.STSD,s.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return s.box(s.types.stsd,s.STSD,s.avc1(e));if(t==="hevc"&&e.vps)return s.box(s.types.stsd,s.STSD,s.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(Kt+1)),o=Math.floor(i%(Kt+1));return s.box(s.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,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(Kt+1)),a=Math.floor(t%(Kt+1));return s.box(s.types.traf,s.box(s.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(s.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(s.types.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(s.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){let i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n),o,l,u,d,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],u=l.duration,d=l.size,c=l.flags,h=l.cts,a.set([u>>>24&255,u>>>16&255,u>>>8&255,u&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return s.box(s.types.trun,a)}static initSegment(e){s.types||s.init();let t=s.moov(e);return ot(s.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let m=0;m<i.length;m+=1){a+=3;for(let p=0;p<i[m].length;p+=1)a+=2+i[m][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let m=0;m<i.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,i[m].length]),a),a+=3;for(let p=0;p<i[m].length;p+=1)o.set(new Uint8Array([i[m][p].length>>8,i[m][p].length&255]),a),a+=2,o.set(i[m][p],a),a+=i[m][p].length}let u=s.box(s.types.hvcC,o),d=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return s.box(s.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&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]),u,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Me.types=void 0;Me.HDLR_TYPES=void 0;Me.STTS=void 0;Me.STSC=void 0;Me.STCO=void 0;Me.STSZ=void 0;Me.VMHD=void 0;Me.SMHD=void 0;Me.STSD=void 0;Me.FTYP=void 0;Me.DINF=void 0;var Mc=9e4;function il(s,e,t=1,i=!1){let r=s*e*t;return i?Math.round(r):r}function vy(s,e,t=1,i=!1){return il(s,e,1/t,i)}function Ts(s,e=!1){return il(s,1e3,1/Mc,e)}function Ey(s,e=1){return il(s,Mc,1/e)}function yd(s){let{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}var Ty=10*1e3,_y=1024,Sy=1152,by=1536,Ki=null,ha=null;function vd(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}var ji=class extends Je{constructor(e,t,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Ki===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ki=a?parseInt(a[1]):0}if(ha===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);ha=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&yd(t)} > ${e&&yd(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=et(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,n,a,o,l){let u,d,c,h,f,m,p=n,g=n,v=e.pid>-1,T=t.pid>-1,E=t.samples.length,_=e.samples.length>0,b=o&&E>0||E>1;if((!v||_)&&(!T||b)||this.ISGenerated||o){if(this.ISGenerated){var S,R,I,A;let N=this.videoTrackConfig;(N&&(t.width!==N.width||t.height!==N.height||((S=t.pixelRatio)==null?void 0:S[0])!==((R=N.pixelRatio)==null?void 0:R[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((A=N.pixelRatio)==null?void 0:A[1]))||!N&&b||this.nextAudioTs===null&&_)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));let L=this.isVideoContiguous,P=-1,O;if(b&&(P=Ay(t.samples),!L&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){this.warn(`Dropped ${P} out of ${E} video samples due to a missing keyframe`);let N=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,g+=(t.samples[0].pts-N)/t.inputTimeScale,O=g}else P===-1&&(this.warn(`No keyframe found out of ${E} video samples`),m=!1);if(this.ISGenerated){if(_&&b){let N=this.getVideoStartPts(t.samples),M=(et(e.samples[0].pts,N)-N)/t.inputTimeScale;p+=Math.max(0,M),g+=Math.max(0,-M)}if(_){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,p,this.isAudioContiguous,a,T||b||l===W.AUDIO?g:void 0),b){let N=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,g,L,N)}}else b&&(u=this.remuxVideo(t,g,L,0));u&&(u.firstKeyFrame=P,u.independent=P!==-1,u.firstKeyFramePTS=O)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Nc(i,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Fc(r,n,this._initPTS))),{audio:d,video:u,initSegment:c,independent:m,text:h,id3:f}}computeInitPts(e,t,i,r){let n=Math.round(i*t),a=et(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,i,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},u=this._initPTS,d=!u||r,c="audio/mp4",h,f,m,p=-1;if(d&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Me.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(p=e.id,m=e.inputTimeScale,!u||m!==u.timescale?h=f=this.computeInitPts(n[0].pts,m,i,"audio"):d=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Me.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(p=t.id,m=t.inputTimeScale,!u||m!==u.timescale){let g=this.getVideoStartPts(a),v=et(a[0].dts,g),T=this.computeInitPts(v,m,i,"video"),E=this.computeInitPts(g,m,i,"video");f=Math.min(f,T),h=Math.min(h,E)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d?(u&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/m} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,i,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,u=this._initPTS,d=u.baseTime*n/u.timescale,c=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,T=!1;if(!i||c===null){let $=d+t*n,U=a[0].pts-et(a[0].dts,a[0].pts);Ki&&c!==null&&Math.abs($-U-(c+d))<15e3?i=!0:c=$-U-d}let E=c+d;for(let $=0;$<l;$++){let U=a[$];U.pts=et(U.pts,E),U.dts=et(U.dts,E),U.dts<a[$>0?$-1:$].dts&&(T=!0)}T&&a.sort(function($,U){let ee=$.dts-U.dts,he=$.pts-U.pts;return ee||he}),m=a[0].dts,p=a[a.length-1].dts;let _=p-m,b=_?Math.round(_/(l-1)):f||e.inputTimeScale/30;if(i){let $=m-E,U=$>b,ee=$<-1;if((U||ee)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ts($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ts(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||E>=a[0].pts||Ki)){m=E;let he=a[0].pts-$;if(U)a[0].dts=m,a[0].pts=he;else{let te=!0;for(let oe=0;oe<a.length&&!(a[oe].dts>he&&te);oe++){let Ve=a[oe].pts;if(a[oe].dts-=$,a[oe].pts-=$,oe<a.length-1){let $e=a[oe+1].pts,rt=a[oe].pts,Et=$e<=rt,ui=$e<=Ve;te=Et==ui}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ts(he,!0)}/${Ts(m,!0)}, delta: ${Ts($,!0)} ms`)}}m=Math.max(0,m);let x=0,S=0,R=m;for(let $=0;$<l;$++){let U=a[$],ee=U.units,he=ee.length,te=0;for(let oe=0;oe<he;oe++)te+=ee[oe].data.length;S+=te,x+=he,U.length=te,U.dts<R?(U.dts=R,R+=b/4|0||1):R=U.dts,g=Math.min(U.pts,g),v=Math.max(U.pts,v)}p=a[l-1].dts;let I=S+4*x+8,A;try{A=new Uint8Array(I)}catch($){this.observer.emit(y.ERROR,y.ERROR,{type:z.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:$,bytes:I,reason:`fail allocating video mdat ${I}`});return}let L=new DataView(A.buffer);L.setUint32(0,I),A.set(Me.types.mdat,4);let P=!1,O=Number.POSITIVE_INFINITY,N=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let $=0;$<l;$++){let U=a[$],ee=U.units,he=0;for(let Ve=0,$e=ee.length;Ve<$e;Ve++){let rt=ee[Ve],Et=rt.data,ui=rt.data.byteLength;L.setUint32(h,ui),h+=4,A.set(Et,h),h+=ui,he+=4+ui}let te;if($<l-1)f=a[$+1].dts-U.dts,te=a[$+1].pts-U.pts;else{let Ve=this.config,$e=$>0?U.dts-a[$-1].dts:b;if(te=$>0?U.pts-a[$-1].pts:b,Ve.stretchShortVideoTrack&&this.nextAudioTs!==null){let rt=Math.floor(Ve.maxBufferHole*n),Et=(r?g+r*n:this.nextAudioTs+d)-U.pts;Et>rt?(f=Et-$e,f<0?f=$e:P=!0,this.log(`It is approximately ${Et/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=$e}else f=$e}let oe=Math.round(U.pts-U.dts);O=Math.min(O,f),F=Math.max(F,f),N=Math.min(N,te),M=Math.max(M,te),o.push(vd(U.key,f,he,oe))}if(o.length){if(Ki){if(Ki<70){let $=o[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(ha&&M-N<F-O&&b/F<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let $=m;for(let U=0,ee=o.length;U<ee;U++){let he=$+o[U].duration,te=$+o[U].cts;if(U<ee-1){let oe=he+o[U+1].cts;o[U].duration=oe-te}else o[U].duration=U?o[U-1].duration:b;o[U].cts=0,$=he}}}f=P||!f?b:f;let G=p+f;this.nextVideoTs=c=G-d,this.videoSampleDuration=f,this.isVideoContiguous=!0;let Q={data1:Me.moof(e.sequenceNumber++,m,Ee(e,{samples:o})),data2:A,startPTS:(g-d)/n,endPTS:(v+f-d)/n,startDTS:(m-d)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Q}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Sy;case"ac3":return by;default:return _y}}remuxAudio(e,t,i,r,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,u=this.getSamplesPerFrame(e),d=u*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,g=h?0:8,v=this.nextAudioTs||-1,T=c.baseTime*a/c.timescale,E=T+t*a;if(this.isAudioContiguous=i=i||p.length&&v>0&&(r&&Math.abs(E-(v+T))<9e3||Math.abs(et(p[0].pts,E)-(v+T))<20*d),p.forEach(function(M){M.pts=et(M.pts,E)}),!i||v<0){let M=p.length;if(p=p.filter(G=>G.pts>=0),M!==p.length&&this.warn(`Removed ${p.length-M} of ${M} samples (initPTS ${T} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,E-T):v=p[0].pts-T}if(e.segmentCodec==="aac"){let M=this.config.maxAudioFramesDrift;for(let G=0,K=v+T;G<p.length;G++){let Y=p[G],Q=Y.pts,$=Q-K,U=Math.abs(1e3*$/a);if($<=-M*d&&m)G===0&&(this.warn(`Audio frame @ ${(Q/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*$/a)} ms.`),this.nextAudioTs=v=Q-T,K=Q);else if($>=M*d&&U<Ty&&m){let ee=Math.round($/d);for(K=Q-ee*d;K<0&&ee&&d;)ee--,K+=d;G===0&&(this.nextAudioTs=v=K-T),this.warn(`Injecting ${ee} audio frames @ ${((K-T)/a).toFixed(3)}s due to ${Math.round(1e3*$/a)} ms gap.`);for(let he=0;he<ee;he++){let te=eo.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);te||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),te=Y.unit.subarray()),p.splice(G,0,{unit:te,pts:K}),K+=d,G++}}Y.pts=K,K+=d}}let _=null,b=null,x,S=0,R=p.length;for(;R--;)S+=p[R].unit.byteLength;for(let M=0,G=p.length;M<G;M++){let K=p[M],Y=K.unit,Q=K.pts;if(b!==null){let U=f[M-1];U.duration=Math.round((Q-b)/l)}else if(i&&e.segmentCodec==="aac"&&(Q=v+T),_=Q,S>0){S+=g;try{x=new Uint8Array(S)}catch(U){this.observer.emit(y.ERROR,y.ERROR,{type:z.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:S,reason:`fail allocating audio mdat ${S}`});return}h||(new DataView(x.buffer).setUint32(0,S),x.set(Me.types.mdat,4))}else return;x.set(Y,g);let $=Y.byteLength;g+=$,f.push(vd(!0,u,$,0)),b=Q}let I=f.length;if(!I)return;let A=f[f.length-1];v=b-T,this.nextAudioTs=v+l*A.duration;let L=h?new Uint8Array(0):Me.moof(e.sequenceNumber++,_/l,Ee({},e,{samples:f}));e.samples=[];let P=(_-T)/a,O=this.nextAudioTs/a,F={data1:L,data2:x,startPTS:P,endPTS:O,startDTS:P,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,F}};function et(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function Ay(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function Nc(s,e,t,i){let r=s.samples.length;if(!r)return;let n=s.inputTimeScale;for(let o=0;o<r;o++){let l=s.samples[o];l.pts=et(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=et(l.dts-i.baseTime*n/i.timescale,e*n)/n}let a=s.samples;return s.samples=[],{samples:a}}function Fc(s,e,t){let i=s.samples.length;if(!i)return;let r=s.inputTimeScale;for(let a=0;a<i;a++){let o=s.samples[a];o.pts=et(o.pts-t.baseTime*r/t.timescale,e*r)/r}s.samples.sort((a,o)=>a.pts-o.pts);let n=s.samples;return s.samples=[],{samples:n}}var to=class extends Je{constructor(e,t,i,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=Yd(e);if(t)Lp(e,t);else{let l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}n&&(i=Ed(n,_e.AUDIO,this)),a&&(r=Ed(a,_e.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,i,r,n,a){var o,l;let{initPTS:u,lastEndTime:d}=this,c={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};V(d)||(d=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return c;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let p=kp(h,m,this),g=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,T=Er(v,1/0),E=Er(g,1/0),_=Er(v,0,!0),b=Er(g,0,!0),x=n,S=0,R=g&&(!v||!u&&E<T||u&&u.trackId===m.audio.id),I=R?g:v;if(I){let K=I.timescale,Y=I.start-n*K,Q=R?m.audio.id:m.video.id;x=I.start/K,S=R?b-E:_-T,(a||!u)&&(xy(u,x,n,S)||K!==u.timescale)&&(u&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${Y/K} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${x-n} (${Y}/${K}) trackId: ${Q}`),u=null,f.initPTS=Y,f.timescale=K,f.trackId=Q)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);u?(f.initPTS=u.baseTime,f.timescale=u.timescale,f.trackId=u.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=u={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let A=x-u.baseTime/u.timescale,L=A+S;S>0?this.lastEndTime=L:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let P=!!m.audio,O=!!m.video,N="";P&&(N+="audio"),O&&(N+="video");let F=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),M={data1:h,startPTS:A,startDTS:A,endPTS:L,endDTS:L,type:N,hasAudio:P,hasVideo:O,nb:1,dropped:0,encrypted:F};c.audio=P&&!O?M:void 0,c.video=O?M:void 0;let G=v==null?void 0:v.sampleCount;if(G){let K=v.keyFrameIndex,Y=K!==-1;M.nb=G,M.dropped=K===0||this.isVideoContiguous?0:Y?K:G,M.independent=Y,M.firstKeyFrame=K,Y&&v.keyFrameStart&&(M.firstKeyFramePTS=(v.keyFrameStart-u.baseTime)/u.timescale),this.isVideoContiguous||(c.independent=Y),this.isVideoContiguous||(this.isVideoContiguous=Y),M.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${K}/${G} dropped: ${M.dropped} start: ${M.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=Nc(i,n,u,u),r.samples.length&&(c.text=Fc(r,n,u)),c}};function Er(s,e,t=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function xy(s,e,t,i){if(s===null)return!0;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function Ed(s,e,t){let i=s.codec;return i&&i.length>4?i:e===_e.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Nr(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var wt;try{wt=self.performance.now.bind(self.performance)}catch{wt=Date.now}var kr=[{demux:Ya,remux:to},{demux:Qa,remux:ji},{demux:Ha,remux:ji},{demux:Wa,remux:ji}];kr.splice(2,0,{demux:qa,remux:ji});var Xr=class{constructor(e,t,i,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){let n=i.transmuxing;n.executeStart=wt();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:u,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:T,initSegmentData:E}=l,_=Ry(a,t);if(_&&Yi(_.method)){let R=this.getDecrypter(),I=zo(_.method);if(R.isSync()){let A=R.softwareDecrypt(a,_.key.buffer,_.iv.buffer,I);if(i.part>-1){let P=R.flush();A=P&&P.buffer}if(!A)return n.executeEnd=wt(),fa(i);a=new Uint8Array(A)}else return this.asyncResult=!0,this.decryptionPromise=R.webCryptoDecrypt(a,_.key.buffer,_.iv.buffer,I).then(A=>{let L=this.push(A,null,i);return this.decryptionPromise=null,L}),this.decryptionPromise}let b=this.needsProbing(d,c);if(b){let R=this.configureTransmuxer(a);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),n.executeEnd=wt(),fa(i)}(d||c||m||b)&&this.resetInitSegment(E,p,g,T,t),(d||m||b)&&this.resetInitialTimestamp(v),u||this.resetContiguity();let x=this.transmux(a,_,f,h,i);this.asyncResult=Ms(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=wt(),x}flush(e){let t=e.transmuxing;t.executeStart=wt();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(i){let c=i.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:u}=this;if(!l||!u){t.executeEnd=wt();let c=[fa(e)];return this.asyncResult?Promise.resolve(c):c}let d=l.flush(o);return Ms(d)?(this.asyncResult=!0,d.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,d,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:u}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===W.MAIN?"level":"track"} ${i.level}`);let d=this.remuxer.remux(r,n,a,o,u,l,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=wt()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r}=this,n;for(let c=0,h=kr.length;c<h;c++){var a;if((a=kr[c].demux)!=null&&a.probe(e,this.logger)){n=kr[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,u=n.remux,d=n.demux;(!l||!(l instanceof u))&&(this.remuxer=new u(i,t,r,this.logger)),(!o||!(o instanceof d))&&(this.demuxer=new d(i,t,r,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ds(this.config)),e}};function Ry(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var fa=s=>({remuxResult:{},chunkMeta:s});function Ms(s){return"then"in s&&s.then instanceof Function}var io=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null}},so=class{constructor(e,t,i,r,n,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=r,this.timeOffset=n,this.initSegmentChange=a}},Td=0,Qr=class{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Td++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let u=l.data,d=this.hls;if(!(!d||!(u!=null&&u.event)||u.instanceNo!==this.instanceNo))switch(u.event){case"init":{var c;let h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(u.data);break}case"flush":{this.onFlush(u.data);break}case"workerLog":{d.logger[u.data.logType]&&d.logger[u.data.logType](u.data.message);break}default:{u.data=u.data||{},u.data.frag=this.frag,u.data.part=this.part,u.data.id=this.id,d.trigger(u.event,u.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let u=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(l,u)=>{u=u||{},u.frag=this.frag||void 0,l===y.ERROR&&(u=u,u.parent=this.id,u.part=this.part,this.error=u.error),this.hls.trigger(l,u)};this.observer=new Qo,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=Fu(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||G0()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=V0(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=K0());let{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Se(n)})}catch(d){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new Xr(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Xr(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Td++;let t=this.hls.config,i=Fu(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Se(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),H0(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,n,a,o,l,u,d){var c,h;u.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,T=!(v&&n.cc===v.cc),E=!(v&&u.level===v.level),_=v?u.sn-v.sn:-1,b=this.part?u.part-this.part.index:-1,x=_===0&&u.id>1&&u.id===(v==null?void 0:v.stats.chunkCount),S=!E&&(_===1||_===0&&(b===1||x&&b<=0)),R=self.performance.now();(E||_||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(b||!S)&&(a.stats.parsing.start=R);let I=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),A=new so(T,S,l,E,p,I);if(!S||T||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${u.sn}${u.part>-1?" part: "+u.part:""} ${this.id===W.MAIN?"level":"track"}: ${u.level} id: ${u.id}
|
|
31
|
+
${t.m3u8}`)}function Nh(s,e,t=!0,i){let r=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,a=r>=0,o=0;if(a&&r<n.length)o=n[r].start,i==null||i.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===s.endSN+1)o=s.fragmentEnd,i==null||i.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=s.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=s.fragmentStart,i==null||i.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Cy(e,o),o}function Cy(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e)}}function Fh(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){let i=s.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n>0&&n<t&&(t=n)}}else t/=2;return Math.round(t)}function Bh(s,e,t){var i;if(!s)return null;let r=s.fragments[e-s.startSN];return r||(r=s.fragmentHint,((i=r)==null?void 0:i.sn)===e)?r:t&&e<s.startSN&&t.sn===e?t:null}function oc(s,e,t){return s?Uh(s.partList,e,t):null}function Uh(s,e,t){if(s)for(let i=s.length;i--;){let r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function $h(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function wy(s,e){return s!==e&&e?lc(s)!==lc(e):!1}function lc(s){return s.replace(/\?[^?]*$/,"")}function qs(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function Oy(s,e){return!!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function uc(s,e){let t=s.start+e;s.setStart(t)}function Gh(s,e){let t=e.fragments;for(let i=0,r=t.length;i<r;i++)uc(t[i],s);e.fragmentHint&&uc(e.fragmentHint,s),e.alignedSliding=!0}function _n(s,e,t){s&&(My(e,s,t),e.alignedSliding||Ny(e,s,t),!e.alignedSliding&&!e.skippedSegments&&Nh(s,e,!1,t))}function My(s,e,t){if(!Oy(e,s))return;let i=Math.min(e.endCC,s.endCC),r=qs(e.fragments,i),n=qs(s.fragments,i);if(!r||!n)return;let a=r.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Gh(a,s)}function Ny(s,e,t){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;let i=s.fragments,r=e.fragments;if(!i.length||!r.length)return;let n,a,o=Math.min(e.endCC,s.endCC);e.startCC<o&&s.startCC<o&&(n=qs(r,o),a=qs(i,o)),(!n||!a)&&(n=r[Math.floor(r.length/2)]||r.filter(h=>!!h)[0],a=qs(i,n.cc)||i[Math.floor(i.length/2)]);let l=n.programDateTime,u=a.programDateTime;if(!l||!u)return;let d=(u-l)/1e3;if(Math.abs(d)>Math.max(60,s.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${s.totalduration})`);return}let c=d-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${c})`),Gh(c,s)}function be(s,e,t){Se(s,e,t),s.addEventListener(e,t)}function Se(s,e,t){s.removeEventListener(e,t)}function Sn(s){let e="",t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}var O={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},rr=class extends vn{constructor(e,t,i,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=O.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:u,state:d}=this,c=l?l.currentTime:0,h=oe.bufferInfo(u||l,c,a.maxBufferHole),f=h.len;if(this.log(`Media seeking to ${c}, state: ${d}, ${f?"in":"out of"} buffer`),this.state===O.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,y=o.start+o.duration+m;if(!f||y<h.start||p>h.end){let T=c<p,v=c>y;(T||v)&&(o.loader&&(v||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){let p=Math.max(h.end,c),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${c} with buffer @${p}`),this.loadingParts=y)}}let g=!oe.isBuffered(l,c);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,g&&(this.startPosition=c)),f<1&&this.state===O.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new mn(e.config),this.initFragmentLoader=new mn(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ir(e.config)}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===O.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=O.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let i=this.getLevelDetails();return i!=null&&i.live?(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=oe.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let d=l[l.length-1];return oe.isBuffered(this.media,d.start+d.duration/2)}let u=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(u.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;be(i,"seeking",this.onMediaSeeking),be(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===O.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let i=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Se(r,"seeking",this.onMediaSeeking),Se(r,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=O.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}let o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} chunk: ${o}`),this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===O.FRAG_LOADING||!this.fragCurrent&&a===O.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=O.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(E.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===O.STOPPED||this.state===O.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===Me.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&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)===Me.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){let r=t.getPartialFragment(i.end);r&&(t.removeFragment(r),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(E.BUFFER_FLUSHING,r)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(i=>{var r;let n=i.frag;if(!this.levels||!co(n,(r=this.fragCurrent)==null?void 0:r.initSegment))throw new _t({type:Q.NETWORK_ERROR,details:k.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return i}).then(i=>{let{frag:r,payload:n}=i,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&hs(a.method)){let o=self.performance.now(),{decryptRange:l}=pn(r,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Vl(a.method),l).catch(u=>{throw t.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:r}),this.fragmentLoader.abort(),u}).then(u=>{let d=self.performance.now();return t.trigger(E.FRAG_DECRYPTED,{frag:r,part:null,payload:u,stats:{tstart:o,tdecrypt:d}}),i.payload=u,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&Ne(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===O.STOPPED||this.state===O.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var i,r;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!co(e,t)}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?Sn(oe.getBuffered(i)):"(detached)"})`),Ne(e)){var r;if(e.type!==j.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=O.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==Me.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=O.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let i=e.frag,{part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(u=>!u),{decryptRange:o}=pn(i,r),l=new sr(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a,i.duration,this.iframesOnly,o);this.log(`load complete ${i.type} sn: ${i.sn}${r?" part: "+r.index:""} of ${this.fragInfo(i,!1,r)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var r;let n=null;return e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=O.KEY_LOADING,n=this.keyLoader.load(e,i).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(E.KEY_LOADED,a),this.state===O.KEY_LOADING&&(this.state=O.IDLE),a}),this.hls.trigger(E.KEY_LOADING,{frag:e})):e.encrypted||(n=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),n&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),n}_doFragLoad(e,t,i=null,r){this.fragCurrent=e;let n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=this.fragPrevious;if(!Gs(e,a)){let f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a==null?void 0:a.sn}->${e.sn}`),this.loadingParts=f)}if(i=Math.max(e.start,i||0),this.loadingParts){let f=n.partList;if(f&&r){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);let g=this.getNextPart(f,e,i);if(g>-1){let m=f[g];if(e=this.fragCurrent=m.fragment,!Gs(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);let p=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${i}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=O.FRAG_LOADING;let y,T=this.loadInitSegmentIfNeeded(e);if(p||T){let v=!!p;y=Promise.all([p,T]).then(([_])=>v&&(!_||this.fragContextChanged(_.frag))?null:this.doFragPartsLoad(e,m,t,r)).catch(_=>this.handleFragLoadError(_))}else y=this.doFragPartsLoad(e,m,t,r).catch(v=>this.handleFragLoadError(v));return this.hls.trigger(E.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(f,i))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(o=n.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),u=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var d;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(d=this.fragCurrent)==null?void 0:d.relurl}`),l==null||l.catch(()=>null),u==null||u.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),H(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=O.FRAG_LOADING;let c=this.config.progressive&&e.type!==j.SUBTITLE,h;return c&&u?h=u.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,r,l)).catch(f=>this.handleFragLoadError(f)):h=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,c?r:void 0,c?l:void 0),u,l]).then(([f])=>(!c&&r&&r(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([h,l]).then(([f])=>f)}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;let l=[],u=(o=i.details)==null?void 0:o.partList,d=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;let f=h.part;this.hls.trigger(E.FRAG_LOADED,h);let g=oc(i.details,e.sn,c.index+1)||Uh(u,e.sn,c.index+1);if(g)d(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===k.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Q.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==O.PARSING){!this.fragCurrent&&this.state!==O.STOPPED&&this.state!==O.ERROR&&(this.state=O.IDLE);return}let{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),u=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=u),this.updateLevelTiming(i,r,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;let r=e.partList[0],n=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=n&&this.playhead>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,u=a>-1?oc(l,n,a):null,d=u?u.fragment:Bh(l,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:u,level:o}):null}bufferFragmentData(e,t,i,r,n){if(this.state!==O.PARSING)return;Ne(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=St(a,o)),!l.length)return;let u=this.initPTS[t.cc],d=u?-u.baseTime/u.timescale:void 0,c={type:e.type,frag:t,part:i,chunkMeta:r,offset:d,parent:t.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!oe.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=oe.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;let r=this.playhead,a=this.lastCurrentTime>r||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,i,r){let n=oe.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return oe.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let r=e.nextStart;if(r&&i.start>r){let n=e.buffered;if(n){let a=e.len,o=e.bufferedIndex;for(let l=n.length-1;l>o;l--)n[l].start<i.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t/2),n=Math.max(e-t*3,i.maxMaxBufferLength/2,r);return n>=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,a=t.fragmentStart,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var u;l=this.getInitialLiveFragment(t);let h=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((u=l)==null?void 0:u.start)||0,p,y;if(f!==-1&&f>=a?(p=f,y=f===h?"config":"next load start"):g?(p=g,y="live edge"):(p=e,y="buffer pos"),p<m&&(p=m,y="live frag start"),p<a&&(p=a,y="playlist start"),this.startPosition!=p||this.nextLoadPosition!=p){let v=t.live&&!this.filterReplacedPrimary(l,t)?-1:p;this.log(`Setting startPosition to ${v} next load ${p} ${f===-1?"":`(from ${h}) `}based on ${y}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=v,this.nextLoadPosition=p}}}else e<=a&&(l=i[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let d=this.filterReplacedPrimary(l,t);return!d&&l&&(d=Ih(t,l.sn),d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return!!(i===Me.OK||i===Me.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,i,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(bn(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(bn(this.config)&&("type"in e?e:e.fragment).type!==j.SUBTITLE){let i=this.hls.interstitialsManager,r=i==null?void 0:i.bufferingItem;if(r){let n=r.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-r.start)>1||r.start===0))return null}else if(e.end<=r.start&&(t==null?void 0:t.live)===!1||e.start>=r.end&&r.nextEvent&&(r.nextEvent.appendInPlace&&!r.nextEvent.hasPlayed||e.start-r.end>1))return null}if(Kh(e,i==null?void 0:i.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let r=-1,n=!1,a=!0;for(let l=0,u=e.length;l<u;l++){let d=e[l];if(a=a&&!d.independent,r>-1&&i<d.start)break;let c=d.loaded||d.gap;c?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(r=l),n=c&&!d.gap}let o=e[r];return o&&o.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--;){if(i=e[r],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(r=ny(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=xh(e,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:u}=r,d=i.partList,c=!!(this.loadingParts&&d!=null&&d.length&&l);c&&!this.bitrateTest&&d[d.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===Me.NOT_LOADED&&(n=null);let h;if(e<t){var f;let m=e<this.lastCurrentTime||e>t-u||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:u;h=ms(n,a,e,m)}else h=a[a.length-1];if(h){let g=h.sn-i.startSN,m=this.fragmentTracker.getState(h);if((m===Me.OK||m===Me.PARTIAL&&h.gap)&&(n=h),Gs(h,n)&&(!c||d[0].fragment.sn>h.sn||!i.live)){let p=a[g+1];h.sn<o&&this.fragmentTracker.getState(p)!==Me.OK?h=p:h=null}}return h}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&H(n);if(a||!o&&!n){_n(i,e,this);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}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;i<t&&(i=-1);let r=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&H(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){let o=this.hls.liveSyncPosition;i=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var e;let{media:t}=this,i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let i=(t=this.media)==null?void 0:t.currentTime;return H(i)?i:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==j.MAIN)return!1;let t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ne(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==O.FRAG_LOADING_WAITING_RETRY)&&(this.state=O.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let T=this.getCurrentContext(t.chunkMeta);T&&(t.frag=T.frag)}let{frag:i,part:r}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}let a=t.details===k.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);let o=t.errorAction;if(!o){this.state=O.ERROR;return}let{action:l,flags:u,retryCount:d=0,retryConfig:c}=o,h=!!c,f=h&&l===Qe.RetryRequest,g=h&&!o.resolved&&u&Xe.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,p=m==null?void 0:m.live;if(!f&&g&&Ne(i)&&p&&i.sn<m.endSN&&!Xc(t))this.resetFragmentErrors(e),r?r.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&d<c.maxNumRetry){var y;let T=Xs((y=t.response)==null?void 0:y.code),v=Nl(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=O.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,T){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${v}ms`)}else if(c)if(this.resetFragmentErrors(e),d<c.maxNumRetry)!a&&l!==Qe.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else l===Qe.SendAlternateToPenaltyBox?this.state=O.WAITING_LEVEL:this.state=O.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!Xs(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=O.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===O.PARSING||this.state===O.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);let a=!n;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,Number.POSITIVE_INFINITY,i===j.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===j.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==O.STOPPED&&(this.state=O.IDLE)}afterBufferFlushed(e,t){if(!e)return;let i=oe.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===O.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==O.STOPPED&&(this.state=O.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){let n=i.details;if(!n){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((c,h)=>{let f=e.elementaryStreams[h];if(f){let g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${h} duration reliably (${g})`),c||!1;let m=r.partial?0:Mh(n,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:n,level:i,drift:m,type:h,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var o,l,u,d;let c=((o=this.transmuxer)==null?void 0:o.error)===null,h=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((u=(d=this.levels)==null?void 0:d.length)!=null?u:0)>1;if((i.fragmentError===0||c&&(i.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,i),c){let g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=O.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var r,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(r=t&&!i?e.startPTS:(i||e).start)!=null?r:NaN}-${(n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;let r=i.loading.first>0,a=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return r&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0,{hls:r,media:n,config:a,levels:o,playlistType:l}=this,u=this.getLevelDetails();if(n&&!n.paused&&o){var d;let f=l===j.AUDIO?_h(e.audioCodec,128e3):e.maxBitrate,g=1+r.ttfbEstimate/1e3,m=r.bandwidthEstimate*a.abrBandWidthUpFactor,p=u&&(this.loadingParts?u.partTarget:u.averagetargetduration)||((d=this.fragCurrent)==null?void 0:d.duration)||6;i=g+f*p/m,e.details||(i+=g)}let c=this.playhead,h=!(u!=null&&u.live)||t.end-c>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:h}}scheduleTrackSwitch(e,t,i){let{media:r,playlistType:n}=this;if(!r||!e)return;let a=i?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let u=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,c=Math.max(a.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>c)return;let f=n===j.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let r=t===j.AUDIO;this.flushMainBuffer(0,i.start-(r?0:1),r?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case O.KEY_LOADING:case O.FRAG_LOADING:case O.FRAG_LOADING_WAITING_RETRY:case O.PARSING:case O.PARSED:this.state=O.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(oe.isBuffered(e,i)?t=this.getAppendedFrag(i):oe.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!Gs(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:i,config:r,playlistType:n}=this;if(t!=null&&t.readyState&&e&&i&&r){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;let l=n===j.AUDIO?i.nextAudioTrack:i.nextLoadLevel,u=e[l],{fetchdelay:d,okToFlushForwardBuffer:c}=this.calculateOptimalSwitchPoint(u,o);this.scheduleTrackSwitch(o,d,c)}this.tickImmediate()}};function Kh(s,e,t){if(e)for(let i=e.length;i--;){let r=e[i].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace&&(s.start>=n&&s.end<=a||t>s.start&&s.end>n&&s.start<a))return!0}return!1}function bn(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}var An=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=Fy(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function Fy(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r<s.length;r++){let n=s[r];t.set(n,i),i+=n.length}return t}var ja={exports:{}},dc;function By(){return dc||(dc=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,u,d){this.fn=l,this.context=u,this.once=d||!1}function n(l,u,d,c,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new r(d,c||l,h),g=t?t+u:u;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,u){--l._eventsCount===0?l._events=new i:delete l._events[u]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],d,c;if(this._eventsCount===0)return u;for(c in d=this._events)e.call(d,c)&&u.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},o.prototype.listeners=function(u){var d=t?t+u:u,c=this._events[d];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,g=new Array(f);h<f;h++)g[h]=c[h].fn;return g},o.prototype.listenerCount=function(u){var d=t?t+u:u,c=this._events[d];return c?c.fn?1:c.length:0},o.prototype.emit=function(u,d,c,h,f,g){var m=t?t+u:u;if(!this._events[m])return!1;var p=this._events[m],y=arguments.length,T,v;if(p.fn){switch(p.once&&this.removeListener(u,p.fn,void 0,!0),y){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,d),!0;case 3:return p.fn.call(p.context,d,c),!0;case 4:return p.fn.call(p.context,d,c,h),!0;case 5:return p.fn.call(p.context,d,c,h,f),!0;case 6:return p.fn.call(p.context,d,c,h,f,g),!0}for(v=1,T=new Array(y-1);v<y;v++)T[v-1]=arguments[v];p.fn.apply(p.context,T)}else{var _=p.length,S;for(v=0;v<_;v++)switch(p[v].once&&this.removeListener(u,p[v].fn,void 0,!0),y){case 1:p[v].fn.call(p[v].context);break;case 2:p[v].fn.call(p[v].context,d);break;case 3:p[v].fn.call(p[v].context,d,c);break;case 4:p[v].fn.call(p[v].context,d,c,h);break;default:if(!T)for(S=1,T=new Array(y-1);S<y;S++)T[S-1]=arguments[S];p[v].fn.apply(p[v].context,T)}}return!0},o.prototype.on=function(u,d,c){return n(this,u,d,c,!1)},o.prototype.once=function(u,d,c){return n(this,u,d,c,!0)},o.prototype.removeListener=function(u,d,c,h){var f=t?t+u:u;if(!this._events[f])return this;if(!d)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!h||g.once)&&(!c||g.context===c)&&a(this,f);else{for(var m=0,p=[],y=g.length;m<y;m++)(g[m].fn!==d||h&&!g[m].once||c&&g[m].context!==c)&&p.push(g[m]);p.length?this._events[f]=p.length===1?p[0]:p:a(this,f)}return this},o.prototype.removeAllListeners=function(u){var d;return u?(d=t?t+u:u,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o}(ja)),ja.exports}var Uy=By(),ql=B0(Uy),nr="1.7.3",ps={};function $y(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Gy(){let s=ps[nr];if(s)return s.clientCount++,s;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return ps[nr]=r,r}function Ky(s){let e=ps[s];if(e)return e.clientCount++,e;let t=new self.URL(s,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return ps[s]=r,r}function Vy(s){let e=ps[s||nr];if(e&&e.clientCount--===1){let{worker:i,objectURL:r}=e;delete ps[s||nr],r&&self.URL.revokeObjectURL(r),i.terminate()}}function Hy(s,e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let p=new Error(`invalid ADTS sampling index:${a}`);s.emit(E.ERROR,E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,u=r[a],d=a;(o===5||o===29)&&(d-=3);let c,h=(d&14)>>1,f=(d&1)<<7|l<<3,g=0;if(o===1&&a>=6){g=5;let p=a-3;c=[g<<3|h,f|(p&14)>>1,(p&1)<<7|8,0]}else c=[o<<3|h,f];let m="mp4a.40."+(g||o);return Te.log(`manifest codec:${i}, parsed codec:${m}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:u,channelCount:l,codec:m,parsedCodec:m,manifestCodec:i}}function Vh(s,e){return s[e]===255&&(s[e+1]&246)===240}function Hh(s,e){return s[e+1]&1?7:9}function Wl(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function qy(s,e){return e+5<s.length}function Rn(s,e){return e+1<s.length&&Vh(s,e)}function Wy(s,e){return qy(s,e)&&Vh(s,e)&&Wl(s,e)<=s.length-e}function Yy(s,e){if(Rn(s,e)){let t=Hh(s,e);if(e+t>=s.length)return!1;let i=Wl(s,e);if(i<=t)return!1;let r=e+i;return r===s.length||Rn(s,r)}return!1}function qh(s,e,t,i,r){if(!s.samplerate){let n=Hy(e,t,i,r);if(!n)return;Re(s,n)}}function Wh(s){return 1024*9e4/s}function jy(s,e){let t=Hh(s,e);if(e+t<=s.length){let i=Wl(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Yh(s,e,t,i,r){let n=Wh(s.samplerate),a=i+r*n,o=jy(e,t),l;if(o){let{frameLength:c,headerLength:h}=o,f=h+c,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let m={unit:l,pts:a};return g||s.samples.push(m),{sample:m,length:f,missing:g}}let u=e.length-t;return l=new Uint8Array(u),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:u,missing:-1}}var nt=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function Vt(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var ar=class{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,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=St(this.cachedData,e),this.cachedData=null);let i=Qs(e,0),r=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?Bl(i):void 0,u=e.length;for((this.basePTS===null||this.frameIndex===0&&H(l))&&(this.basePTS=zy(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:nt.audioId3,duration:Number.POSITIVE_INFINITY});r<u;){if(this.canParse(e,r)){let d=this.appendFrame(a,e,r);d?(this.frameIndex++,this.lastPTS=d.sample.pts,r+=d.length,n=r):r=u}else tv(e,r)?(i=Qs(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:nt.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===u&&n!==u){let d=e.slice(n);this.cachedData?this.cachedData=St(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:Vt(),id3Track:o,textTrack:Vt()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Vt(),id3Track:this._id3Track,textTrack:Vt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},zy=(s,e,t)=>{if(H(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},Xy=[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],Qy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Jy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Zy=[0,1,1,4];function jh(s,e,t,i,r){if(t+24>e.length)return;let n=zh(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function zh(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,u=Xy[l*14+r-1]*1e3,c=Qy[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Jy[t][i],g=Zy[i],m=f*8*g,p=Math.floor(f*u/c+a)*g,y=Vs();return!!y&&y<=87&&i===2&&u>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:c,channelCount:h,frameLength:p,samplesPerFrame:m}}}function Yl(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Xh(s,e){return e+1<s.length&&Yl(s,e)}function eE(s,e){return Yl(s,e)&&4<=s.length-e}function Qh(s,e){if(e+1<s.length&&Yl(s,e)){let i=zh(s,e),r=4;i!=null&&i.frameLength&&(r=i.frameLength);let n=e+r;return n===s.length||Xh(s,n)}return!1}var xn=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ir(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,vi.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(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){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){let a=gh(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}).catch(r)}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}},ko=class extends ar{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=Qs(e,0),r=(i==null?void 0:i.length)||0;if(Qh(e,r))return!1;for(let n=e.length;r<n;r++)if(Yy(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Wy(e,t)}appendFrame(e,t,i){qh(e,this.observer,t,i,e.manifestCodec);let r=Yh(e,t,i,this.basePTS,this.frameIndex);if((r==null?void 0:r.missing)===0)return r}demuxSampleAes(e,t,i){let r=this.demux(e,i),n=this.sampleAes=new xn(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(r.audioTrack.samples,0,()=>{a(r)})})}},Jh=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o}return t},Po=class extends ar{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=Zh(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Qs(e,0);if(!t)return!1;let i=t.length;if(e[i]===11&&e[i+1]===119&&Bl(t)!==void 0){if(Jh(e,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function Zh(s,e,t,i,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,d=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+d>e.length)return-1;let c=e[t+6]>>5,h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,m=[2,1,2,3,3,4,4,5][c]+f,p=e[t+5]>>3,y=e[t+5]&7,T=new Uint8Array([n<<6|p<<1|y>>2,(y&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),v=1536/o*9e4,_=i+r*v,S=e.subarray(t,t+d);return s.config=T,s.channelCount=m,s.samplerate=o,s.samples.push({unit:S,pts:_}),d}var Co=class extends ar{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Qs(e,0),i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Bl(t)!==void 0&&Jh(e,i)<=16)return!1;for(let r=e.length;i<r;i++)if(Qh(e,i))return Te.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return eE(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return jh(e,t,i,this.basePTS,this.frameIndex)}},tE=/\/emsg[-/]ID3/i,wo=class{constructor(e,t,i,r=Te){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=r}resetTimeStamp(){}resetInitSegment(e,t,i,r){let n=this.videoTrack=Vt("video",1),a=this.audioTrack=Vt("audio",1),o=this.txtTrack=Vt("text",1);if(this.id3Track=Vt("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=uh(e);if(l.video){let{id:u,timescale:d,codec:c,supplemental:h}=l.video;n.id=u,n.timescale=o.timescale=d,n.codec=c,n.supplemental=h}if(l.audio){let{id:u,timescale:d,codec:c}=l.audio;a.id=u,a.timescale=d,a.codec=c}o.id=nh.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return pv(e,"moof")}demux(e,t,i){this.timeOffset=t;let r=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=St(this.remainderData,e));let u=xv(r);this.remainderData=u.remainder,n.samples=u.valid||new Uint8Array}else n.samples=r;let o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let i=this.timeOffset,r=this.videoTrack,n=this.txtTrack;r.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(r,this.timeOffset),o=this.parseFragment(r,n,i,t);return{videoTrack:r,audioTrack:Vt(),id3Track:a,textTrack:Vt(),initData:this.initData,sampleData:o}}parseFragment(e,t,i,r){let n=this.initData;if(n&&r){let{samples:a,sampleData:o}=Rv(i,e,n,this.logger,r.iframe);return t.samples=a,o}t.samples=Iv(i,e)}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=ne(e.samples,["emsg"]);r&&r.forEach(n=>{let a=Lv(n);if(tE.test(a.schemeIdUri)){let o=cc(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let u=a.payload;i.samples.push({data:u,len:u.byteLength,dts:o,pts:o,type:nt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||nt.misbklv;if(a.schemeIdUri.startsWith(o)){let l=cc(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:nt.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function cc(s,e){return H(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}var iE=1,sE=2,Bs=-1,In=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let r=t.byteLength;if(r===0)return[];let n=e.naluState||0,a=n===Bs?0:n,o=[],l=0,u=0,d=-1,c=0;for(n===Bs&&(d=0,c=this.getNALuType(t,0),u=1);u<r;){let h=t.indexOf(iE,u);if(h===-1)break;u=h+1;let f=h;for(;f>0&&t[f-1]===0;)f--;if(!(h-f+(f===0?a:0)<sE)){if(d>=0)o.push({data:t.subarray(d,f),type:c});else{let m=this.getLastNalUnit(e.samples);m&&(f>0?m.data=St(m.data,t.subarray(0,f)):a>0&&(m.data=m.data.subarray(0,m.data.byteLength-a)),m.state=0)}if(u<r)d=u,c=this.getNALuType(t,u);else{l=Bs,d=-1;break}}}if(l!==Bs){let h=r;for(;h>0&&t[h-1]===0;)h--;l=r-h+(h===0?a:0)}if(d>=0)o.push({data:t.subarray(d),type:c,state:l});else if(o.length===0&&l!==Bs){let h=this.getLastNalUnit(e.samples);h&&(h.data=St(h.data,t),h.state=l)}return e.naluState=l,o}},Hi=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(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),i=this.word>>>32-t;if(e>32&&Te.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<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)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(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}},Oo=class extends In{parsePES(e,t,i,r,n){let a=n.iframe,o=this.parseNALu(e,i.data,r),l=this.VideoSample,u,d=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach(c=>{var h,f;switch(c.type){case 1:{if(a)break;let y=!1;u=!0;let T=c.data;if(d&&T.length>4){let v=this.readSliceType(T);(v===2||v===4||v===7||v===9)&&(y=!0)}if(y){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=y;break}case 5:u=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;u=!0,Js(c.data,1,i.pts,t.samples);break}case 7:{var m,p;u=!0,d=!0;let y=c.data,T=this.readSPS(y);if(!e.sps||e.width!==T.width||e.height!==T.height||((m=e.pixelRatio)==null?void 0:m[0])!==T.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[y];let v=y.subarray(1,4),_="avc1.";for(let S=0;S<3;S++){let A=v[S].toString(16);A.length<2&&(A="0"+A),_+=A}e.codec=_}break}case 8:u=!0,e.pps=[c.data];break;case 9:u=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}l&&u&&l.units.push(c)}),r&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Hi(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(i+n+256)%256),i=r===0?i:r}readSPS(e){let t=new Hi(e),i=0,r=0,n=0,a=0,o,l,u,d=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),p=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);d();let T=d();if(c(5),g(3),d(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let x=h();if(x===3&&g(1),p(),p(),g(1),f())for(l=x!==3?8:12,u=0;u<l;u++)f()&&(u<6?y(16,t):y(64,t))}p();let v=h();if(v===0)h();else if(v===1)for(g(1),m(),m(),o=h(),u=0;u<o;u++)m();p(),g(1);let _=h(),S=h(),A=c(1);A===0&&g(1),g(1),f()&&(i=h(),r=h(),n=h(),a=h());let b=[1,1];if(f()&&f())switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:{b=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((_+1)*16-i*2-r*2),height:(2-A)*(S+1)*16-(A?2:4)*(n+a),pixelRatio:b}}},Mo=class extends In{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=!1;i.data=null;let u=d=>(a=this.VideoSample=this.createVideoSample(d,i.pts,i.dts),a);n.forEach((d,c)=>{var h,f;if(this.startsNewAccessUnit(a,e,d,c)){this.pushAccessUnit(a,e);let m=d.type>=16&&d.type<=23;a=u(m),l=!1}switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=u(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=u(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=u(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,Js(d.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Re(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let m=this.readSPS(d.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let p in m.params)e.params[p]=m.params[p]}this.pushParameterSet(e.sps,d.data,e.vps),a||(a=u(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let m=this.readPPS(d.data);for(let p in m)e.params[p]=m[p]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=u(!1));break;default:o=!1;break}a&&o&&a.units.push(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,i,r){if(!e)return!1;if(!t.audFound&&r===0)return!0;if(!e.frame)return!1;let{type:n,data:a}=i;return n>=32&&n<=35||n===39||n>=41&&n<=44||n>=48&&n<=55?!0:n<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new Hi(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:r}}readSPS(e){let t=new Hi(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),y=t.readUByte(),T=[],v=[];for(let X=0;X<i;X++)T.push(t.readBoolean()),v.push(t.readBoolean());if(i>0)for(let X=i;X<8;X++)t.readBits(2);for(let X=0;X<i;X++)T[X]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[X]&&t.readUByte();t.readUEG();let _=t.readUEG();_==3&&t.skipBits(1);let S=t.readUEG(),A=t.readUEG(),b=t.readBoolean(),x=0,L=0,R=0,I=0;b&&(x+=t.readUEG(),L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());let P=t.readUEG(),w=t.readUEG(),B=t.readUEG(),U=t.readBoolean();for(let X=U?0:i;X<=i;X++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let he=0;he<4;he++)for(let pe=0;pe<(he===3?2:6);pe++)if(!t.readBoolean())t.readUEG();else{let Fe=Math.min(64,1<<4+(he<<1));he>1&&t.readEG();for(let st=0;st<Fe;st++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let F=t.readUEG(),G=0;for(let X=0;X<F;X++){let he=!1;if(X!==0&&(he=t.readBoolean()),he){X===F&&t.readUEG(),t.readBoolean(),t.readUEG();let pe=0;for(let Ke=0;Ke<=G;Ke++){let Fe=t.readBoolean(),st=!1;Fe||(st=t.readBoolean()),(Fe||st)&&pe++}G=pe}else{let pe=t.readUEG(),Ke=t.readUEG();G=pe+Ke;for(let Fe=0;Fe<pe;Fe++)t.readUEG(),t.readBoolean();for(let Fe=0;Fe<Ke;Fe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let X=t.readUEG();for(let he=0;he<X;he++){for(let pe=0;pe<B+4;pe++)t.readBits(1);t.readBits(1)}}let $=0,K=1,se=1,ee=!0,ue=1,ie=0;t.readBoolean(),t.readBoolean();let ge=!1;if(t.readBoolean()){if(t.readBoolean()){let At=t.readUByte(),wi=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Je=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];At>0&&At<16?(K=wi[At-1],se=Je[At-1]):At===255&&(K=t.readBits(16),se=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ge=t.readBoolean(),ge&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ue=t.readBits(32),ie=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Je=t.readBoolean(),rt=t.readBoolean(),Et=!1;(Je||rt)&&(Et=t.readBoolean(),Et&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Et&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ht=0;ht<=i;ht++){ee=t.readBoolean();let tt=ee||t.readBoolean(),oi=!1;tt?t.readEG():oi=t.readBoolean();let jt=oi?1:t.readUEG()+1;if(Je)for(let Rt=0;Rt<jt;Rt++)t.readUEG(),t.readUEG(),Et&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(rt)for(let Rt=0;Rt<jt;Rt++)t.readUEG(),t.readUEG(),Et&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readUEG())}let ve=S,Ge=A;if(b){let X=1,he=1;_===1?X=he=2:_==2&&(X=2),ve=S-X*L-X*x,Ge=A-he*I-he*R}let lt=r?["A","B","C"][r]:"",Yt=o<<24|l<<16|u<<8|d,Pe=0;for(let X=0;X<32;X++)Pe=(Pe|(Yt>>X&1)<<31-X)>>>0;let yt=Pe.toString(16);return a===1&&yt==="2"&&(yt="6"),{codecString:`hvc1.${lt}${a}.${yt}.${n?"H":"L"}${y}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,u,d],general_constraint_indicator_flags:[c,h,f,g,m,p],general_level_idc:y,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:$,chroma_format_idc:_,frame_rate:{fixed:ee,fps:ie/ue}},width:ve,height:Ge,pixelRatio:[K,se]}}readPPS(e){let t=new Hi(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return Ot(e).substring(3)===Ot(t).substring(3)}},qe=188,Ln=class s{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){let i=s.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(qe*5,t-qe)+1,r=0;for(;r<i;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=qe)if(e[l]===71&&(t-l===qe||e[l+qe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+qe*99,e.length-qe)+1)),n||(n=Dn(e,l)===0),n&&o>1&&(a===0&&o>2||l+qe>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:nh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Fo(this.logger):null,this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,(n==null?void 0:n.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,r=!1,n=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,d=this._id3Track,c=this._txtTrack,h=i.iframe,f=o.pid,g=o.pesData,m=u.pid,p=d.pid,y=this._klvPid,T=u.pesData,v=d.pesData,_=null,S=null,A=this.pmtParsed,b=this._pmtId,x=e.length;if(this.remainderData&&(e=St(this.remainderData,e),x=e.length,this.remainderData=null),x<qe&&!n)return this.remainderData=e,{audioTrack:u,videoTrack:o,id3Track:d,textTrack:c};let L=Math.max(0,s.syncOffset(e));x-=(x-L)%qe,x<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let R=0;for(let P=L;P<x;P+=qe)if(e[P]===71){let w=!!(e[P+1]&64),B=Dn(e,P),U=(e[P+3]&48)>>4,C;if(U>1){if(C=P+5+e[P+4],C===P+qe)continue}else C=P+4;switch(B){case f:w&&(g&&!(l!=null&&l.isCorrupted)&&(a=Ui(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,a,!1,i)),g={data:[],size:0},l==null||l.reset(f)),l==null||l.handlePacket(e.subarray(P)),g&&(g.data.push(e.subarray(C,P+qe)),g.size+=P+qe-C);break;case m:if(h)break;if(w){if(T&&(a=Ui(T,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,a,i);break;case"mp3":this.parseMPEGPES(u,a);break;case"ac3":this.parseAC3PES(u,a);break}T={data:[],size:0}}T&&(T.data.push(e.subarray(C,P+qe)),T.size+=P+qe-C);break;case p:if(h)break;w&&(v&&(a=Ui(v,this.logger))&&this.parseID3PES(d,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(C,P+qe)),v.size+=P+qe-C);break;case y:if(h)break;w&&(_&&(a=Ui(_,this.logger))&&this.parseKlvPES(d,a),_={data:[],size:0}),_&&(_.data.push(e.subarray(C,P+qe)),_.size+=P+qe-C);break;case 0:w&&(C+=e[C]+1),b=this._pmtId=rE(e,C);break;case b:{w&&(C+=e[C]+1);let N=nE(e,C,this.typeSupported,r,this.observer,this.logger,this.config,i);f=N.videoPid,f>0&&(o.pid=f,o.segmentCodec=N.segmentVideoCodec),m=N.audioPid,m>0&&(u.pid=m,u.segmentCodec=N.segmentAudioCodec),p=N.id3Pid,p>0&&(d.pid=p),y=N.klvPid,y>0&&(this._klvPid=y),S!==null&&!A&&(this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${S}'. Backtracking to sync byte @${L} to parse all TS packets.`),S=null,P=L-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:S=B;break}}else R++;R>0&&No(this.observer,new Error(`Found ${R} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=g,u.pesData=T,d.pesData=v;let I={audioTrack:u,videoTrack:o,id3Track:d,textTrack:c};return n&&this.extractRemainingSamples(I,i),I}flush(e,t){let{remainderData:i}=this;this.remainderData=null;let r;return i?r=this.demux(i,0,t,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(e,t){let{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,o=r.pesData,l=i.pesData,u=n.pesData,d=this.videoIntegrityChecker,c;if(o&&!(d!=null&&d.isCorrupted)&&(c=Ui(o,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,a,c,!0,t),r.pesData=null)):r.pesData=o,l&&(c=Ui(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,c,t);break;case"mp3":this.parseMPEGPES(i,c);break;case"ac3":this.parseAC3PES(i,c);break}i.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(c=Ui(u,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=u}demuxSampleAes(e,t,i,r){let n=this.demux(e,i,r,!0,!this.config.progressive),a=this.sampleAes=new xn(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Oo:e==="hevc"&&(this.videoParser=new Mo))}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let r=0,n=this.aacOverFlow,a=t.data;if(n){this.aacOverFlow=null;let h=n.missing,f=n.sample.unit.byteLength;if(h===-1)a=St(n.sample.unit,a);else{let g=f-h;n.sample.unit.set(a.subarray(0,h),g),e.samples.push(n.sample),r=n.missing}}let o,l;for(o=r,l=a.length;o<l-1&&!Rn(a,o);o++);if(o!==r){let h,f=o<l-1;if(f?h=`AAC PES did not start with ADTS header,offset:${o}`:h="No ADTS header found in AAC PES",No(this.observer,new Error(h),i,f,this.logger),!f)return}qh(e,this.observer,a,o,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(n){let h=Wh(e.samplerate);u=n.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;o<l;)if(c=Yh(e,a,o,u,d),o+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;o<l-1&&!Rn(a,o);o++);}parseMPEGPES(e,t){let i=t.data,r=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(Xh(i,a)){let l=jh(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=Zh(e,i,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=Re({},t,{type:this._videoTrack?nt.emsg:nt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i;let r=(i=t.pts)!=null?i:t.dts;if(r===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let n=t.data;if(n.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<n.length;){var o;if(a+16>n.length)break;let l=a;if(a+=16,a>=n.length)break;let u=n[a];a+=1;let d=0;if(u&128){let g=u&127;if(g===0||g>4||a+g>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)d=d<<8|n[a+m];a+=g}else d=u;if(a+d>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let c=a+d,h=n.subarray(l,c),f={data:h,len:h.byteLength,pts:r,dts:(o=t.dts)!=null?o:r,type:nt.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=c}}};function Dn(s,e){return((s[e+1]&31)<<8)+s[e+2]}function rE(s,e){return(s[e+10]&31)<<8|s[e+11]}function nE(s,e,t,i,r,n,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(s[e+1]&15)<<8|s[e+2],d=e+3+u-4,c=(s[e+10]&15)<<8|s[e+11];for(e+=12+c;e<d;){let h=Dn(s,e),f=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){za("ADTS AAC",n);break}case 15:l.audioPid===-1&&(l.audioPid=h);break;case 21:l.id3Pid===-1&&(l.id3Pid=h);break;case 219:if(!i){za("H.264",n);break}case 27:l.videoPid===-1&&(l.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=h,l.segmentAudioCodec="mp3");break;case 193:if(!i){za("AC-3",n);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=h,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(s[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=h,n.log(`KLV metadata PID found: ${h}`));break}let y=s[g+1]+2;g+=y,m-=y}}break;case 194:case 135:return No(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:l.videoPid===-1&&(l.videoPid=h,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=f+5}return l}function No(s,e,t,i,r){r.warn(`parsing error: ${e.message}`),s.emit(E.ERROR,E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:t,error:e,reason:e.message})}function za(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Ui(s,e){let t=0,i,r,n,a,o,l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=St(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>s.size-6)return null;let d=i[7];d&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,d&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let c=n+9;if(s.size<=c)return null;s.size-=c;let h=new Uint8Array(s.size);for(let f=0,g=l.length;f<g;f++){i=l[f];let m=i.byteLength;if(c)if(c>m){c-=m;continue}else i=i.subarray(c),m-=c,c=0;h.set(i,t),t+=m}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var Fo=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=Dn(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let i=(e[3]&48)>>4;if(i===0)return;let r=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=r;let a=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;let u=a?n+1&15:n;if(r!==u){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${u} Last-CC=${n}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}},Bo=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},kn,aE={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Xa=new Uint8Array([0,0,0,0,0,0,0,0]),oE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),lE=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),uE=new Uint8Array([0,0,0,0,0,0,0,0]),Us=new Uint8Array([0,0,0,0,0,0,0,1]),hc=new Uint8Array([105,115,111,109]),dE=new Uint8Array([97,118,99,49]),cE=new Uint8Array([0,0,0,1]),Zt=class s{static box(e,...t){let i=8,r=t.length,n=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(Ue(a,0,i),Ue(a,4,e),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return s.box(re.hdlr,aE[e])}static mdat(e){return s.box(re.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(Gt+1)),r=Math.floor(t%(Gt+1));return s.box(re.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(re.mdia,s.mdhd(e.timescale||0,e.duration||0),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(re.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?s.box(re.minf,s.box(re.smhd,uE),s.DINF,s.stbl(e)):s.box(re.minf,s.box(re.vmhd,lE),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(re.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[re.moov,s.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[re.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Gt+1)),r=Math.floor(t%(Gt+1)),n=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,r>>24,r>>16&255,r>>8&255,r&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 s.box(re.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return s.box(re.sdtp,i)}static stbl(e){return s.box(re.stbl,s.stsd(e),s.box(re.stts,Xa),s.box(re.stsc,Xa),s.box(re.stsz,oE),s.box(re.stco,Xa))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=s.box(re.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,u=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return s.box(re.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,u>>8&255,u&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,s.box(re.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(re.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(re.mp4a,s.audioStsd(e),s.box(re.esds,s.esds(e)))}static mp3(e){return s.box(re[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(re["ac-3"],s.audioStsd(e),s.box(re.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return s.box(re.stsd,Us,s.mp4a(e));if(t==="ac3"&&e.config)return s.box(re.stsd,Us,s.ac3(e));if(t==="mp3"&&e.codec==="mp3")return s.box(re.stsd,Us,s.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return s.box(re.stsd,Us,s.avc1(e));if(t==="hevc"&&e.vps)return s.box(re.stsd,Us,s.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(Gt+1)),o=Math.floor(i%(Gt+1));return s.box(re.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,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(Gt+1)),a=Math.floor(t%(Gt+1));return s.box(re.traf,s.box(re.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(re.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(re.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(re.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){let i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n),o,l,u,d,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],u=l.duration,d=l.size,c=l.flags,h=l.cts,a.set([u>>>24&255,u>>>16&255,u>>>8&255,u&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return s.box(re.trun,a)}static initSegment(e){let t=s.moov(e);return St(s.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let g=0;g<i.length;g+=1){a+=3;for(let m=0;m<i[g].length;m+=1)a+=2+i[g][m].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let g=0;g<i.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,i[g].length]),a),a+=3;for(let m=0;m<i[g].length;m+=1)o.set(new Uint8Array([i[g][m].length>>8,i[g][m].length&255]),a),a+=2,o.set(i[g][m],a),a+=i[g][m].length}let u=s.box(re.hvcC,o),d=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return s.box(re.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&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]),u,s.box(re.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(re.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};kn=Zt;Zt.FTYP=kn.box(re.ftyp,hc,cE,hc,dE);Zt.DINF=kn.box(re.dinf,kn.box(re.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var ef=9e4;function jl(s,e,t=1,i=!1){let r=s*e*t;return i?Math.round(r):r}function hE(s,e,t=1,i=!1){return jl(s,e,1/t,i)}function $s(s,e=!1){return jl(s,1e3,1/ef,e)}function fE(s,e=1){return jl(s,ef,1/e)}function fc(s){let{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}var gE=10*1e3,mE=1024,pE=1152,vE=1536,Uo=8589934592;function gc(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1,paddingValue:0}}}var fs=class extends at{constructor(e,t,i,r){super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&fc(t)} > ${e&&fc(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=mt(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,n,a,o,l,u){let d,c,h,f,g,m,p=n,y=n,v=!u.iframe&&e.pid>-1,_=t.pid>-1,S=t.samples.length,A=e.samples.length>0,b=o&&S>0||S>1;if((!v||A)&&(!_||b)||this.ISGenerated||o){if(this.ISGenerated){var L,R,I,P;let C=this.videoTrackConfig;(C&&(t.width!==C.width||t.height!==C.height||((L=t.pixelRatio)==null?void 0:L[0])!==((R=C.pixelRatio)==null?void 0:R[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((P=C.pixelRatio)==null?void 0:P[1]))||!C&&b||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));let w=this.isVideoContiguous,B=-1,U;if(b&&(B=yE(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,B>0){this.warn(`Dropped ${B} out of ${S} video samples due to a missing keyframe`);let C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,y+=(t.samples[0].pts-C)/t.inputTimeScale,U=y}else B===-1&&(this.warn(`No keyframe found out of ${S} video samples`),m=!1);if(this.ISGenerated){if(A&&b&&n){let C=this.getVideoStartPts(t.samples),F=(mt(e.samples[0].pts,C)-C)/t.inputTimeScale;p+=Math.max(0,F),y+=Math.max(0,-F)}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,_||b||l===j.AUDIO?y:void 0,u),b){let C=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,y,w,C,u)}}else b&&(d=this.remuxVideo(t,y,w,0,u));d&&(d.firstKeyFrame=B,d.independent=B!==-1,d.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=tf(i,n,this._initPTS,this._initDTS)),r.samples.length&&(f=sf(r,n,this._initPTS))),{audio:c,video:d,initSegment:h,independent:m,text:f,id3:g}}computeInitPts(e,t,i,r){let n=Math.round(i*t),a=mt(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n;)a+=Uo;return a-n}generateIS(e,t,i,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},u=this._initPTS,d=!u||r,c="audio/mp4",h,f,g,m=-1;if(d&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Zt.initSegment([e]),metadata:{channelCount:e.channelCount}},d){m=e.id,g=e.inputTimeScale;let p=this.computeInitPts(n[0].pts,g,i,"audio");(!u||g!==u.timescale||i===0&&p<u.baseTime)&&(h=f=p)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Zt.initSegment([t]),metadata:{width:t.width,height:t.height}},d){m=t.id,g=t.inputTimeScale;let p=this.getVideoStartPts(a),y=mt(a[0].dts,p),T=this.computeInitPts(y,g,i,"video"),v=this.computeInitPts(p,g,i,"video");(!u||g!==u.timescale||H(h)||i===0&&v<u.baseTime)&&(f=Math.min(f,T),h=Math.min(h,T))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d&&H(h)?(u&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/g} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/g} (${h}/${g}) trackId: ${m}`),this._initPTS={baseTime:h,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):h=g=void 0,{tracks:l,initPTS:h,timescale:g,trackId:m}}remuxVideo(e,t,i,r,n){let a=e.inputTimeScale,o=e.samples,l=[],u=o.length,d=this._initPTS,c=d.baseTime*a/d.timescale,h=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,p,y=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,v=!1;if(!i||h===null){let $=c+t*a,K=o[0].pts-mt(o[0].dts,o[0].pts);Vs()&&h!==null&&Math.abs($-K-(h+c))<15e3?i=!0:h=$-K-c}let _=h+c;for(let $=0;$<u;$++){let K=o[$];K.pts=mt(K.pts,_),K.dts=mt(K.dts,_),K.dts<o[$>0?$-1:$].dts&&(v=!0)}v&&o.sort(function($,K){let se=$.dts-K.dts,ee=$.pts-K.pts;return se||ee}),m=o[0].dts,p=o[o.length-1].dts;let S=p-m,A=S?Math.round(S/(u-1)):g||e.inputTimeScale/30;if(i){let $=m-_,K=$>A,se=$<-1;if((K||se)&&(K?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${$s($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${$s(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!se||_>=o[0].pts||Vs())){m=_;let ee=o[0].pts-$;if(K)o[0].dts=m,o[0].pts=ee;else{let ue=!0;for(let ie=0;ie<o.length&&!(o[ie].dts>ee&&ue);ie++){let ge=o[ie].pts;if(o[ie].dts-=$,o[ie].pts-=$,ie<o.length-1){let le=o[ie+1].pts,ve=o[ie].pts,Ge=le<=ve,lt=le<=ge;ue=Ge==lt}}}this.log(`Video: Initial PTS/DTS adjusted: ${$s(ee,!0)}/${$s(m,!0)}, delta: ${$s($,!0)} ms`)}}m=Math.max(0,m);let b=0,x=0,L=m;for(let $=0;$<u;$++){let K=o[$],se=K.units,ee=se.length,ue=0;for(let ie=0;ie<ee;ie++)ue+=se[ie].data.length;x+=ue,b+=ee,K.length=ue,K.dts<L?(K.dts=L,L+=A/4|0||1):L=K.dts,y=Math.min(K.pts,y),T=Math.max(K.pts,T)}p=o[u-1].dts;let R=x+4*b+8,I;try{I=new Uint8Array(R)}catch($){this.observer.emit(E.ERROR,E.ERROR,{type:Q.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:$,bytes:R,reason:`fail allocating video mdat ${R}`});return}Ue(I,0,R),Ue(I,4,re.mdat);let P=!1,w=Number.POSITIVE_INFINITY,B=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let $=0;$<u;$++){let K=o[$],se=K.units,ee=0;for(let ge=0,le=se.length;ge<le;ge++){let ve=se[ge],Ge=ve.data,lt=ve.data.byteLength;Ue(I,f,lt),f+=4,I.set(Ge,f),f+=lt,ee+=4+lt}let ue;if($<u-1)g=o[$+1].dts-K.dts,ue=o[$+1].pts-K.pts;else{let ge=this.config,le=$>0?K.dts-o[$-1].dts:A;if(ue=$>0?K.pts-o[$-1].pts:A,ge.stretchShortVideoTrack&&this.nextAudioTs!==null){let ve=Math.floor(ge.maxBufferHole*a),Ge=(r?y+r*a:this.nextAudioTs+c)-K.pts;Ge>ve?(g=Ge-le,g<0?g=le:P=!0,this.log(`It is approximately ${Ge/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=le}else g=le}let ie=Math.round(K.pts-K.dts);if(w=Math.min(w,g),U=Math.max(U,g),B=Math.min(B,ue),C=Math.max(C,ue),!i&&$===0&&ie>g){let ge=Math.round(ie/A)*A;ge-ie===1&&(this.log(`pad first CTS ${ie} -> ${ge} of sn: ${n.sn}`),ie=ge)}l.push(gc(K.key,g,ee,ie))}if(l.length){let $=Vs();if($){if($<70){let K=l[0].flags;K.dependsOn=2,K.isNonSync=0}}else if(Ov()&&C-B<U-w&&A/U<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let K=m;for(let se=0,ee=l.length;se<ee;se++){let ue=K+l[se].duration,ie=K+l[se].cts;if(se<ee-1){let ge=ue+l[se+1].cts;l[se].duration=ge-ie}else l[se].duration=se?l[se-1].duration:A;l[se].cts=0,K=ue}}}g=P||!g?A:g;let N=p+g;this.nextVideoTs=h=N-c,this.videoSampleDuration=g,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=g=n.duration*a,this.nextVideoTs=h=m+g-c):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let W={data1:Zt.moof(n.sn,m,Re(e,{samples:l})),data2:I,startPTS:(y-c)/a,endPTS:(T+g-c)/a,startDTS:(m-c)/a,endDTS:h/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return pE;case"ac3":return vE;default:return mE}}remuxAudio(e,t,i,r,n,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,u=o/l,d=this.getSamplesPerFrame(e),c=d*u,h=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=n!==void 0,p=e.samples,y=f?0:8,T=this.nextAudioTs||-1,v=h.baseTime*o/h.timescale,_=v+t*o;if(this.isAudioContiguous=i=i||p.length&&T>0&&(r&&Math.abs(_-(T+v))<9e3||Math.abs(mt(p[0].pts,_)-(T+v))<20*c),p.forEach(function(N){N.pts=mt(N.pts,_)}),!i||T<0){let N=p.length;if(p=p.filter(F=>F.pts>=0),N!==p.length&&this.warn(`Removed ${p.length-N} of ${N} samples (initPTS ${v} / ${o})`),!p.length)return;n===0?T=0:r&&!m?T=Math.max(0,_-v):T=p[0].pts-v}if(e.segmentCodec==="aac"){let N=this.config.maxAudioFramesDrift;for(let F=0,G=T+v;F<p.length;F++){let W=p[F],$=W.pts,K=$-G,se=Math.abs(1e3*K/o);if(K<=-N*c&&m)F===0&&(this.warn(`Audio frame @ ${($/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*K/o)} ms.`),this.nextAudioTs=T=$-v,G=$);else if(K>=N*c&&se<gE&&m){let ee=Math.round(K/c);for(G=$-ee*c;G<0&&ee&&c;)ee--,G+=c;F===0&&(this.nextAudioTs=T=G-v),this.warn(`Injecting ${ee} audio frames @ ${((G-v)/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let ue=0;ue<ee;ue++){let ie=Bo.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=W.unit.subarray()),p.splice(F,0,{unit:ie,pts:G}),G+=c,F++}}W.pts=G,G+=c}}let S=null,A=null,b,x=0,L=p.length;for(;L--;)x+=p[L].unit.byteLength;for(let N=0,F=p.length;N<F;N++){let G=p[N],W=G.unit,$=G.pts;if(A!==null){let se=g[N-1];se.duration=Math.round(($-A)/u)}else if(i&&e.segmentCodec==="aac"&&($=T+v),S=$,x>0){x+=y;try{b=new Uint8Array(x)}catch(se){this.observer.emit(E.ERROR,E.ERROR,{type:Q.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:se,bytes:x,reason:`fail allocating audio mdat ${x}`});return}f||(Ue(b,0,x),Ue(b,4,re.mdat))}else return;b&&b.set(W,y);let K=W.byteLength;y+=K,g.push(gc(!0,d,K,0)),A=$}let R=g.length;if(!R)return;let I=g[g.length-1];T=A-v,this.nextAudioTs=T+u*I.duration;let P=f?new Uint8Array(0):Zt.moof(e.sequenceNumber++,S/u,Re({},e,{samples:g}));e.samples=[];let w=(S-v)/o,B=this.nextAudioTs/o,C={data1:P,data2:b,startPTS:w,endPTS:B,startDTS:w,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,C}};function mt(s,e){let t;if(e===null)return s;for(e<s?t=-Uo:t=Uo;Math.abs(s-e)>4294967296;)s+=t;return s}function yE(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function tf(s,e,t,i){let r=s.samples.length;if(!r)return;let n=s.inputTimeScale;for(let o=0;o<r;o++){let l=s.samples[o];l.pts=mt(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=mt(l.dts-i.baseTime*n/i.timescale,e*n)/n}let a=s.samples;return s.samples=[],{samples:a}}function sf(s,e,t){let i=s.samples.length;if(!i)return;let r=s.inputTimeScale;for(let a=0;a<i;a++){let o=s.samples[a];o.pts=mt(o.pts-t.baseTime*r/t.timescale,e*r)/r}s.samples.sort((a,o)=>a.pts-o.pts);let n=s.samples;return s.samples=[],{samples:n}}var $o=class extends at{constructor(e,t,i,r){super("passthrough-remuxer",r),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=i||uh(e);if(t)Tv(e,t);else{let u=a||o;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}a&&(r=mc(a,Le.AUDIO,this)),o&&(n=mc(o,Le.VIDEO,this));let l={};a&&o?l.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,r,n,a,o,l,u,d,c){var h,f;let{initPTS:g,lastEndTime:m}=this,p={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};H(m)||(m=this.lastEndTime=n||0);let y=t.samples;if(!y.length)return p;let T=this.pendingInitSegment;T&&(this.pendingInitSegment=void 0,this.generateInitSegment(T,this.decryptdata,d));let v={initPTS:void 0,timescale:void 0,trackId:void 0},_=this.initData;if((h=_)!=null&&h.length||(this.generateInitSegment(y),_=this.initData),!((f=_)!=null&&f.length))return this.warn("Failed to generate initSegment."),p;if(u.iframe&&_.audio&&_.video){var S;let X=(S=this.initTracks)==null||(S=S.audiovideo)==null?void 0:S.initSegment,he=X?gv(X):null;if(he){var A;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(he,this.decryptdata),(A=this.initData)!=null&&A.length&&(_=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(v.tracks=this.initTracks,p.initSegment=v,this.emitInitSegment=!1);let b=u.iframe,x=c&&(!b||c.includeSampleDetails)?c.tracks:Av(y,_,u,this,b),L=_.audio?x[_.audio.id]:null,R=_.video?x[_.video.id]:null,I=!!_.audio,P=!!_.video,w="";I&&(w+="audio"),P&&(w+="video");let B=Yr(R,1/0),U=Yr(L,1/0),C=Yr(R,0,!0),N=Yr(L,0,!0),F=n,G=0;R&&L&&_.audio&&(U>C||B>N)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${B}-${C} a: ${U}-${N}}`,R,L);let W=!!L&&(!R||!g&&U<B||!!g&&g.trackId===_.audio.id),$=W?L:R;if(!$)return this.log(`No media samples found in ${l} ${u.level} ${u.part===-1?"":`part: ${u.part} of`} sn: ${u.sn} at playlist time: ${n}`),p;let K=y,se,ee;if(R&&R.sampleCount>=1&&_.video&&u.iframe){let{trun:X,start:he}=R,pe=X.length===1,Ke=X.length?pe?X[0].samples:X[0].samples.concat(...X.slice(1).map(Fe=>Fe.samples)):[];if(Ke.length){let Fe=X[0],st=Fe;for(let ht=X.length;ht--;)if(X[ht].samples.length){st=X[ht];break}let At=st.lastSampleDurationOffset,{defaultSampleDurationOffset:wi}=Fe,Je=Math.abs(u.duration-(C-B))>.05,rt=Ke.length<R.sampleCount;if(!(Je||rt||this.videoOnlyRemux||!pe))G=C-B;else{let ht=rt?st.sampleOffset+st.samples.reduce((Rt,Ku)=>Rt+Ku.size,0):void 0,tt=Je?u.duration:C-B,oi=TE(Ke,tt*_.video.timescale,At,wi),jt=mv(y,_.video.id,Ke.length,ht,oi);jt?(K=jt,ee=EE(he,Ke)):this.warn(`IFrame remux skipped (sn ${u.sn}); using native sample duration`),G=jt&&oi?tt:C-B}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${X.length})`),G=C-B}else G=W?N-U:C-B;if(this.videoOnlyRemux&&K===y)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${u.sn})`),p;let ue=$.timescale,ie=$.start-n*ue,ge=W?_.audio.id:_.video.id;if(F=$.start/ue,(a||!g)&&(_E(g,F,n,G)||ue!==g.timescale)){let X=!1,he=W?"audio":"video";if(g){let pe=n!==0?F/n:1+F/1;X=F>=0&&Math.abs(1-pe)<.001,this.log(`${he} timestamps in track ${ge} at playlist time: ${a?"":"~"}${n} maps to ${F} with initPTS: ${g.baseTime/g.timescale} (${ie/ue-g.baseTime/g.timescale}s diff) (${w}) drift estimate: ${pe} ${X?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}X||(this.log(`Found initPTS in ${he} track ${ge} at playlist time: ${n} offset: ${F-n} (${ie}/${ue})`),g=null,v.initPTS=ie,v.timescale=ue,v.trackId=ge)}g?(v.initPTS=g.baseTime,v.timescale=g.timescale,v.trackId=g.trackId):((!v.timescale||v.trackId===void 0||v.initPTS===void 0)&&(this.warn("Could not set initPTS"),v.initPTS=F,v.timescale=1,v.trackId=-1),this.initPTS=g={baseTime:v.initPTS,timescale:v.timescale,trackId:v.trackId});let le=F-g.baseTime/g.timescale,ve=le+G,Ge=P&&($==null?void 0:$.ptsMin)!==void 0?$.ptsMin/$.timescale-g.baseTime/g.timescale:le,lt=ee!==void 0&&R?ee/R.timescale-g.baseTime/g.timescale:P&&$!=null&&$.ptsMax?$.ptsMax/$.timescale-g.baseTime/g.timescale:ve;G>0?this.lastEndTime=ve:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let Yt=(_.audio?_.audio.encrypted:!1)||(_.video?_.video.encrypted:!1),Pe={data1:K,data2:se,startPTS:Ge,startDTS:le,endPTS:lt,endDTS:ve,type:w,hasAudio:I,hasVideo:P,nb:1,dropped:0,encrypted:Yt};p.audio=I&&!P?Pe:void 0,p.video=P?Pe:void 0;let yt=this.isVideoContiguous,Ft=R==null?void 0:R.sampleCount;if(Ft){let X=R.keyFrameIndex,he=X!==-1;Pe.nb=Ft,Pe.dropped=X===0||yt?0:he?X:Ft,Pe.independent=he,Pe.firstKeyFrame=X,he&&R.keyFrameStart&&(Pe.firstKeyFramePTS=(R.keyFrameStart-g.baseTime)/g.timescale),yt||(p.independent=he),this.isVideoContiguous||(this.isVideoContiguous=he),Pe.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${X}/${Ft} dropped: ${Pe.dropped} start: ${Pe.firstKeyFramePTS||"NA"}`)}return p.initSegment=v,p.id3=tf(i,n,g,g),r.samples.length&&(p.text=sf(r,n,g)),p}};function Yr(s,e,t=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function EE(s,e){let t=s,i=s;for(let r=0;r<e.length;r++){let{cts:n,duration:a}=e[r];i=Math.max(i,t+(n||0)+a),t+=a}return i}function TE(s,e,t,i){if(t!==void 0){let n=s[s.length-1],a=e;for(let o=0;o<s.length-1;o++)a-=s[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(i===void 0)return;let r=Math.round(e/s.length);for(let n=0;n<s.length;n++)s[n].duration=r;return{durationOffset:i,value:r}}function _E(s,e,t,i){if(s===null)return!0;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>=r}function mc(s,e,t){let i=s.codec;return i&&i.length>4?i:e===Le.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?cn(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):i==="mjpg"?i:(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var hi;try{hi=self.performance.now.bind(self.performance)}catch{hi=Date.now}var nn=[{demux:wo,remux:$o},{demux:Ln,remux:fs},{demux:ko,remux:fs},{demux:Co,remux:fs}];nn.splice(2,0,{demux:Po,remux:fs});var Pn=class{constructor(e,t,i,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){if(!this.observer)return jr(i);let n=i.transmuxing;n.executeStart=hi();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:u,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:g}=r||o,{audioCodec:m,videoCodec:p,defaultInitPts:y,duration:T,initSegmentData:v}=l,_=SE(a,t);if(_&&hs(_.method)){let x=this.getDecrypter(),L=Vl(_.method);return this.asyncResult=!0,this.decryptionPromise=x.decrypt(a,_.key.buffer,_.iv.buffer,L,i.decryptRange).then(R=>{let I=this.push(R,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}let S=this.needsProbing(d,c);if(S){let x=i.iframe&&v&&Ln.probe(v,this.logger)?v:a,L=this.configureTransmuxer(x);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),n.executeEnd=hi(),jr(i)}(d||c||g||S)&&this.resetInitSegment(v,m,p,T,t,i),(d||g||S)&&this.resetInitialTimestamp(y),u||this.resetContiguity();let A=this.transmux(a,_,f,h,i);this.asyncResult=or(A);let b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=hi(),A}flush(e){let t=e.transmuxing;t.executeStart=hi();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(i){let c=i.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:u}=this;if(!l||!u){t.executeEnd=hi();let c=[jr(e)];return this.asyncResult?Promise.resolve(c):c}let d=l.flush(o,e);return or(d)?(this.asyncResult=!0,d.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,d,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){if(!this.remuxer)return;let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:u}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);let d=this.remuxer.remux(r,n,a,o,u,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=hi()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,n,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,i,r,n,a),l.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,r,n){let a;return(t==null?void 0:t.method)==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){let{demuxer:n,remuxer:a}=this;if(!n||!a)return jr(r);let o=n.demux(e,t,r,!1,!this.config.progressive),{audioTrack:l,videoTrack:u,id3Track:d,textTrack:c}=o;return{remuxResult:a.remux(l,u,d,c,t,i,!1,this.id,r,o.initData,o.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r}=this;if(!i)return;let n;try{for(let c=0,h=nn.length;c<h;c++){var a;if((a=nn[c].demux)!=null&&a.probe(e,this.logger)){n=nn[c];break}}}catch(c){return c}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,u=n.demux,d=n.remux;(!o||!(o instanceof u))&&(this.logger.log(`Using ${u.name}`),this.demuxer=new u(i,t,r,this.logger),this.probe=u.probe),(!l||!(l instanceof d))&&(this.logger.log(`Using ${d.name}`),this.remuxer=new d(i,t,r,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ir(this.config)),e}};function SE(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var jr=s=>({remuxResult:{},chunkMeta:s});function or(s){return"then"in s&&s.then instanceof Function}var Go=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null}},Ko=class{constructor(e,t,i,r,n,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=r,this.timeOffset=n,this.initSegmentChange=a}},pc=0,Cn=class{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=pc++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let u=l.data,d=this.hls;if(!(!d||!(u!=null&&u.event)||u.instanceNo!==this.instanceNo))switch(u.event){case"init":{var c;let h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(u.data);break}case"flush":{this.onFlush(u.data);break}case"workerLog":{d.logger[u.data.logType]&&d.logger[u.data.logType](u.data.message);break}default:{u.data=u.data||{},u.data.frag=this.frag,u.data.part=this.part,u.data.id=this.id,d.trigger(u.event,u.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let u=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(l,u)=>{u=u||{},u.frag=this.frag||void 0,l===E.ERROR&&(u=u,u.parent=this.id,u.part=this.part,this.error=u.error),this.hls.trigger(l,u)};this.observer=new ql,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);let o=Od(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||$y()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Ky(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Gy());let{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ke(n)})}catch(d){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new Pn(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Pn(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=pc++;let t=this.hls.config,i=Od(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ke(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Vy(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,n,a,o,l,u,d){var c,h;u.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:n.start,p=n.decryptdata,y=this.frag,T=y?n.cc!==y.cc:!0,v=y?u.level!==y.level:!0,_=y?u.sn-y.sn:-1,S=this.part?u.part-this.part.index:-1,A=_===0&&u.id>1&&u.id===(y==null?void 0:y.stats.chunkCount),b=!v&&(_===1||_===0&&(S===1||A&&S<=0)),x=self.performance.now();(v||_||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(S||!b)&&(a.stats.parsing.start=x);let L=!(y&&((c=n.initSegment)==null?void 0:c.url)===((h=y.initSegment)==null?void 0:h.url)),R=new Ko(T,b,l,v,m,L);if(!b||T||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${u.sn}${u.part>-1?" part: "+u.part:""} ${this.id} playlist: ${u.level} id: ${u.id}
|
|
32
32
|
discontinuity: ${T}
|
|
33
|
-
trackSwitch: ${
|
|
34
|
-
contiguous: ${
|
|
33
|
+
trackSwitch: ${v}
|
|
34
|
+
contiguous: ${b}
|
|
35
35
|
accurateTimeOffset: ${l}
|
|
36
|
-
timeOffset: ${
|
|
37
|
-
initSegmentChange: ${I}`);let L=new io(i,r,t,o,d);this.configureTransmuxer(L)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:u,state:A},e instanceof ArrayBuffer?[e]:[]);else if(m){let L=m.push(e,g,u,A);Ms(L)?L.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,u,"transmuxer-interface push error")}):this.handleTransmuxComplete(L)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let r=i.flush(e);Ms(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},_d=100,ro=class extends Ps{constructor(e,t,i){super(e,t,i,"audio-stream-controller",W.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){if(i===W.MAIN){let o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){let u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(t,u==null?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===C.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(r==null?void 0:r.cc)===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=rc(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(_d),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e==null?void 0:e[t],r=i==null?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case C.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=C.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=C.WAITING_TRACK,this.startFragRequested=!1;return}let u=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&u&&(this.bufferFlushed=!1,this.afterBufferFlushed(u,_e.AUDIO,W.AUDIO));let d=this.getFwdBufferInfo(u,W.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}let c=d.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:d.end;if(this.switchingTrack&&r){let E=p;l.PTSKnown&&E<m&&(d.end>m||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(c>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let v=this.getNextFragment(g,l);if(v&&this.isLoopLoading(v,g)&&(v=this.getNextFragmentLoopLoading(v,l,d,W.MAIN,h)),!v){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&Le(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Oe.OK&&(this.mainFragLoading=T=null),T&&Le(T))){if(v.start>T.end){let _=this.fragmentTracker.getFragAtPos(g,W.MAIN);_&&_.end>T.end&&(T=_,this.mainFragLoading={frag:_,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new bi(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(_d),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let u=this.mainDetails;if(!u||n.endCC>u.endCC||u.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let d=r[a],c=0;if(n.live||(i=d.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(d.details){var h;c=this.alignPlaylists(n,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(Tc(n,u),n.alignedSliding||Wr(n,u),c=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(u,c),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=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}let u=l[o];if(!u){this.warn("Audio track is undefined on fragment load progress");return}let d=u.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let c=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Qr(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,v=g!==-1,T=new ks(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,v);h.push(n,m,c,"",i,r,d.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Yr,complete:!1};p.push(new Uint8Array(n)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===W.MAIN&&Le(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==W.AUDIO){!this.audioOnly&&i.type===W.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Le(i)){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,ge({},n)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,t);break;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ae.AUDIO_TRACK&&(this.state=C.IDLE);break;case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case k.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==_e.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==_e.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,W.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:u,level:d}=o,{details:c}=d,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(d,p.tracks,g,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:p.tracks})}if(h){let{startPTS:g,endPTS:v,startDTS:T,endDTS:E}=h;u&&(u.elementaryStreams[_e.AUDIO]={startPTS:g,endPTS:v,startDTS:T,endDTS:E}),l.setElementaryStreamInfo(_e.AUDIO,g,v,T,E),this.bufferFragmentData(h,l,u,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let g=Ee({id:i,frag:l,details:c},m);r.trigger(y.FRAG_PARSING_METADATA,g)}if(f){let g=Ee({id:i,frag:l,details:c},f);r.trigger(y.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=W.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Oe.NOT_LOADED||r===Oe.PARTIAL){var n;if(!Le(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.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=C.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Wr(t.details,a)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;_i({name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,Ei)||(Br(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,ge({},e))}},Ns=class extends Je{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=t==null?void 0:t.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href}catch(u){this.warn(`Could not construct new URL for Rendition Report: ${u}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let d=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&d>t.partTarget&&(l+=1)}let u=i&&Uu(i);return new Ur(o,l>=0?l:void 0,u)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let d=Math.max(l||0,0);r.appliedTimelineOffset=d,r.fragments.forEach(c=>{c.setStart(c.playlistOffset+d)})}if(r.live||i!=null&&i.live){let d="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){k0(i,r,this);let T=r.playlistParsingError;if(T){this.warn(T);let E=this.hls;if(!E.config.ignorePlaylistParsingErrors){var u;let{networkDetails:_}=t;E.trigger(y.ERROR,{type:z.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:T,reason:T.message,level:t.level||void 0,parent:(u=r.fragments[0])==null?void 0:u.type,networkDetails:_,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,f=(r.edge-h)*1e3,m=gc(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,v;if(r.canBlockReload&&r.endSN&&r.advanced){let T=this.hls.config.lowLatencyMode,E=r.lastPartSn,_=r.endSN,b=r.lastPartIndex,x=b!==-1,S=E===_;x?S?(g=_+1,v=T?0:b):(g=E,v=T?b+1:r.maxPartIndex):g=_+1;let R=r.age,I=R+r.ageHeader,A=Math.min(I-r.partTarget,r.targetduration*1.5);if(A>0){if(I>r.targetduration*3)this.log(`Playlist last advanced ${R.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&I-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${A} with playlist age: ${r.age}`),A=0;else{let L=Math.floor(A/r.targetduration);if(g+=L,v!==void 0){let P=Math.round(A%r.targetduration/r.partTarget);v+=P}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${A} skip sn ${L} to part ${v}`)}r.tuneInGoal=A}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v),T||!S){r.requestScheduled=a,this.loadingPlaylist(d,p);return}}else(r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(d,p,r)}else this.clearTimer()}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,r){let n=Uu(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=Lr.No),new Ur(i,r,n)}checkRetry(e){let t=e.details,i=$r(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Be.RetryRequest||!r.resolved&&n===Be.SendAlternateToPenaltyBox);if(l){var u;if(a>=o.maxNumRetry)return!1;if(i&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let d=jo(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,r.resolved=!0}return l}};function Uc(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Fs(s[t].attrs,e[t].attrs))return!1;return!0}function Fs(s,e,t){let i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function no(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}var ao=class extends Ns{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{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(){let{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.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} 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){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=xt(l,o,Ei);if(h>-1)n=o[h];else{let f=xt(l,this.tracks);n=this.tracks[f]}}let u=this.findTrackId(n);u===-1&&n&&(u=this.findTrackId(null));let d={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,d);let c=this.trackId;if(u!==-1&&c===-1)this.setAudioTrack(u);else if(o.length&&c===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===ae.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&_i(e,r,Ei))return r;let n=xt(e,this.tracksInGroup,Ei);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=n0(e,t.levels,i,a,Ei);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=xt(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,ge({},r)),n))return;let a=this.switchParams(r.url,i==null?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||_i(e,r,Ei)))return i}if(e){let{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let u=0;u<t.length;u++){let d=t[u];if(_i({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},d,Ei))return u}for(let u=0;u<t.length;u++){let d=t[u];if(Fs(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(let u=0;u<t.length;u++){let d=t[u];if(Fs(e.attrs,d.attrs,["LANGUAGE"]))return u}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Br(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e})}},oo=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(n){var i;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
36
|
+
timeOffset: ${m}
|
|
37
|
+
initSegmentChange: ${L}`);let I=new Go(i,r,t,o,d);this.configureTransmuxer(I)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:u,state:R},e instanceof ArrayBuffer?[e]:[]);else if(g){let I=g.push(e,p,u,R);or(I)?I.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,u,"transmuxer-interface push error")}):this.handleTransmuxComplete(I)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let r=i.flush(e);or(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},vc=100,Vo=class extends rr{constructor(e,t,i){super(e,t,i,"audio-stream-controller",j.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:i,id:r,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(r===j.MAIN){let u=i.cc,d=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${u} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=i,this.state===O.WAITING_INIT_PTS){let c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==u)&&this.syncWithAnchor(i,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&d&&d.cc!==u?(d.abortRequests(),this.syncWithAnchor(i,d)):this.state===O.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(r==null?void 0:r.cc)===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=xh(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===O.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=O.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(vc),i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case O.IDLE:this.doTickIdle();break;case O.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e==null?void 0:e[t],r=i==null?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=O.WAITING_INIT_PTS}break}case O.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case O.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=O.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=O.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=O.WAITING_TRACK,this.startFragRequested=!1;return}let u=this.getBufferOutput();this.bufferFlushed&&u&&(this.bufferFlushed=!1,this.afterBufferFlushed(u,Le.AUDIO));let d=this.getFwdBufferInfo();if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,l)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=O.ENDED;return}let c=d.len,h=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:d.end;if(this.switchingTrack&&r){let v=m;l.PTSKnown&&v<g&&v>=this.timelineOffset&&(d.end>g||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${v} -> ${g} + 0.05`),r.currentTime=g+.05)}if(c>=h&&!this.switchingTrack&&p<f[f.length-1].start)return;let y=this.getNextFragment(p,l);if(y&&this.isLoopLoading(y,p)&&(y=this.getNextFragmentLoopLoading(y,l,d,j.MAIN,h)),!y){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,h,y))return;let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&Ne(y)&&!y.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Me.OK&&(this.mainFragLoading=T=null),T&&Ne(T))){if(y.start>T.end){let _=this.fragmentTracker.getFragAtPos(p,j.MAIN);_&&_.end>T.end&&(T=_,this.mainFragLoading={frag:_,targetBufferTime:null})}if(y.start>T.end)return}this.loadFragment(y,o,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new qi(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==O.STOPPED&&(this.setInterval(vc),this.state=O.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let u=this.mainDetails;if(!u||n.endCC>u.endCC||u.expired){this.cachedTrackLoadedData=t,this.state!==O.STOPPED&&(this.state=O.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let d=r[a],c=0;if(n.live||(i=d.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(d.details){var h;c=this.alignPlaylists(n,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(_n(u,n,this),c=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(u,c),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===O.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=O.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=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}let u=l[o];if(!u){this.warn("Audio track is undefined on fragment load progress");return}let d=u.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let c=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Cn(this.hls,j.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let p=r?r.index:-1,y=p!==-1,T=new sr(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,y,i.duration);h.push(n,g,c,"",i,r,d.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);let{cache:m}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new An,complete:!1};m.push(new Uint8Array(n)),this.state!==O.STOPPED&&(this.state=O.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===j.MAIN&&Ne(t.frag)&&(this.mainFragLoading=t,this.state===O.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==j.AUDIO){!this.audioOnly&&i.type===j.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ne(i)){let n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(i,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,j.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying,r=e==null?void 0:e.level;return(!i||i.level!==r)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.AUDIO,t);break;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===de.AUDIO_TRACK&&(this.state=O.IDLE);break;case k.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case k.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===O.ENDED&&(this.state=O.IDLE);let i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,t),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:u,level:d}=o,{details:c}=d,{audio:h,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=O.PARSING,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:p}=this,y=p.nextAudioTrackBufferFlushForwardOffset,T=Math.max(this.getLoadPosition()+y,l.start);super.flushMainBuffer(T,Number.POSITIVE_INFINITY,j.AUDIO)}if(m!=null&&m.tracks){let p=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,m.tracks,p,a),r.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(h){let{startPTS:p,endPTS:y,startDTS:T,endDTS:v}=h;u&&(u.elementaryStreams[Le.AUDIO]={startPTS:p,endPTS:y,startDTS:T,endDTS:v}),l.setElementaryStreamInfo(Le.AUDIO,p,y,T,v),this.bufferFragmentData(h,l,u,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let p=Re({id:i,frag:l,details:c},g);r.trigger(E.FRAG_PARSING_METADATA,p)}if(f){let p=Re({id:i,frag:l,details:c},f);r.trigger(E.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,r){if(this.state!==O.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=j.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),(a==null?void 0:a.split(",").length)===1&&(n.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Me.NOT_LOADED||r===Me.PARTIAL){var n;if((n=t.details)!=null&&n.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=O.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&_n(a,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;Vi({name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,Ki)||(gn(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,J({},e))}get nextAudioTrack(){return this.nextTrackId}},lr=class extends at{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=t==null?void 0:t.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href}catch(u){this.warn(`Could not construct new URL for Rendition Report: ${u}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let d=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&d>t.partTarget&&(l+=1)}let u=i&&Md(i);return new fn(o,l>=0?l:void 0,u)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:r,stats:n}=t,a=r.fragments,o=self.performance.now(),l=n.loading.first?Math.max(0,Math.floor(o-n.loading.first)):0;r.advancedDateTime=Date.now()-l;let u=this.hls.config.timelineOffset;if(u!==r.appliedTimelineOffset){let c=Math.max(u||0,0);r.appliedTimelineOffset=c,a.forEach(h=>{h==null||h.setStart(h.playlistOffset+c)})}if(r.live||i!=null&&i.live){var d;let c="levelInfo"in t?t.levelInfo:t.track;r.reloaded(i);let h=(d=a[a.length-1])==null?void 0:d.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let S=new Error(`${h} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(S);let{networkDetails:A,context:b}=t;this.hls.trigger(E.ERROR,{type:Q.NETWORK_ERROR,details:k.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:S,reason:S.message,level:t.level,parent:h,context:b,networkDetails:A,stats:n});return}if(i){Ly(i,r,this);let S=r.playlistParsingError;if(S){this.warn(S);let A=this.hls;if(!A.config.ignorePlaylistParsingErrors){let{networkDetails:b}=t;A.trigger(E.ERROR,{type:Q.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:S,reason:S.message,level:t.level,parent:h,networkDetails:b,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(r.edge-g)*1e3,p=Fh(r,m);r.requestScheduled+p<o?r.requestScheduled=o:r.requestScheduled<=o&&(r.requestScheduled+=p);let y=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?"UPDATED":`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${y?` | requested ${y.msn} - ${y.part}`:""})`}`),!this.canLoad||!r.live)return;let T,v,_;if(r.canBlockReload&&r.advanced){let S=this.hls.config.lowLatencyMode,A=r.lastPartSn,b=r.endSN,x=r.lastPartIndex,L=x!==-1,R=A===b;L?R?(v=b+1,_=S?0:x):(v=A,_=S?x+1:r.maxPartIndex):v=b+1;let I=r.age,P=I+r.ageHeader,w=Math.min(P-r.partTarget,r.targetduration*1.5);if(w>0){if(P>r.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,_=void 0;else if(i!=null&&i.tuneInGoal&&P-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${w} with playlist age: ${r.age}`),w=0;else{let B=Math.floor(w/r.targetduration);if(v+=B,_!==void 0){let U=Math.round(w%r.targetduration/r.partTarget);_+=U}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${w} skip sn ${B} to part ${_}`)}r.tuneInGoal=w}if(T=this.getDeliveryDirectives(r,t.deliveryDirectives,v,_),S||!R){r.requestScheduled=o,this.loadingPlaylist(c,T);return}}else(r.canBlockReload||r.canSkipUntil)&&(T=this.getDeliveryDirectives(r,t.deliveryDirectives,v,_));T&&v!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(p-l*2,p/2)),this.scheduleLoading(c,T,r)}else this.clearTimer()}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}let o=Math.max(a-n,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,r){let n=Md(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=rn.No),new fn(i,r,n)}checkRetry(e){let t=e.details,i=un(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Qe.RetryRequest||!r.resolved&&n===Qe.SendAlternateToPenaltyBox);if(l){var u;if(a>=o.maxNumRetry)return!1;if(i&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var d;let c=Xs((d=e.response)==null?void 0:d.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let h=Nl(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),h)}}e.levelRetry=!0,r.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),Xs(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function rf(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!ur(s[t].attrs,e[t].attrs))return!1;return!0}function ur(s,e,t){let i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}var Ho=class extends lr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} 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){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>tr(h.groupId,i));if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=Ht(l,o,Ki);if(h>-1)n=o[h];else{let f=Ht(l,this.tracks);n=this.tracks[f]}}let u=this.findTrackId(n);u===-1&&n&&(u=this.findTrackId(null));let d={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,d);let c=this.trackId;if(u!==-1&&c===-1)this.setAudioTrack(u);else if(o.length&&c===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===de.AUDIO_TRACK&&t.context.id===this.trackId&&tr(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&Vi(e,r,Ki))return r;let n=Ht(e,this.tracksInGroup,Ki);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=ry(e,t.levels,i,a,Ki);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=Ht(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e,t=!0){let i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,n=i[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===r&&a||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,J(J({},n),{},{flushImmediate:t})),a))return;let o=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Vi(e,r,Ki)))return i}if(e){let{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let u=0;u<t.length;u++){let d=t[u];if(Vi({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},d,Ki))return u}for(let u=0;u<t.length;u++){let d=t[u];if(ur(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(let u=0;u<t.length;u++){let d=t[u];if(ur(e.attrs,d.attrs,["LANGUAGE"]))return u}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&gn(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e})}},qo=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;i==="async-blocker"||i==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):i==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(n){var i;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
38
38
|
${this.list("video")}
|
|
39
39
|
${this.list("audio")}
|
|
40
|
-
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],r=i==null?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},
|
|
41
|
-
required tracks: ${
|
|
42
|
-
transfer tracks: ${Se(r,(l,u)=>l==="initSegment"?void 0:u)}}`),!Gd(r,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,u=this.details,d=Math.max(l,(u==null?void 0:u.fragments[0].start)||0);if(d-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,n.forEach(l=>{let u=l,d=r[u];if(d){let c=d.buffer;if(c){let h=this.fragmentTracker,f=d.id;if(h.hasFragments(f)||h.hasParts(f)){let g=ie.getBuffered(c);h.detectEvictedFragments(u,g,f,null,!0)}let m=ma(u),p=[u,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(u),this.trackSourceBuffer(u,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let u=l.length;u--;)o&&l[u].abort(),n.removeSourceBuffer(l[u]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&bd(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(y.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ma(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new oo(this.tracks)}onBufferCodecs(e,t){var i;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var u,d;let c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c,T=r[l],E=(u=this.transferData)==null||(u=u.tracks)==null?void 0:u[l],_=E!=null&&E.buffer?E:T,b=(_==null?void 0:_.pendingCodec)||(_==null?void 0:_.codec),x=_==null?void 0:_.levelCodec;T||(T=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});let S=Ir(b,x),R=S==null?void 0:S.replace(Sd,"$1"),I=Ir(f,m),A=(d=I)==null?void 0:d.replace(Sd,"$1");I&&S&&R!==A&&(l.slice(0,5)==="audio"&&(I=Nr(I,this.appendSource)),this.log(`switching codec ${b} to ${I}`),I!==(T.pendingCodec||T.codec)&&(T.pendingCodec=I),T.container=p,this.appendChangeType(l,p,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,r=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,W.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&ie.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,W.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:u,offset:d}=t,c=u.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();c.start=m;let p=o.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);let v=i.audio,T=!1;n==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);let E=i.video,_=E==null?void 0:E.buffer;if(_&&h!=="initSegment"){let S=l||o,R=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(E.ending||E.ended)){let A=S.start+S.duration*.05,L=_.buffered,P=this.currentOp("video");!L.length&&!P?this.blockAudio(S):!P&&!ie.isBuffered(_,A)&&this.lastVideoAppendEnd<A&&this.blockAudio(S)}else if(n==="video"){let I=S.end;if(R){let A=R.frag.start;(I>A||I<this.lastVideoAppendEnd||ie.isBuffered(_,A))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}let b=(l||o).start,x={label:`append-${n}`,execute:()=>{var S;c.executeStart=self.performance.now();let R=(S=this.tracks[n])==null?void 0:S.buffer;R&&(T?this.updateTimestampOffset(R,b,.1,n,h,f):d!==void 0&&V(d)&&this.updateTimestampOffset(R,d,1e-6,n,h,f)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{let S=self.performance.now();c.executeEnd=c.end=S,p.first===0&&(p.first=S),g&&g.first===0&&(g.first=S);let R={};this.sourceBuffers.forEach(([I,A])=>{I&&(R[I]=ie.getBuffered(A))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:R})},onError:S=>{var R;let I={type:z.MEDIA_ERROR,parent:o.type,details:k.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:u,error:S,err:S,fatal:!1},A=(R=this.media)==null?void 0:R.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR||S.name=="QuotaExceededError"||"quota"in S)I.details=k.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!A)I.errorAction=Wi(!0);else if(S.name===Bc&&this.sourceBufferCount===0)I.errorAction=Wi(!0);else{let L=++this.appendErrors[n];this.warn(`Failed ${L}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${A||"no media error"})`),(L>=this.hls.config.appendErrorMaxRetry||A)&&(I.fatal=!0)}this.hls.trigger(y.ERROR,I)}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===W.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(x,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:n}=t;i?this.append(this.getFlushOp(i,r,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[_e.AUDIOVIDEO]?n.push("audiovideo"):(a[_e.AUDIO]&&n.push("audio"),a[_e.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let u=r?r.stats:i.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:r,stats:u,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let r=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===k.BUFFER_APPEND_ERROR&&t.frag){var i;let r=(i=t.errorAction)==null?void 0:i.nextAutoLevel;V(r)&&r!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;let r=e.config,n=i.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(V(o)&&o>=0){let u=Math.max(o,a),d=Math.floor(n/a)*a-u;this.flushBackBuffer(n,a,d)}let l=r.frontBufferFlushThreshold;if(V(l)&&l>0){let u=Math.max(r.maxBufferLength,l),d=Math.max(u,a),c=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,c)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=ie.getBuffered(n);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:i});let l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:r})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=ie.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),u=a.end(o-1);if(i>l||e>=l&&e<=u)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let u=Math.max(0,t.fragmentStart),d=Math.max(u,r);return{duration:1/0,start:u,end:d}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return V(n)?{duration:n}:null;let a=this.media.duration,o=V(i.duration)?i.duration:0;return r>o&&r>a||!V(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(V(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Se(i)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(y.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),u=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${u})${this.currentOp(a)?" Queued":""} ${Se(o)}`);try{let d=i.addSourceBuffer(u),c=ma(a),h=[a,d];t[c]=h,o.buffer=d}catch(d){var r;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:u,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&(t==="video"||t==="audiovideo")&&Is(i,"video")&&(r=$p(r,i));let n=Ir(r,e.levelCodec);return n?t.slice(0,5)==="audio"?Nr(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,i,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=V(r.duration)?r.duration:1/0,u=V(n.duration)?n.duration:1/0,d=Math.max(0,t),c=Math.min(i,l,u);c>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${c}] from the ${e} SourceBuffer`),o.remove(d,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.tracks[t],r=i==null?void 0:i.buffer;if(!r)throw new lo(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;let r=(i=this.tracks[t])==null?void 0:i.buffer;!r||r.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(r=>{i.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}};function bd(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Iy(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function ma(s){return s==="audio"?1:0}var Us=class s{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&V(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let 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 Math.min(e,this.hls.config.maxDevicePixelRatio)}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;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},Ly={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Xe=Ly,Dy={HLS:"h"},ky=Dy,Ct=class s{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t}},Py="Dict";function wy(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function Cy(s,e,t,i){return new Error(`failed to ${s} "${wy(e)}" as ${t}`,{cause:i})}function Rt(s,e,t){return Cy("serialize",s,e,t)}var Jr=class{constructor(e){this.description=e}},Ad="Bare Item",Oy="Boolean";function My(s){if(typeof s!="boolean")throw Rt(s,Oy);return s?"?1":"?0"}function Ny(s){return btoa(String.fromCharCode(...s))}var Fy="Byte Sequence";function Uy(s){if(ArrayBuffer.isView(s)===!1)throw Rt(s,Fy);return`:${Ny(s)}:`}var By="Integer";function $y(s){return s<-999999999999999||999999999999999<s}function $c(s){if($y(s))throw Rt(s,By);return s.toString()}function Gy(s){return`@${$c(s.getTime()/1e3)}`}function Gc(s,e){if(s<0)return-Gc(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return(r%2===0?r:r+1)/t}else return Math.round(s*t)/t}var Ky="Decimal";function Vy(s){let e=Gc(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Rt(s,Ky);let t=e.toString();return t.includes(".")?t:`${t}.0`}var Hy="String",qy=/[\x00-\x1f\x7f]+/;function Wy(s){if(qy.test(s))throw Rt(s,Hy);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yy(s){return s.description||s.toString().slice(7,-1)}var jy="Token";function xd(s){let e=Yy(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Rt(e,jy);return e}function co(s){switch(typeof s){case"number":if(!V(s))throw Rt(s,Ad);return Number.isInteger(s)?$c(s):Vy(s);case"string":return Wy(s);case"symbol":return xd(s);case"boolean":return My(s);case"object":if(s instanceof Date)return Gy(s);if(s instanceof Uint8Array)return Uy(s);if(s instanceof Jr)return xd(s);default:throw Rt(s,Ad)}}var zy="Key";function ho(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Rt(s,zy);return s}function sl(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${ho(e)}`:`;${ho(e)}=${co(t)}`).join("")}function Kc(s){return s instanceof Ct?`${co(s.value)}${sl(s.params)}`:co(s)}function Xy(s){return`(${s.value.map(Kc).join(" ")})${sl(s.params)}`}function Qy(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Rt(s,Py);let t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof Ct||(n=new Ct(n));let a=ho(r);return n.value===!0?a+=sl(n.params):(a+="=",Array.isArray(n.value)?a+=Xy(n):a+=Kc(n)),a}).join(`,${i}`)}function Vc(s,e){return Qy(s,e)}var St="CMCD-Object",Re="CMCD-Request",yi="CMCD-Session",Vt="CMCD-Status",Jy={br:St,ab:St,d:St,ot:St,tb:St,tpb:St,lb:St,tab:St,lab:St,url:St,pb:Re,bl:Re,tbl:Re,dl:Re,ltc:Re,mtp:Re,nor:Re,nrr:Re,rc:Re,sn:Re,sta:Re,su:Re,ttfb:Re,ttfbb:Re,ttlb:Re,cmsdd:Re,cmsds:Re,smrt:Re,df:Re,cs:Re,ts:Re,cid:yi,pr:yi,sf:yi,sid:yi,st:yi,v:yi,msd:yi,bs:Vt,bsd:Vt,cdn:Vt,rtp:Vt,bg:Vt,pt:Vt,ec:Vt,e:Vt},Zy={REQUEST:Re};function ev(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(r=>e[r]=t),e},{})}function tv(s,e){let t={};if(!s)return t;let i=Object.keys(s),r=e?ev(e):{};return i.reduce((n,a)=>{var o;let l=Jy[a]||r[a]||Zy.REQUEST,u=(o=n[l])!==null&&o!==void 0?o:n[l]={};return u[a]=s[a],n},t)}function iv(s){return["ot","sf","st","e","sta"].includes(s)}function sv(s){return typeof s=="number"?V(s):s!=null&&s!==""&&s!==!1}var Hc="event";function rv(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}var Pr=s=>Math.round(s),fo=(s,e)=>Array.isArray(s)?s.map(t=>fo(t,e)):s instanceof Ct&&typeof s.value=="string"?new Ct(fo(s.value,e),s.params):(e.baseUrl&&(s=rv(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Tr=s=>Pr(s/100)*100,nv=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Ct&&typeof s.value=="string"?t=new Ct([s]):typeof s=="string"&&(t=[s])),fo(t,e)},av={br:Pr,d:Pr,bl:Tr,dl:Tr,mtp:Tr,nor:nv,rtp:Tr,tb:Pr},qc="request",Wc="response",rl=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ov=["e"],lv=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function un(s){return lv.test(s)}function uv(s){return rl.includes(s)||ov.includes(s)||un(s)}var Yc=["d","dl","nor","ot","rtp","su"];function dv(s){return rl.includes(s)||Yc.includes(s)||un(s)}var cv=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function hv(s){return rl.includes(s)||Yc.includes(s)||cv.includes(s)||un(s)}var fv=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function mv(s){return fv.includes(s)||un(s)}var gv={[Wc]:hv,[Hc]:uv,[qc]:dv};function jc(s,e={}){let t={};if(s==null||typeof s!="object")return t;let i=e.version||s.v||1,r=e.reportingMode||qc,n=i===1?mv:gv[r],a=Object.keys(s).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let l=r===Wc||r===Hc;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");let u=Ee({},av,e.formatters),d={version:i,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(c=>{let h=s[c],f=u[c];if(typeof f=="function"&&(h=f(h,d)),c==="v"){if(i===1)return;h=i}c=="pr"&&h===1||(l&&c==="ts"&&!V(h)&&(h=Date.now()),sv(h)&&(iv(c)&&typeof h=="string"&&(h=new Jr(h)),t[c]=h))}),t}function pv(s,e={}){let t={};if(!s)return t;let i=jc(s,e),r=tv(i,e==null?void 0:e.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{let l=Vc(o,{whitespace:!1});return l&&(n[a]=l),n},t)}function yv(s,e,t){return Ee(s,pv(e,t))}var vv="CMCD";function Ev(s,e={}){return s?Vc(jc(s,e),{whitespace:!1}):""}function Tv(s,e={}){if(!s)return"";let t=Ev(s,e);return encodeURIComponent(t)}function _v(s,e={}){if(!s)return"";let t=Tv(s,e);return`${vv}=${t}`}var Rd=/CMCD=[^&#]+/;function Sv(s,e,t){let i=_v(e,t);if(!i)return s;if(Rd.test(s))return s.replace(Rd,i);let r=s.includes("?")?"&":"?";return`${s}${r}${i}`}var mo=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Xe.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{let{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),u={d:(a||n).duration*1e3,ot:l};(l===Xe.VIDEO||l===Xe.AUDIO||l==Xe.MUXED)&&(u.br=o.bitrate/1e3,u.tb=this.getTopBandwidth(l)/1e3,u.bl=this.getBufferLength(l));let d=a?this.getNextPart(a):this.getNextFrag(n);d!=null&&d.url&&d.url!==n.url&&(u.nor=d.url),this.apply(r,u)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let 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(){let 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,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:ky.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ee(t,this.createData());let i=t.ot===Xe.INIT||t.ot===Xe.VIDEO||t.ot===Xe.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),yv(e.headers,t,n)):e.url=Sv(e.url,t,n)}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let r=e.sn-i.startSN;return i.fragments[r+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return Xe.TIMED_TEXT;if(e.sn==="initSegment")return Xe.INIT;if(t==="audio")return Xe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Xe.VIDEO:Xe.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===Xe.AUDIO)i=r.audioTracks;else{let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}return i.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,i=e===Xe.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ie.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},bv=3e5,go=class extends Je{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==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){let{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){let{errorAction:i}=t;if((i==null?void 0:i.action)===Be.SendAlternateToPenaltyBox&&i.flags===Ze.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:u}=t.context;o&&r?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details===k.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${Se(n)} penalized: ${Se(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let 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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>bv&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,vc(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ae.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ae.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(d=>d.pathwayId===a))return;let u=this.getLevelsForPathway(o).map(d=>{let c=new Ae(d.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let m=zc(d.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new bi({attrs:c,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:m,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let g=1;g<d.audioGroups.length;g++)p.addGroupId("audio",`${d.audioGroups[g]}_clone_${a}`);if(d.subtitleGroups)for(let g=1;g<d.subtitleGroups.length;g++)p.addGroupId("text",`${d.subtitleGroups[g]}_clone_${a}`);return p});t.push(...u),Id(this.audioTracks,i,l,a),Id(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+d)}let n={responseType:"json",url:r.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},u={onSuccess:(d,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=d.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);let T={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(d,c,h,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(d.code===429){let p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){let g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(d,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Id(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=Ee({},a);return o.details=void 0,o.attrs=new Ae(o.attrs),o.url=o.attrs.URI=zc(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function zc(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a==null?void 0:a[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(u=>{u&&l.searchParams.set(u,n[u])}),l.href}var Zr=class s extends Je{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:i,initData:r}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=_s(this.config));let o=a.map(aa).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=Dr(a);if(i!=="sinf"||o!==xe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{let f=Ce(new Uint8Array(r)),m=Xo(JSON.parse(f).sinf),p=zd(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let u=Ge(l),{keyIdToKeySessionPromise:d,mediaKeySessions:c}=this,h=d[u];for(let f=0;f<c.length;f++){let m=c[f],p=m.decryptdata;if(!p.keyId)continue;let g=Ge(p.keyId);if(Hr(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(h=d[g],!h)continue;if(p.pssh)break;delete d[g],p.pssh=new Uint8Array(r),p.keyId=l,h=d[u]=h.then(()=>this.generateRequestWithPreferredKeySession(m,i,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${u} not encountered in playlist. Key-system sessions ${c.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(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),this.hls.on(y.DESTROYING,this.onDestroying,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),this.hls.off(y.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t==null?void 0:t[e];if(r)return r.licenseUrl;if(e===xe.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t==null?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=u=>{let d=u.shift();this.getMediaKeysPromise(d,r,n).then(c=>a({keySystem:d,mediaKeys:c})).catch(c=>{u.length?l(u):c instanceof We?o(c):o(new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return dc===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let n=_0(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Se(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(u=>{this.log(`Failed to obtain access to key-system "${e}": ${u}`)}),o.then(u=>{this.log(`Access for key-system "${u.keySystem}" obtained`);let d=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=u.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,d.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ge(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=_r(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ge(e.decryptdata.keyId||[])}
|
|
43
|
-
} (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>aa(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=aa(r);n?t(n):i(new Error(`Unable to find format for key-system "${r}"`))}).catch(i)})}selectKeySystemFormat(e){let 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){let t=_s(this.config),i=e.map(Dr).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=Av(e,t[i]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,i=_r(t),r=this.bannedKeyIds[i];if(r||this.getKeyStatus(t)==="internal-error"){let o=Ld(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[i];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:u})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,u).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:u,decryptdata:t}))))).then(l=>{let u="cenc",d=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,u,d,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof We){let l=ge({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let u=new We(l,o.message);this.handleError(u,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof We){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ge(i.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=_r(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=Dr(e.keyFormat),n=r?[r]:_s(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=_s(this.config)),e.length===0)throw new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Se({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let m=a.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=m.initData?m.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=_r(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let u=new Qo,d=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){u.emit("error",new Error("invalid state"));return}let{messageType:g,message:v}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(T=>{u.eventNames().length?u.emit("error",T):this.handleError(T)}):g==="license-release"?e.keySystem===xe.FAIRPLAY&&this.updateKeySession(e,Ga("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${g}"`)},c=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?u.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=Ld(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${o})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),g&&(u.eventNames().length?u.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}let g=this.getKeyStatuses(e);if(!Object.keys(g).some(_=>g[_]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${Se(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=g[o];if(T)c(T,e);else{var E;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(E=e.keyStatusTimeouts)[o]||(E[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let b=this.getKeyStatus(e.decryptdata);if(b&&b!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${b} from other session.`),c(b,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",c(T,e)},1e3)),this.log(`No status for keyId ${o} (${Se(g)}).`)}};Ye(e.mediaKeysSession,"message",d),Ye(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{u.on("error",p),u.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(u.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(u.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){let o=r;r=i,i=o}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===xe.PLAYREADY&&n.length===16){let o=Ge(n);t[o]=i,lc(n)}let a=Ge(n);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},u=t.certLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:ge({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,d,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new We({type:z.KEY_SYSTEM_ERROR,details:k.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(r=>{throw new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let d;for(let c=0,h=n.length;c<h;c++){var a,o;d=n[c];let f=(a=d.querySelector("name"))==null?void 0:a.textContent,m=(o=d.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=r.querySelector("Challenge"),u=l==null?void 0:l.textContent;if(!u)throw new Error("Cannot find <Challenge> in key message");return Ga(atob(u))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(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}`);let u=this.config.licenseResponseCallback;if(u)try{l=u.call(this.hls,o,a,e)}catch(d){this.error(d)}r(l)}else{let l=i.errorRetry,u=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new We({type:z.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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{let d=u-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:u})=>{e.keySystem==xe.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(l,u)),l.send(u)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,Ye(i,"encrypted",this.onMediaEncrypted),Ye(i,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(Qe(e,"encrypted",this.onMediaEncrypted),Qe(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Qi.clearKeyUriToKeyIdMap();let n=r.length;s.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ge((r==null?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(u=>self.clearTimeout(a[u]));let{drmSystemOptions:o}=this.config;return(b0(o)?new Promise((u,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(u).catch(d)}):Promise.resolve()).catch(u=>{this.log(`Could not remove session: ${u}`),this.hls&&this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${u}`)})}).then(()=>t.close()).catch(u=>{this.log(`Could not close session: ${u}`),this.hls&&this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${u}`)})})}return Promise.resolve()}};Zr.CDMCleanupPromise=void 0;function _r(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Ge(s.keyId)}function Av(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}var We=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}};function Ld(s,e){let t=s==="output-restricted",i=t?k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:k.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new We({type:z.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}var po=class{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),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,u=this.hls;if(u.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let d=u.currentLevel;u.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=d)&&(d=d-1,u.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:u.currentLevel}),u.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function Xc(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 Qc(s,e){let 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){pe.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r)}catch(r){pe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(s.mode=t)}function Hi(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function yo(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=Rv(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a])}r==="disabled"&&(s.mode=r)}function xv(s,e){if(e<=s[0].startTime)return 0;let t=s.length-1;if(e>s[t].endTime)return-1;let i=0,r=t,n;for(;i<=r;)if(n=Math.floor((r+i)/2),e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n;return s[i].startTime-e<e-s[r].startTime?i:r}function Rv(s,e,t){let i=[],r=xv(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){let o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function wr(s){let e=[];for(let t=0;t<s.length;t++){let i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}var vo=class extends Ns{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,i=wr(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{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(){let{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.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;wr(i.textTracks).forEach(a=>{Hi(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} 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){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=!1),a.forEach((d,c)=>{d.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let d=xt(o,a);if(d>-1)n=a[d];else{let c=xt(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,u),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||_i(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(Fs(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(Fs(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(no(r,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ae.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&_i(e,i))return i;let r=xt(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(i)return null;{let n=xt(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=wr(e.textTracks),i=this.currentTrack,r;if(i&&(r=t.filter(n=>no(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!V(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:u,url:d}=r;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:d});let c=this.switchParams(r.url,i==null?void 0:i.details,r.details);this.loadPlaylist(c)}};function Iv(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function As(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}var zi=.025,en=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function Lv(s,e,t){return`${s.identifier}-${t+1}-${As(e)}`}var Eo=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return ga(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=ga(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=V(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return ga(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<zi))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?en.Range:en.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Dv(this)}};function ga(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<zi)?e.start:e.start+e.duration}function Jc(s,e,t){let i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function pa(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function Dv(s){return`["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Vi(s){let e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var To=class{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,a),n.once(y.AUDIO_TRACK_LOADED,a),n.once(y.SUBTITLE_TRACK_LOADED,a),n.on(y.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,()=>{let d=this.bufferedEnd;this.reachedPlayout(d)&&(this._bufferedEosTime=d,n.trigger(y.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Jc(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=ie.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=ie.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,i){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,i){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Vi(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Dd=.033,_o=class extends Je{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=r[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let n=i[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let n=i[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if(((i=t[r].event)==null?void 0:i.identifier)===e)return r}return-1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let n=0;n<r;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},t),o=Object.keys(r),l=n?n.filter(u=>!o.includes(u.identifier)):[];a.length&&a.sort((u,d)=>{let c=u.cue.pre,h=u.cue.post,f=d.cue.pre,m=d.cue.post;if(c&&!f)return-1;if(f&&!c||h&&!m)return 1;if(m&&!h)return-1;if(!c&&!f&&!h&&!m){let p=u.startTime,g=d.startTime;if(p!==g)return p-g}return u.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=a,l.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(r,e);(i||t.length||(n==null?void 0:n.length)!==a.length||a.some((l,u)=>Math.abs(l.playout.start-n[u].playout.start)>.005||Math.abs(l.playout.end-n[u].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,i){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let u=this.eventMap[o];u?u.setDateRange(l):(u=new Eo(l,t),this.eventMap[o]=u,i===!1&&(u.appendInPlace=i)),r.push(u)}}return r}parseSchedule(e,t){let i=[],r=t.main.details,n=r.live?1/0:r.edge,a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,u=0;if(e.forEach((d,c)=>{let h=d.cue.pre,f=d.cue.post,m=e[c-1]||null,p=d.appendInPlace,g=f?n:d.startOffset,v=d.duration,T=d.timelineOccupancy===en.Range?v:0,E=d.resumptionOffset,_=(m==null?void 0:m.startTime)===g,b=g+d.cumulativeDuration,x=p?b+v:g+E;if(h||!f&&g<=0){let R=u;u+=T,d.timelineStart=b;let I=a;a+=v,i.push({event:d,start:b,end:x,playout:{start:I,end:a},integrated:{start:R,end:u}})}else if(g<=n){if(!_){let A=g-l;if(A>Dd){let L=l,P=u;u+=A;let O=a;a+=A;let N={previousEvent:e[c-1]||null,nextEvent:d,start:L,end:L+A,playout:{start:O,end:a},integrated:{start:P,end:u}};i.push(N)}else A>0&&m&&(m.cumulativeDuration+=A,i[i.length-1].end=g)}f&&(x=b),d.timelineStart=b;let R=u;u+=T;let I=a;a+=v,i.push({event:d,start:b,end:x,playout:{start:I,end:a},integrated:{start:R,end:u}})}else return;let S=d.resumeTime;f||S>n?l=n:l=S}),l<n){var o;let d=l,c=u,h=n-l;u+=h;let f=a;a+=h,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:d+h,playout:{start:f,end:a},integrated:{start:c,end:u}})}this.setDurations(n,a,u)}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let u=o.cue.pre,d=o.cue.post,c=u?0:d?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=Ai(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Dd&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=V(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>zi?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;let u=Ai(null,o.fragments,i);if(!u)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let d=a==="audio"?.175:0;return Math.abs(u.start-i)<zi+d||Math.abs(u.end-i)<zi+d?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${u.start}-${u.end} sn: ${u.sn} cc: ${u.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let u=o.error?0:o.duration||0;i+=u}r&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function mt(s){return`[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}var So=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i=e.assetListUrl,r;try{r=Jc(i,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,k.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(y.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},u=n.interstitialAssetListLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let g=h.data,v=g==null?void 0:g.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,k.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(y.ERROR,T);return}e.assetListResponse=g,this.hls.trigger(y.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p})},onError:(h,f,m,p)=>{let g=this.assignAssetListError(e,k.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(y.ERROR,g)},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,k.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(y.ERROR,p)}};return o.load(l,d,c),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,r,n,a){return e.error=i,{type:z.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}};function kd(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Sr(s,e){return`[${s}] Advancing timeline position to ${e}`}var bo=class extends Je{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(i);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let u=this.playingAsset;if(!u){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}let d=u.timelineStart,c=u.duration||0;if(a&&i<d||i>=d+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,u)}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(i>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],u=n.durations,d=i.map(p=>p.identifier),c=!!(o.length||d.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
44
|
-
Schedule: ${l.map(p=>mt(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),i.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let g=p.assetItem.timelineStart,v=p.timelineOffset-g;if(v)try{p.timelineOffset=g}catch(T){Math.abs(v)>zi&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:u,removedIds:d}),this.isInterstitial(a)&&d.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new So(e),this.schedule=new _o(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,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_UPDATED,this.onLevelUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,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_UPDATED,this.onLevelUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Qe(e,"play",this.onPlay),Qe(e,"pause",this.onPause),Qe(e,"seeking",this.onSeeking),Qe(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;Ye(i,"seeking",this.onSeeking),Ye(i,"timeupdate",this.onTimeupdate),Ye(i,"play",this.onPlay),Ye(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,m,p)=>{if(c){let g=c[h].start,v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==en.Point){let T=i(f);(T==null?void 0:T.interstitial)===v&&(g+=T.assetItem.startOffset+T[p])}}else{let T=m==="bufferedPos"?a():e[m];g+=T-c.start}return g}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(c),g=(m=e.schedule.items)==null?void 0:m[p];if(g){let v=g[h].start-g.start;return c+v}}return c},a=()=>{let c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);let g=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),T=(m=e.schedule.items)==null?void 0:m[v],E=e.getBufferingPlayer(),_=E==null?void 0:E.interstitial,b=_==null?void 0:_.appendInPlace,x=g&&e.itemsMatch(g,T);if(g&&(b||x)){let S=i(e.playingAsset),R=(S==null?void 0:S.media)||e.primaryMedia;if(R){let I=h==="primary"?R.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),A=c-I,L=(b?I:R.currentTime)+A;if(L>=0&&(!S||b||L<=S.duration)){R.currentTime=L;return}}}if(T){let S=c;if(h!=="primary"){let I=T[h].start,A=c-I;S=T.start+A}let R=!e.isInterstitial(T);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(R||T.event.appendInPlace)){let I=e.media||(b?E==null?void 0:E.media:null);I&&(I.currentTime=S)}else if(g){let I=e.findItemIndex(g);if(v>I){let L=e.schedule.findJumpRestrictedIndex(I+1,v);if(L>I){e.setSchedulePosition(L);return}}let A=0;if(R)e.timelinePos=S,e.checkBuffer();else{let L=T.event.assetList,P=c-(T[h]||T).start;for(let O=L.length;O--;){let N=L[O];if(N.duration&&P>=N.startOffset&&P<N.startOffset+N.duration){A=O;break}}}e.setSchedulePosition(v,A)}}},u=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},d={get bufferedEnd(){let c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let c=u(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=u(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=u();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=u())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=u())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return u()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return u()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){let c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{let c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(c);if(h.appendInPlace){let m=c.playout.start+c.event.duration;l(m+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!V(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Se(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,u=(i=this.detachedData)==null?void 0:i.mediaSource,d;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),d="Primary";else if(u){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),d=`${m}`):d="detached MediaSource"}else d="detached media";if(!n){if(u)n=this.detachedData,this.log(`using detachedData: MediaSource ${Se(n)}`);else if(!this.detachedData||a.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){let g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=c&&n?n:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){let n=this.hls.startPosition;if(this.log(Sr("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),n=pa(i,r);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,i){let r=pa(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Sr("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,n=i.getEvent(r);if(n){let a=i.findEventIndex(r),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&mt(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let d=a.event,c=this.playingAsset,h=c==null?void 0:c.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==d.assetList[t].identifier)){var l;let m=d.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${d.assetList.length} ${Vi(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:m,event:d,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${mt(a)}`),d.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:d,schedule:r.slice(0),scheduleIndex:e}),d.cue.once)){var u;this.updateSchedule();let m=(u=this.schedule)==null?void 0:u.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,i,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(d=>{let c=d.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let d=o.event;if(i===void 0){i=a.findAssetIndex(d,this.timelinePos);let m=pa(d,i-1);if(d.isAssetPastPlayoutLimit(m)||d.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(d,e,i);return}i=m}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(d,i);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${mt(o)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(y.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=d.assetList[i];if(!f){this.advanceAfterAssetEnded(d,e,i||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=d.assetList.length;this.warn(`asset ${i+1}/${m} player destroyed ${d}`),h=this.createAssetPlayer(d,f,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&kd(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&kd(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${mt(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Sr("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${mt(e)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ie.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Sr("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((i=r.mainForwardBufferInfo)==null?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=ge(ge({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ge(ge({},this.altSelection),{},{audio:i});return}let n=ge(ge({},r),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ge(ge({},this.altSelection),{},{subtitles:i});return}let n=ge(ge({},r),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){let i=$u(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=$u(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var i;let a=this.schedule.findEventIndex(n.identifier),o=(i=this.schedule.items)==null?void 0:i[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let i=e.end+.25,r=ie.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${mt(e)} (was ${mt(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let r=ie.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}updateBufferedPos(e,t,i){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var u;let d=this.findItemIndex(n),c=Math.min(d+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(u=h.event)!=null&&u.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){let f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>d&&l>o)this.bufferedToItem(h);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:n}=i;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${mt(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,c)=>{let h=this.getAssetPlayer(d.identifier);h&&(c===u&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(u=>u.pauseBuffering());this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){let i=e.event,r=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(r||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var o;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let u,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){let h=d-l;h>0&&(u=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${u?` live-start: ${d} start-offset: ${u}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let c=this.assetListLoader.loadAssetList(e,u);c&&(e.assetListLoader=c)}else if(!a&&r){for(let u=t;u<r;u++){let d=e.assetList[u],c=this.getAssetPlayerQueueIndex(d.identifier);(c===-1||this.playerQueue[c].destroyed)&&!d.error&&this.createAssetPlayer(e,d,u)}let l=e.assetList[t];if(l){let u=this.getAssetPlayer(l.identifier);return u&&u.loadSource(),u}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,n,a){let o={parentIdentifier:e.identifier,identifier:Lv(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let r=this.hls,n=r.userConfig,a=n.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=Ee({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let l=r.audioTracks[r.audioTrack],u=r.subtitleTracks[r.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){let _=this.timelinePos-t.timelineStart;if(_>1){let b=t.duration;b&&_<b&&(d=_)}}let c=t.identifier,h=ge(ge({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:u||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=Ee({},f,{contentId:As(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let m=new To(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[i]=t;let p=!0,g=_=>{if(_.live){var b;let R=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:z.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:R},A=((b=this.schedule)==null?void 0:b.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,A,i,R.message);return}let x=_.edge-_.fragmentStart,S=t.duration;(p||S===null||x>S)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${S} > ${x}`),t.duration=x,this.updateSchedule())};m.on(y.LEVEL_UPDATED,(_,{details:b})=>g(b)),m.on(y.LEVEL_PTS_UPDATED,(_,{details:b})=>g(b)),m.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(_,b)=>{let x=this.getAssetPlayer(c);if(x&&b.tracks){x.off(y.BUFFER_CODECS,v),x.tracks=b.tracks;let S=this.primaryMedia;this.bufferingAsset===x.assetItem&&S&&!x.media&&this.bufferAssetPlayer(x,S)}};m.on(y.BUFFER_CODECS,v);let T=()=>{var _;let b=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${b}`),!b||!this.schedule)return;let x=this.schedule.findEventIndex(e.identifier),S=(_=this.schedule.items)==null?void 0:_[x];this.isInterstitial(S)&&this.advanceAssetBuffering(S,t)};m.on(y.BUFFERED_TO_END,T);let E=_=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,_)};return m.once(y.MEDIA_ENDED,E(i)),m.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(y.ERROR,(_,b)=>{if(!this.schedule)return;let x=this.getAssetPlayer(c);if(b.details===k.BUFFER_STALLED_ERROR){if(x!=null&&x.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),m.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let b=new Error(`Asset player destroyed unexpectedly ${c}`),x={fatal:!0,type:z.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Vi(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let r=this.playerQueue[i];this.log(`clear ${r} toSegment: ${t&&mt(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,u=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!d||d.identifier!==l)&&(d&&(this.clearAssetPlayer(d.identifier,i[r]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${u} ${Vi(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(i=this.schedule.items)==null?void 0:i[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let u=this.getBufferingPlayer();if(u===e)return;let d=n.appendInPlace;if(d&&(u==null?void 0:u.interstitial.appendInPlace)===!1)return;let c=(u==null?void 0:u.tracks)||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Gd(c,e.tracks)){let h=new Error(`Asset ${Vi(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),f={fatal:!0,type:z.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,u=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+u} in ${o} ${e} (media.currentTime: ${r})`),l&&(u/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){let d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,n)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,r,n){if(e.details===k.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Vi(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),u=this.playerQueue[l]||null,d=this.schedule.items,c=Ee({},e,{fatal:!1,errorAction:Wi(!0),asset:a,assetListIndex:r,event:t,schedule:d,scheduleIndex:i,player:u});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,r=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${mt(i)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let a=this.updateItem(i,r);this.itemsMatch(i,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var i,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,u=n.duration,d=0;o.forEach((p,g)=>{let v=parseFloat(p.DURATION);this.createAsset(n,g,d,l+d,v,p.URI),d+=v}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${u}) ${n}`);let c=this.waitingItem,h=(c==null?void 0:c.event.identifier)===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(a),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){let p=n.assetList[0];if(p){let g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;g&&v&&this.bufferAssetPlayer(g,v)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case k.ASSET_LIST_PARSING_ERROR:case k.ASSET_LIST_LOAD_ERROR:case k.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case k.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Pd=500,Ao=class extends Ps{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",W.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,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)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.LEVEL_LOADED,this.onLevelLoaded,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)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(Pd),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,success:r}=t;if(this.fragContextChanged(i)||(Le(i)&&(this.fragPrevious=i),this.state=C.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=i.start;for(let u=0;u<n.length;u++)if(o>=n[u].start&&o<=n[u].end){a=n[u];break}let l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,W.SUBTITLE)}}onError(e,t){let i=t.frag;(i==null?void 0:i.type)===W.SUBTITLE&&(t.details===k.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Uc(this.levels,t)){this.levels=t.map(i=>new bi(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new bi(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==C.STOPPED&&this.setInterval(Pd)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;let c=this.mainDetails;if(!c){this.startFragRequested=!1;return}let h=c.fragments[0];if(!l.details)a.hasProgramDateTime&&c.hasProgramDateTime?(Wr(a,c),u=a.fragmentStart):h&&(u=h.start,Va(a,u));else{var d;u=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details),u===0&&h&&(u=h.start,Va(a,u))}c&&!this.startFragRequested&&this.setStartPosition(c,u)}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(Ai(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&Yi(r.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,zo(r.method)).catch(o=>{throw n.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){let{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,n=this.getLoadPosition(),a=ie.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,u=i.details,d=this.hls.maxBufferLength+u.levelTargetDuration;if(l>d)return;let c=u.fragments,h=c.length,f=u.edge,m=null,p=this.fragPrevious;if(o<f){let T=r.maxFragLookUpTolerance,E=o>f-T?0:T;m=Ai(p,c,Math.max(c[0].start,o),E),!m&&p&&p.start<c[0].start&&(m=c[0])}else m=c[h-1];if(m=this.filterReplacedPrimary(m,i.details),!m)return;let g=m.sn-u.startSN,v=c[g-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===Oe.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===Oe.NOT_LOADED){let T=this.mapToInitFragWhenRequired(m);T&&this.loadFragment(T,i,o)}}}loadFragment(e,t,i){Le(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new xo(this.tracksBuffered[this.currentTrackId]||[])}},xo=class{constructor(e){this.buffered=void 0;let t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},kv={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},Zc=s=>String.fromCharCode(kv[s]||s),gt=15,Pt=100,Pv={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},wv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Cv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ov={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Mv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Ro=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;pe.log(`${this.time} [${e}] ${i}`)}}},vi=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},tn=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Io=class{constructor(){this.uchar=" ",this.penState=new tn}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},Lo=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new tn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Pt;t++)this.chars.push(new Io);this.logger=e}equals(e){for(let t=0;t<Pt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Pt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Pt;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Pt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Pt)}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=Zc(e);if(this.pos>=Pt){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<Pt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<Pt;i++){let r=this.chars[i].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},xs=class{constructor(e){this.rows=[],this.currRow=gt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<gt;t++)this.rows.push(new Lo(e));this.logger=e}reset(){for(let e=0;e<gt;e++)this.rows[e].clear();this.currRow=gt-1}equals(e){let t=!0;for(let i=0;i<gt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<gt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<gt;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Se(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<gt;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let u=0;u<this.nrRollUpRows;u++)this.rows[t-this.nrRollUpRows+u+1].copy(a.rows[n+u])}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Se(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());let 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;let t=[],i="",r=-1;for(let n=0;n<gt;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
45
|
-
`)),i}getTextAndFormat(){return this.rows}},sn=class{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 xs(i),this.nonDisplayedMemory=new xs(i),this.lastOutputScreen=new xs(i),this.currRollUpRow=this.displayedMemory.rows[gt-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[gt-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;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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"){let 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){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+Se(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let 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))}},rn=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Fv(),this.logger=void 0;let r=this.logger=new Ro;this.channels=[null,new sn(e,t,r),new sn(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let r=t[i]&127,n=t[i+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+vi([t[i],t[i+1]])+"] -> ("+vi([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(Nv(r,n,l)){br(null,null,l),this.logger.log(3,()=>"Repeated command ("+vi([r,n])+") is dropped");continue}br(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else br(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let d=this.currentChannel;d&&d>0?this.channels[d].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+vi([r,n])+" orig: "+vi([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return!1;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!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;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+vi([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?i=a===1?Pv[e]:Cv[e]:i=a===1?wv[e]:Ov[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Zc(a)+"' in channel "+i),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+vi(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=Mv[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}br(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function br(s,e,t){t.a=s,t.b=e}function Nv(s,e,t){return t.a===s&&t.b===e}function Fv(){return{a:null,b:null}}var nl=function(){if(qr!=null&&qr.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let u=l.toLowerCase();return~o.indexOf(u)?u:!1}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let u=1;for(;u<arguments.length;u++){let d=arguments[u];for(let c in d)o[c]=d[c]}return o}function a(o,l,u){let d=this,c={enumerable:!0};d.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=u,v=null,T="",E=!0,_="auto",b="start",x=50,S="middle",R=50,I="middle";Object.defineProperty(d,"id",n({},c,{get:function(){return h},set:function(A){h=""+A}})),Object.defineProperty(d,"pauseOnExit",n({},c,{get:function(){return f},set:function(A){f=!!A}})),Object.defineProperty(d,"startTime",n({},c,{get:function(){return m},set:function(A){if(typeof A!="number")throw new TypeError("Start time must be set to a number.");m=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},c,{get:function(){return p},set:function(A){if(typeof A!="number")throw new TypeError("End time must be set to a number.");p=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},c,{get:function(){return g},set:function(A){g=""+A,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},c,{get:function(){return v},set:function(A){v=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},c,{get:function(){return T},set:function(A){let L=i(A);if(L===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},c,{get:function(){return E},set:function(A){E=!!A,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},c,{get:function(){return _},set:function(A){if(typeof A!="number"&&A!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");_=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},c,{get:function(){return b},set:function(A){let L=r(A);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},c,{get:function(){return x},set:function(A){if(A<0||A>100)throw new Error("Position must be between 0 and 100.");x=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},c,{get:function(){return S},set:function(A){let L=r(A);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");S=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},c,{get:function(){return R},set:function(A){if(A<0||A>100)throw new Error("Size must be between 0 and 100.");R=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},c,{get:function(){return I},set:function(A){let L=r(A);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");I=L,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Do=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function eh(s){function e(i,r,n,a){return(i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let 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}var ko=class{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 r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function th(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var Po=new nl(0,0,""),Ar=Po.align==="middle"?"middle":"center";function Uv(s,e,t){let i=s;function r(){let o=eh(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let u=new ko;th(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){u.set(h,t[p].region);break}break;case"vertical":u.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),u.integer(h,m[0]),u.percent(h,m[0])&&u.set("snapToLines",!1),u.alt(h,m[0],["auto"]),m.length===2&&u.alt("lineAlign",m[1],["start",Ar,"end"]);break;case"position":m=f.split(","),u.percent(h,m[0]),m.length===2&&u.alt("positionAlign",m[1],["start",Ar,"end","line-left","line-right","auto"]);break;case"size":u.percent(h,f);break;case"align":u.alt(h,f,["start",Ar,"end","left","right"]);break}},/:/,/\s/),l.region=u.get("region",null),l.vertical=u.get("vertical","");let d=u.get("line","auto");d==="auto"&&Po.line===-1&&(d=-1),l.line=d,l.lineAlign=u.get("lineAlign","start"),l.snapToLines=u.get("snapToLines",!0),l.size=u.get("size",100),l.align=u.get("align",Ar);let c=u.get("position","auto");c==="auto"&&Po.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=r(),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=r(),a(),n(s,e)}function ih(s){return s.replace(/<br(?: \/)?>/gi,`
|
|
46
|
-
`)}var
|
|
40
|
+
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],r=i==null?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},yc=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nf="HlsJsTrackRemovedError",bE=.25,AE=.001,Wo=class extends Error{constructor(e){super(e),this.name=nf}},Yo=class extends at{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{let{media:r,mediaSource:n}=this;i&&this.log("Media source opened"),!(!r||!n)&&(Se(n,"sourceopen",this._onMediaSourceOpen),Se(r,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let i=this.media.error,{appendError:r,appendErrors:n}=this,a=!1;!r&&i&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${Tc(a,i)}`);this.warn(o),this.hls.trigger(E.ERROR,Re({fatal:a},r,{type:Q.MEDIA_ERROR,details:k.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:r}=this;i!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${i})`)},this._onMediaError=()=>{let{media:i}=this;if(i){var r,n;this.log(`Media error (code: ${(r=i.error)==null?void 0:r.code}): ${(n=i.error)==null?void 0:n.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=z0(pi(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return r&&!this.sourceBufferCount&&r.mediaSource===t?Re(i,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=Re({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=pi(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Ec(i),RE(i,o),i.load()}catch{i.src=o}else i.src=o}be(i,"emptied",this._onMediaEmptied),be(i,"error",this._onMediaError),this.appendSource&&be(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),be(e,"sourceopen",this._onMediaSourceOpen),be(e,"sourceended",this._onMediaSourceEnded),be(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(be(e,"startstreaming",this._onStartStreaming),be(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
41
|
+
required tracks: ${ke(i,(l,u)=>l==="initSegment"?void 0:u)};
|
|
42
|
+
transfer tracks: ${ke(r,(l,u)=>l==="initSegment"?void 0:u)}}`),!Jc(r,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,u=this.details,d=Math.max(l,(u==null?void 0:u.fragments[0].start)||0);if(d-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${l}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,n.forEach(l=>{let u=l,d=r[u];if(d){let c=d.buffer;if(c){let h=this.fragmentTracker,f=d.id;if(h.hasFragments(f)||h.hasParts(f)){let p=oe.getBuffered(c);h.detectEvictedFragments(u,p,f,null,null,!0)}let g=Qa(u),m=[u,c];this.sourceBuffers[g]=m,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(u),this.trackSourceBuffer(u,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let u=l.length;u--;)o&&l[u].abort(),n.removeSourceBuffer(l[u]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Se(n,"sourceopen",this._onMediaSourceOpen),Se(n,"sourceended",this._onMediaSourceEnded),Se(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Se(n,"startstreaming",this._onStartStreaming),Se(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(Se(r,"emptied",this._onMediaEmptied),Se(r,"error",this._onMediaError),Se(r,"seeking",this._onStartStreaming),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&Ec(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Qa(e)]=[null,null];let t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new qo(this.tracks)}onBufferCodecs(e,t){var i;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var u,d;let c=t[l],{id:h,codec:f,levelCodec:g,container:m,metadata:p,supplemental:y}=c,T=r[l],v=(u=this.transferData)==null||(u=u.tracks)==null?void 0:u[l],_=v!=null&&v.buffer?v:T,S=(_==null?void 0:_.pendingCodec)||(_==null?void 0:_.codec),A=_==null?void 0:_.levelCodec;T||(T=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:y,container:m,levelCodec:g,metadata:p,id:h});let b=sn(S,A),x=b==null?void 0:b.replace(yc,"$1"),L=sn(f,g),R=(d=L)==null?void 0:d.replace(yc,"$1");L&&b&&x!==R&&(l.slice(0,5)==="audio"&&(L=cn(L,this.appendSource)),this.log(`switching codec ${S} to ${L}`),L!==(T.pendingCodec||T.codec)&&(T.pendingCodec=L),T.container=m,this.appendChangeType(l,m,L))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,r=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,j.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>r||oe.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,r)||((l=this.fragmentTracker.getAppendedFrag(r,j.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:u,offset:d}=t,c=u.buffering[n],h=Ne(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,f=null,g=!1,{sn:m,cc:p}=o,y=self.performance.now();c.start=y;let T=o.stats.buffering,v=l?l.stats.buffering:null;T.start===0&&(T.start=y),(v==null?void 0:v.start)===0&&(v.start=y);let _=i.audio,S=!1;n==="audio"&&(_==null?void 0:_.container)==="audio/mpeg"&&(S=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);let A=i.video,b=A==null?void 0:A.buffer;if(b&&m!=="initSegment"&&d!==void 0){let R=_==null?void 0:_.buffer,I=l||o;if(n==="audio"&&a!=="main"&&!(A.ending||A.ended)&&R&&oe.getBuffered(R).length){let w=I.start+I.duration*.05,B=oe.getBuffered(b),U=this.currentOp("video");!B.length&&!U?this.blockAudio(I):!oe.isBuffered(b,w)&&this.lastVideoAppendEnd<w&&this.blockAudio(I)}else if(n==="video"){let P=I.end,w=this.lastVideoAppendEnd-P;this.lastVideoAppendEnd=P,w<0||w>I.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let x=(l||o).start,L={label:`append-${n}`,execute:()=>{var R;c.executeStart=self.performance.now();let I=(R=this.tracks[n])==null?void 0:R.buffer;I&&(h&&(f=oe.timeRangesToArray(oe.getBuffered(I)),g=Sc(Ja(f,o),o)),S?this.updateTimestampOffset(I,x,.1,n,m,p):d!==void 0&&H(d)&&this.updateTimestampOffset(I,d,1e-6,n,m,p)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);let R=self.performance.now();c.executeEnd=c.end=R,T.first===0&&(T.first=R),(v==null?void 0:v.first)===0&&(v.first=R);let I={};if(this.sourceBuffers.forEach(([P,w])=>{P&&(I[P]=oe.getBuffered(w))}),h){let P=this.getFragmentAppendProgress(o),w=I[n];if(w&&f){let B=oe.timeRangesToArray(w),U=Ja(B,o);P.progressed||(P.progressed=U-Ja(f,o)>AE);let C=g&&Sc(U,o);P.fullyBuffered[n]=(P.fullyBuffered[n]===void 0||P.fullyBuffered[n])&&C}}this.hls.trigger(E.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:u,parent:a,timeRanges:I})},onError:R=>{var I;this.clearBufferAppendTimeoutId(this.tracks[n]);let P=R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R;if(P&&!this._quotaEvictionPending[n]){let C=this.getBackBufferEvictionTarget(n,r.byteLength,o.type);if(C>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${m} - evicting back buffer to ${C.toFixed(3)}s and retrying`);let N=this.getFlushOp(n,0,C),F=this.getClearEvictionPendingOp(n);this.insertNext([N,L,F],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${m} - no back buffer available to evict`)}h&&(this.getFragmentAppendProgress(o).errored=!0);let w={type:Q.MEDIA_ERROR,parent:a,details:k.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:u,error:R,err:R,fatal:!1},B=(I=this.media)==null?void 0:I.error;if(R.name===nf&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))w.errorAction=Hs(!0);else{var U;P&&(w.details=k.BUFFER_FULL_ERROR);let C=++this.appendErrors[n],N=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${C}/${N+1} times to append segment in "${n}" sourceBuffer with error: ${R.message}`),C>=N&&(w.fatal=!P);let F=(U=this.mediaSource)==null?void 0:U.readyState;(F==="ended"||F==="closed"||B)&&(this.warn(`MediaSource readyState "${F}" during SourceBuffer${Tc(w.fatal,B)}`),w.details=k.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=w,this.hls.trigger(E.ERROR,w),P&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${p} offset: ${d} bytes: ${r.byteLength}`),this.append(L,n,this.isPending(this.tracks[n]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var r;let n=(r=this.tracks[e])==null?void 0:r.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${n?Sn(oe.getBuffered(n)):"(detached)"}`),this.hls.trigger(E.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r),this.hls.trigger(E.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:n}=t;(!i||i==="audio")&&this.unblockAudio(),i?this.append(this.getFlushOp(i,r,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:i,part:r,chunkMeta:n}=t,a=[],o=r?r.elementaryStreams:i.elementaryStreams;o[Le.AUDIOVIDEO]?a.push("audiovideo"):(o[Le.AUDIO]&&a.push("audio"),o[Le.VIDEO]&&a.push("video"));let l=()=>{let u=self.performance.now();i.stats.buffering.end=u,r&&(r.stats.buffering.end=u);let d=r?r.stats:i.stats;this.checkAppendProgress(i,r,n,a),this.hls&&(this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:r,stats:d,id:i.type,chunkMeta:n}),!r&&i.gap&&d.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${d.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${r?`part: ${r.index} of `:""}sn: ${i.sn}`),this.blockBuffers(l,a).catch(u=>{this.warn(`Fragment buffered callback ${u.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:u}=this,d=(r=this.appendError)==null?void 0:r.sourceBufferName;Object.keys(l).forEach(c=>{l[c]&&(u[c]=0,c===d&&(this.appendError=void 0),c==="audio"||c==="video"?(u.audiovideo=0,d==="audiovideo"&&(this.appendError=void 0)):(u.audio=0,u.video=0,d!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let r=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if((a==null?void 0:a.readyState)!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===k.BUFFER_APPEND_ERROR&&t.frag){var i;let r=(i=t.errorAction)==null?void 0:i.nextAutoLevel;H(r)&&r!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,i,t):0}getFragmentAppendProgress(e){var t;let i=_c(e),r=this.fragmentAppendProgress[i];return((t=r)==null?void 0:t.stats)!==e.stats&&(r={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=r),r}checkAppendProgress(e,t,i,r){if(t||!Ne(e)||e.gap||i.iframe||i.partial)return;let n=_c(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];let o=e.stats.buffering;if(o.start&&!o.first)return;let l=(a==null?void 0:a.stats)===e.stats?a:void 0;if(l!=null&&l.errored)return;let u=r.length>0&&r.every(f=>(l==null?void 0:l.fullyBuffered[f])===!0);if(l!=null&&l.progressed||u){delete this.appendsWithoutProgress[n];return}if(!l&&r.length===0)return;let d=(this.appendsWithoutProgress[n]||0)+1,c=this.hls;d>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=d,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${d} time${d>1?"s":""} without buffered range growth`),c.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:d,error:new Error(`Fragment append did not increase buffered coverage (${d})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,r){let{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=n.config,u=o.currentTime,d=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let c=-1/0;if(H(t)&&t>=0){let h=Math.max(t,d);c=Math.floor(u/d)*d-h}if(i){let h=this.getLoopBackBufferFlushEnd(i,r!=null?r:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(u,d,c),H(e)&&e>0){let h=Math.max(l.maxBufferLength,e),f=Math.max(h,d),g=Math.floor(u/d)*d+f;this.flushFrontBuffer(u,d,g)}}getLoopBackBufferFlushEnd(e,t){var i;let{media:r}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(r!=null&&r.loop)||!t||e.level<=t.level)return 0;let{video:n,audiovideo:a}=e.elementaryStreams;if(n!=null&&n.partial||a!=null&&a.partial)return 0;let o=this.getEarliestElementaryStreamStart(e)-bE;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){let{audio:t,video:i,audiovideo:r}=e.elementaryStreams,n=e.start;return r?n=Math.min(n,r.startDTS):(t&&(n=Math.min(n,t.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let u=oe.getBuffered(n);if(u.length>0&&i>u.start(0)){var a,o,l;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i});let d=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(d!=null&&d.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:r})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=oe.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),u=a.end(o-1);if(i>l||e>=l&&e<=u)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let u=Math.max(0,t.fragmentStart),d=Math.max(u,r);return{duration:1/0,start:u,end:d}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return H(n)?{duration:n}:null;let a=this.media.duration,o=H(i.duration)?i.duration:0;return r>o&&r>a||!H(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;!r||!this.media||r.readyState!=="open"||(r.duration!==e&&(H(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ke(i)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),u=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${u})${this.currentOp(a)?" Queued":""} ${ke(o)}`);try{let d=i.addSourceBuffer(u),c=Qa(a),h=[a,d];t[c]=h,o.buffer=d}catch(d){var r;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:u,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&(t==="video"||t==="audiovideo")&&Zs(i,"video")&&(r=$v(r,i));let n=sn(r,e.levelCodec);return n?t.slice(0,5)==="audio"?cn(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${Sn(o)}`),this.hls.trigger(E.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let r=this.currentOp(e);if(!r)return;if(r.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;let r=(i=this.mediaSource)==null?void 0:i.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${r}`);this.error(`${n.message}`,t),this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,i,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!r||!n||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=H(r.duration)?r.duration:1/0,u=H(n.duration)?n.duration:1/0,d=Math.max(0,t);if(d>=u){var c;(c=this.currentOp(e))==null||c.onComplete(),this.shiftAndExecuteNext(e);return}let h=Math.min(i,l,u);if(h>d&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),o.remove(d,h);else throw new Error(`Cannot remove ${h<=d?`invalid range (${d} >= ${h}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let i=this.tracks[t],r=i==null?void 0:i.buffer;if(!r)throw new Wo(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let n=this.calculateAppendTimeoutTime(r);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,n),n)}r.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let r=this.currentOp(e);r&&r.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Dh;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(this.media===null)return i;let r=oe.bufferInfo(e,this.media.currentTime,0);return r.len?(i=Math.max(r.len*1e3,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;let r=(i=this.tracks[t])==null?void 0:i.buffer;!r||r.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),be(n,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(r=>{Se(i,r.event,r.listener)}),t.listeners.length=0)}};function Ec(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function RE(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function Qa(s){return s==="audio"?1:0}function Tc(s,e){return`${s?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function _c(s){return`${s.type}_${s.sn}_${s.level}`}function Ja(s,e){let{start:t,end:i}=e,r=0;for(let n=0;n<s.length;n++){let a=s[n];if(a.start>=i)break;let o=Math.max(t,a.start),l=Math.min(i,a.end);l>o&&(r+=l-o)}return r}function Sc(s,e){return e.duration-s<=.05}var dr=class s{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;e&&(e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){let i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(H(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){let e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.observer||(this.clientRect=null),s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var i;let r=(i=t[0])==null?void 0:i.contentRect;r&&(this.clientRect=r,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let 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)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,i)}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;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},ct=class jo{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof jo?i:new jo(i))),this.value=e,this.params=t}},xE="Dict";function IE(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function LE(s,e,t,i){return new Error(`failed to ${s} "${IE(e)}" as ${t}`,{cause:i})}var bc="Bare Item",DE="Boolean",kE="Byte Sequence",PE="Decimal",CE="Integer";function wE(s){return s<-999999999999999||999999999999999<s}var OE="String",ME=/[\x00-\x1f\x7f]+/,af=class{constructor(s){this.description=s}},NE="Token",FE="Key";function qt(s,e,t){return LE("serialize",s,e,t)}function BE(s){if(typeof s!="boolean")throw qt(s,DE);return s?"?1":"?0"}function UE(s){if(ArrayBuffer.isView(s)===!1)throw qt(s,kE);return`:${X0(s)}:`}function of(s){if(wE(s))throw qt(s,CE);return s.toString()}function $E(s){return`@${of(s.getTime()/1e3)}`}function GE(s){let e=Zc(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw qt(s,PE);let t=e.toString();return t.includes(".")?t:`${t}.0`}function KE(s){if(ME.test(s))throw qt(s,OE);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function VE(s){return s.description||s.toString().slice(7,-1)}function Ac(s){let e=VE(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw qt(e,NE);return e}function zo(s){switch(typeof s){case"number":if(!H(s))throw qt(s,bc);return Number.isInteger(s)?of(s):GE(s);case"string":return KE(s);case"symbol":return Ac(s);case"boolean":return BE(s);case"object":if(s instanceof Date)return $E(s);if(s instanceof Uint8Array)return UE(s);if(s instanceof af)return Ac(s);default:throw qt(s,bc)}}function Xo(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw qt(s,FE);return s}function zl(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${Xo(e)}`:`;${Xo(e)}=${zo(t)}`).join("")}function lf(s){return s instanceof ct?`${zo(s.value)}${zl(s.params)}`:zo(s)}function HE(s){return`(${s.value.map(lf).join(" ")})${zl(s.params)}`}function qE(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw qt(s,xE);let t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ct||(n=new ct(n));let a=Xo(r);return n.value===!0?a+=zl(n.params):(a+="=",Array.isArray(n.value)?a+=HE(n):a+=lf(n)),a}).join(`,${i}`)}function uf(s,e){return qE(s,e)}var WE=["url"],YE=["version","eventTargets","sid","transmissionMode"],jE=["customData","headers"],Rc=s=>s instanceof ct?new ct(Math.round(s.value),s.params):Math.round(s),Za=s=>Array.isArray(s)?s.map(Rc):Rc(s),Qo=(s,e)=>Array.isArray(s)?s.map(t=>Qo(t,e)):s instanceof ct&&typeof s.value=="string"?new ct(Qo(s.value,e),s.params):(e.baseUrl&&(s=ev(s,Z0(e.baseUrl))),e.version===1?encodeURIComponent(s):s),xc=s=>s instanceof ct?new ct(Math.round(s.value/100)*100,s.params):Math.round(s/100)*100,zr=s=>Array.isArray(s)?s.map(xc):xc(s),zE=(s,e)=>{let t=s;return e.version>=2&&(s instanceof ct&&typeof s.value=="string"?t=new ct([s]):typeof s=="string"&&(t=[s])),Qo(t,e)},XE={br:Za,d:Za,bl:zr,dl:zr,mtp:zr,nor:zE,rtp:zr,tb:Za},cr=2,df="bc",QE="ps",cf="pr",JE="e",Ic="t",ZE="c",hf="b",Xl="rr",ff="ce",Xr={BITRATE_CHANGE:df,ERROR:JE,RESPONSE_RECEIVED:Xl,CUSTOM_EVENT:ff},gf=new Map([[QE,"sta"],[cf,"pr"],[ZE,"cid"],[hf,"bg"],[df,"br"]]),Ql="event",Jl="request",mf=["cen","e","h","ts"],pf=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],eT=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Zl(s){return eT.test(s)}var tT=new Set(pf);function vf(s){return tT.has(s)||Zl(s)}var yf=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],iT=new Set(yf);function Ef(s){return iT.has(s)}var sT=new Set(mf);function rT(s){return vf(s)||Ef(s)||sT.has(s)}var nT=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),qn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],aT=new Set(qn);function oT(s){return aT.has(s)||Zl(s)}var lT=new Set(["ot","sf","st","e","sta"]);function uT(s){return lT.has(s)}function dT(s){return typeof s=="number"?H(s):s!=null&&s!==""&&s!==!1}var cT={[Ql]:rT,[Jl]:vf};function Tf(s,e){if(Array.isArray(s)){let t;return e&&(t=s.find(i=>{var r;return((r=i.params)==null?void 0:r.ot)===e})),t||(t=s[0]),Tf(t)}return s instanceof ct?s.value:s}function hT(s){let e={};for(let[i,r]of Object.entries(s)){if(r==null){e[i]=r;continue}if(i==="nor"){let n=(Array.isArray(r)?r:[r])[0];if(n instanceof ct){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else nT.has(i)?e[i]=Tf(r,s.ot):e[i]=r}return e}function _f(s,e={}){let t={};if(s==null||typeof s!="object")return t;let i=e.version||s.v||cr,r=e.reportingMode||Jl,n=i===1?hT(s):s,a=i===1?oT:cT[r],o=Object.keys(n).filter(a);n.e&&n.e!==Xl&&(o=o.filter(f=>!Ef(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let u=r===Ql;if(u){let f=n.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&n.cen!=null&&f===ff&&o.push("cen");let g=f?gf.get(f):void 0;g&&n[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;i>1&&!o.includes("v")&&o.push("v");let d={version:i,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(let f of o){var c,h;let g=n[f],m=(c=(h=e.formatters)==null?void 0:h[f])!=null?c:XE[f];if(typeof m=="function"&&(g=m(g,d)),f==="v"){if(i===1)continue;g=i}if(f==="pr"&&g===1&&!(u&&n.e===cf))continue;u&&f==="ts"&&!H(g)&&(g=Date.now());let p=u&&g===!1&&f==="bg"&&n.e===hf;!dT(g)&&!p||(uT(f)&&typeof g=="string"&&(g=new af(g)),t[f]=g)}return t}var Jt="CMCD-Object",dt="CMCD-Request",ls="CMCD-Session",kt="CMCD-Status",fT={REQUEST:dt},gT={ab:Jt,br:Jt,d:Jt,lab:Jt,lb:Jt,ot:Jt,tab:Jt,tb:Jt,tpb:Jt,bl:dt,cs:dt,dfa:dt,dl:dt,ltc:dt,mtp:dt,nor:dt,nrr:dt,pb:dt,sn:dt,sta:dt,su:dt,tbl:dt,cid:ls,msd:ls,sf:ls,sid:ls,st:ls,v:ls,bg:kt,bs:kt,bsa:kt,bsd:kt,bsda:kt,cdn:kt,ec:kt,nr:kt,pr:kt,pt:kt,rtp:kt};function mT(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])==null||i.forEach(r=>e[r]=t),e},{})}function pT(s,e){let t={};if(!s)return t;let i=Object.keys(s),r=e?mT(e):{};for(let a of i){var n;let o=gT[a]||r[a]||fT.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=s[a]}return t}function vT(s,e){let t={},i=pT(s,e);for(let[r,n]of Object.entries(i)){let a=uf(n,{whitespace:!1});a&&(t[r]=a)}return t}var Lc="CMCD";function Sf(s){return uf(s,{whitespace:!1})}function yT(s,e={}){return s?Sf(_f(s,e)):""}var ET=30,Jo=[...qn,...pf,...yf,...mf].filter((s,e,t)=>t.indexOf(s)===e),TT="application/cmcd",_T=1,Ze={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Pt={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},eu="query",bf="headers";function Dc(s,e,t){var i;let r=new Set((i=e.enabledKeys)!=null?i:[]);return{version:e.version||cr,reportingMode:s,filter:n=>r.has(n),baseUrl:t}}function ST(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++){let i=s[t],r=e[t];if(i===r)continue;if(typeof i=="number"||typeof r=="number"||i.value!==r.value)return!1;let n=i.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&n&&a&&n[o]!==a[l])return!1}return!0}var bT=Object.is,AT=s=>s,Af=Array.from(gf,([s,e])=>e==="br"?{event:s,field:e,equal:(t,i)=>t===void 0||i===void 0?t===i:ST(t,i),snapshot:t=>t.slice()}:{event:s,field:e,equal:bT,snapshot:AT}),RT=new Map(Af.map(s=>[s.event,s]));function xT(s){let{url:e}=s,t=Kn(s,WE);return fetch(e,t)}function IT(s){let{version:e=cr,eventTargets:t=[],sid:i=eh(),transmissionMode:r=eu}=s,n=Kn(s,YE);return J(J({},n),{},{version:e,transmissionMode:r,sid:i,eventTargets:t.reduce((a,o)=>{var l,u,d;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||cr,enabledKeys:((u=o.enabledKeys)==null?void 0:u.slice())||[],url:o.url,events:o.events.slice(),interval:(d=o.interval)!=null?d:ET,batchSize:o.batchSize||1}),a},[])})}var LT=class{constructor(s,e=xT){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=IT(s),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let i of this.config.eventTargets)this.eventTargets.set(i,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((s,e)=>{if(this.disarmInterval(s),e.interval===0||!e.events.includes(Ic))return;let t=()=>{this.recordTargetEvent(s,e,Ic),this.processEventTargets()};s.intervalId=setInterval(t,e.interval*1e3),t()})}stop(s=!1){s&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(s){s.sid&&s.sid!==this.data.sid&&this.resetSession(),s.msd&&!isNaN(s.msd)&&(this.msd=s.msd),this.data=J(J(J({},this.data),s),{},{msd:void 0});for(let e of Af)e.field in s&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(s,e={}){let t=RT.get(s);if(t){let i=t.field,r=e[i];r!==void 0&&Re(this.data,{[i]:r});let n=this.data[i];if(n===void 0||t.equal(n,this.lastEmitted[i]))return;Re(this.lastEmitted,{[i]:t.snapshot(n)})}this.eventTargets.forEach((i,r)=>{this.recordTargetEvent(i,r,s,e)}),this.processEventTargets()}recordTargetEvent(s,e,t,i={}){var r;if(!e.events.includes(t))return;let n=J(J(J({},this.data),i),{},{e:t,ts:(r=i.ts)!=null?r:Date.now(),sn:s.sn++});!isNaN(this.msd)&&!s.msdSent&&(n.msd=this.msd,s.msdSent=!0),s.queue.push(n)}recordResponseReceived(s,e={}){var t,i,r;let{request:n}=s,a=(t=e.url)!=null?t:n==null?void 0:n.url;if(!a)return;let o=new URL(a);o.searchParams.delete(Lc);let l={url:o.toString(),rc:s.status},u=s.resourceTiming;u&&(u.startTime!=null&&(l.ts=Math.round(this.timeOrigin+u.startTime),u.responseStart!=null&&(l.ttfb=Math.round(u.responseStart-u.startTime))),u.duration!=null&&(l.ttlb=Math.round(u.duration)));let d=(i=(r=n.customData)==null?void 0:r.cmcd)!=null?i:{};this.recordEvent(Xl,J(J(J({},d),l),e))}applyRequestReport(s){var e;return(e=this.createRequestReport(s))!=null?e:s}isRequestReportingEnabled(){var s;return!!((s=this.config.enabledKeys)!=null&&s.length)}createRequestReport(s,e){var t;let{customData:i={},headers:r={}}=s,n=Kn(s,jE),a=J(J({},n),{},{headers:J({},r),customData:J(J({},i),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=J(J(J({},this.data),e),{},{sn:this.requestTarget.sn++}),u=Dc(Jl,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let d=a.customData.cmcd=_f(l,u);switch(this.config.transmissionMode){case eu:let c=Sf(d);c&&(o.searchParams.set(Lc,c),a.url=o.toString());break;case bf:Re(a.headers,vT(d,u.customHeaderMap));break}return a}processEventTargets(s=!1){let e=!1;this.eventTargets.forEach((t,i)=>{let{queue:r}=t;if(!r.length||r.length<i.batchSize&&!s)return;let n=s?r.length:i.batchSize,a=r.splice(0,n);this.sendEventReport(i,a).catch(()=>{t.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(s,e){let t=Dc(Ql,s),{status:i}=await this.requester({url:s.url,method:"POST",headers:{"Content-Type":TT},body:e.map(r=>yT(r,t)).join(`
|
|
43
|
+
`)+`
|
|
44
|
+
`});if(i===410)this.disposeEventTarget(s);else if(i===429||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(s){clearInterval(s.intervalId),s.intervalId=void 0}disposeEventTarget(s){let e=this.eventTargets.get(s);e&&(this.disarmInterval(e),this.eventTargets.delete(s))}resetSession(){this.eventTargets.forEach(s=>s.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},DT={HLS:"h"},eo={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function kT(s,e){return new ct(s,e)}new Set(qn);new Set(Jo);var PT=["includeKeys"];function kc(s){return Object.keys(s).every(Zl)}var Zo=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Pt.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Pt.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Pt.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Pt.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Pt.SEEKING)},this.onSeeked=()=>{var r;this.initialized&&(r=this.media)!=null&&r.paused&&this.setPlayerState(Pt.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Ze.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{let{frag:o,part:l}=r,u=this.hls.levels[o.level],d=this.getObjectType(o,u),c={d:(l||o).duration*1e3,ot:d};if(d===Ze.VIDEO||d===Ze.AUDIO||d===Ze.MUXED||d==null&&(o.type==="main"||o.type==="audio")){var n;let f=u.bitrate/1e3;c.br=[f];let{cmcd:g}=this.config,m=(n=g==null?void 0:g.rtpSafetyFactor)!=null?n:5;if(c.rtp=Math.round(f*m/100)*100,d===Ze.MUXED||d==null&&o.type==="main"){let T=this.getTopBandwidth()/1e3;H(T)&&(c.tb=[T]);let v=this.getLowestBandwidth()/1e3;H(v)&&(c.lb=[v])}let p=this.getBufferLength(o);if(H(p)){var a;c.bl=[p];let T=((a=this.media)==null?void 0:a.playbackRate)||1;c.dl=Math.round(p/T/100)*100}this.playheadLevel&&(c.pb=[this.playheadLevel.bitrate/1e3]);let y=this.hls.maxAutoLevel;if(y>=0){let T=this.hls.levels[y];T&&(c.tpb=[T.bitrate/1e3])}}let h=l?this.getNextPart(l):this.getNextFrag(o);h!=null&&h.url&&h.url!==o.url&&(h.byteRange.length>0?c.nor=[kT(h.url,{r:`${h.byteRange[0]}-${h.byteRange[1]}`})]:c.nor=[h.url]),this.apply(r,c)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(r,n,a)=>{var o;let{cmcd:l}=this.config,u=l==null||(o=l.eventTargets)==null?void 0:o.some(d=>{var c;return(c=d.events)==null?void 0:c.includes(Xr.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!u))try{this.reporter.recordResponseReceived({request:{url:r},status:n.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(d){this.hls.logger.warn("Could not record fragment response CMCD data.",d)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:i}=this.config;if(i==null)return;let r=i.version||_T;if(this.reporter=new LT({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:r,transmissionMode:i.useHeaders===!0?bf:eu,enabledKeys:(e=i.includeKeys)!=null?e:[...r>=cr?Jo:qn],eventTargets:((t=i.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=Kn(n,PT);return J(J({},o),{},{enabledKeys:a!=null?a:Jo})})},i.loader),this.reporter.update({sf:DT.HLS,sta:this.playerState}),i.reporterCallback){let n=this.reporter,a={updateCustomData:o=>{kc(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{kc(l)&&n.recordEvent(Xr.CUSTOM_EVENT,J({cen:o},l))}};i.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(E.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(E.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(E.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(E.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){let i=this.media=t.media;this.setPlayerState(this.media.autoplay?Pt.STARTING:Pt.PRELOADING),be(i,"waiting",this.onWaiting),be(i,"play",this.onPlay),be(i,"playing",this.onPlaying),be(i,"pause",this.onPause),be(i,"seeking",this.onSeeking),be(i,"seeked",this.onSeeked),be(i,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(Se(e,"waiting",this.onWaiting),Se(e,"play",this.onPlay),Se(e,"playing",this.onPlaying),Se(e,"pause",this.onPause),Se(e,"seeking",this.onSeeking),Se(e,"seeked",this.onSeeked),Se(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Pt.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Pt.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Pt.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Xr.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;let r={br:[t.bitrate/1e3]},n=(i=t.details)==null?void 0:i.fragments[0];n&&(r.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Xr.BITRATE_CHANGE,r)}onLevelSwitched(e,t){let i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?eo.LOW_LATENCY:eo.LIVE:eo.VOD}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(i=this.media)==null?void 0:i.playbackRate,st:this.getStreamType()});let r=t.ot===Ze.INIT||t.ot===Ze.VIDEO||t.ot===Ze.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let r=e.sn-i.startSN;return i.fragments[r+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){let{type:i}=e;if(i==="subtitle")return Ze.TIMED_TEXT;if(e.sn==="initSegment")return Ze.INIT;if(i==="audio")return Ze.AUDIO;if(i==="main"){if(e.hasStreams){let r=e.elementaryStreams;if(r.audiovideo)return Ze.MUXED;if(r.video)return Ze.VIDEO;if(r.audio)return Ze.AUDIO}if(t){let{audioCodec:r,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(r&&n)return Ze.MUXED;if(r)return Ze.AUDIO}if(n)return Ze.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,i=t.maxAutoLevel,r=i>-1?i+1:t.levels.length;return t.levels.slice(0,r).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,i=t.maxAutoLevel,r=i>-1?i+1:t.levels.length;return t.levels.slice(0,r).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),H(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;let i=e||t;return i?i.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let i=this.getEventBufferLength();H(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,r=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new r(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);let{onSuccess:u}=l;this.loader.load(a,o,J(J({},l),{},{onSuccess:(d,c,h,f)=>{u(d,c,h,f),i(a.url,d,c)}}))}}}},CT=3e5,el=class extends at{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==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){let{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){let{errorAction:i}=t;if((i==null?void 0:i.action)===Qe.SendAlternateToPenaltyBox&&i.flags&Xe.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:u}=t.context;o&&r?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a,!i.resolved&&(t.details!==k.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${ke(n)} penalized: ${ke(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let 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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>CT&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,$h(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});let u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===de.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===de.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(d=>d.pathwayId===a))return;let u=this.getLevelsForPathway(o).map(d=>{let c=new Oe(d.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let g=Rf(d.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new qi({attrs:c,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let p=1;p<d.audioGroups.length;p++)m.addGroupId("audio",`${d.audioGroups[p]}_clone_${a}`);if(d.subtitleGroups)for(let p=1;p<d.subtitleGroups.length;p++)m.addGroupId("text",`${d.subtitleGroups[p]}_clone_${a}`);return m});t.push(...u),Pc(this.audioTracks,i,l,a),Pc(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;gi(r,"_HLS_pathway",this.pathwayId),gi(r,"_HLS_throughput",""+d)}let n={type:de.STEERING_MANIFEST,responseType:"json",url:r.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},u={onSuccess:(d,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let g=d.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;let{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":y}=g;if(m)try{this.uri=new self.URL(m,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);let T={steeringManifest:g,url:r.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,T),y&&this.updatePathwayPriority(y)},onError:(d,c,h,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){let m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){let p=m.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,g)},onTimeout:(d,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Pc(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=Re({},a);return o.details=void 0,o.attrs=new Oe(o.attrs),o.url=o.attrs.URI=Rf(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function Rf(s,e,t,i){if(e){let{[t]:o}=i;if(o){let l=o[e];if(l)return l}}let{HOST:r,PARAMS:n}=i,a=new self.URL(s);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(o=>{o&&gi(a,o,n[o])}),a.href}var tl=class{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new ql,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();let e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}},gt=class 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}},wn=class s extends at{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{let{initDataType:i,initData:r}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.log(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Fs(this.config));let o=a.map(qa).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=Wr(a),u=this.activeLevelKeys();if(l===we.FAIRPLAY&&i==="sinf")try{let g=Ot(new Uint8Array(r)),m=Ul(JSON.parse(g).sinf),p=ch(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}else if(l===we.PLAYREADY)o=Hl(new Uint8Array(r));else if(l===we.WIDEVINE){let g=mh(r).filter(m=>m.systemId===Ch.WIDEVINE);if(g.length){var d;let m=g[0];o=(d=m.kids)!=null&&d.length?m.kids[0]:null}}let c;if(o){let g=We(o);for(let m=0;m<u.length;m++){let p=u[m];if(p.keyId&&(En(o,p.keyId)||p.uri.replace(/-/g,"").indexOf(g)!==-1)){p.pssh||(p.scheme=i,p.pssh=new Uint8Array(r),p.keyId=o,Wi.setKeyIdForUri(p.uri,o)),c=this.getSessionForKey(p,"encrypted-event-key-match");break}}}if(!c){if(u.length){var h,f;return(h=u[0]).scheme||(h.scheme=i),(f=u[0]).pssh||(f.pssh=new Uint8Array(r)),this.getSessionForKey(u[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${We(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return c}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=u=>{let d=u.shift();this.getMediaKeysPromise(d,r,n).then(c=>a({keySystem:d,mediaKeys:c})).catch(c=>{u.length?l(u):c instanceof gt?o(c):o(new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return wh===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let n=yy(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ke(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(u=>{this.log(`Failed to obtain access to key-system "${e}": ${u}`)}),o.then(u=>{this.throwIfDestroyed(),this.log(`Access for key-system "${u.keySystem}" obtained`);let d=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=u.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,d.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,r){let{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${We(i.keyId||[])} keyUri: ${i.uri} for "${r}"`;for(let u=0;u<n.length;u++){let d=n[u];if(!d.initialized&&d.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),d}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:r},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${We(t.keyId||[])}
|
|
45
|
+
} (data length: ${i.byteLength})`),r.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>qa(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let i=qa(t);if(!i)throw new Error(`Unable to find format for key-system "${t}"`);return i})}selectKeySystemFormat(e){let 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){let t=Fs(this.config),i=e.map(Wr).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!Ne(e)||!Ne(a)||e.sn<a.sn)||!i&&r==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=Wr(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Fs(this.config);if(r.length)return this.getKeySystemAccess(r)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=to(e,t[i]);if(r)return r}}loadKey(e){let t=e.decryptdata,i=this.getKeyStatus(t);if(i==="internal-error"){let o=Cc(i,t);return o.data.frag=e,this.error(`${o.message} (${We(t.keyId||[])})`),Promise.reject(o)}let r=e.type,n=this.activeKeys,a=n[r];a&&!t.matches(a.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(a),delete n[r]),n[r]||(n[r]=e);for(let o=this.mediaKeySessions.length;o--;){let l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[We(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){let r=this.getSessionForKey(e,t);return r.catch(n=>this.handleError(n,i)),r.then(n=>e)}getSessionForKey(e,t){let i=this.findContextForKey(e);if(i!==void 0)return Promise.resolve(i);let r=e.uri,n=this.sessionSetupByUri[r],a;n===void 0?a=this.resolveSessionForKey(e,t):a=n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[r]=a;let o=()=>{this.sessionSetupByUri[r]===a&&delete this.sessionSetupByUri[r]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let i=t.length;i--;){let r=t[i];if(to(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:r})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let a=this.mediaKeySessions[n];if(to(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(i,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,r,e,t))).then(n=>{this.throwIfDestroyed();let a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,a,o,t)})})}getUsableKeyPromise(e,t,i){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${i} keyId: ${MT(t)} format: "${t.keyFormat}" URI: ${t.uri})`),r.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof gt){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${We(i.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=Wr(e.keyFormat),i=t?[t]:Fs(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=Fs(this.config)),e.length===0)throw new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ke({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(i=>i.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}filterInitData(e,t,i,r,n){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let u=o.call(this.hls,i,r,Re({},e,{decryptdata:t,reason:n}),n);if(!u)throw new Error("Invalid response from configured generateRequest filter");t.scheme=u.initDataType?u.initDataType:"cenc";let d=u.initData?u.initData:null;return t.pssh=d?new Uint8Array(d):null,u}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}return{initDataType:i,initData:r}}generateRequestWithPreferredKeySession(e,t,i,r,n){let a=this.getUsableKeyPromise(e,t,n);if(a)return a;let o=this.filterInitData(e,t,i,r,n);if(o&&(r=o.initData?o.initData:null,i=o.initDataType),r===null)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e));let l=t.uri,u=new tl;e.keyRequests[l]=u;let d=h=>{let f=e.mediaKeysSession;if(!f){let p=new Error("invalid state");u.errored=p;return}let{messageType:g,message:m}=h;u.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(p=>{u.errored=p,u.hasListeners||this.handleError(p),this.removeSession(e)}):g==="license-release"?e.keySystem===we.FAIRPLAY&&this.updateKeySession(e,t,Lo("acknowledged")).then(()=>this.removeSession(e)).catch(p=>this.handleError(p)):this.warn(`unhandled media key message type "${g}"`)};return u.onmessage=d,be(e.mediaKeysSession,"message",d),this.generateRequest(e,t,i,r,n,!1)}generateRequest(e,t,i,r,n,a){if(a){let f=this.filterInitData(e,t,i,r,n);f&&(r=f.initData?f.initData:r,i=f.initDataType)}let o=t.uri,l=e.keyRequests[o],u=We(t.keyId||[]),d=f=>{let g;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=Cc(f,t):f==="expired"?g=new Error(`key expired (keyId: ${u})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${u})`),g&&(l.errored=g,l.hasListeners||this.handleError(g))},c=f=>{if(!e.mediaKeysSession){let S=new Error("invalid state");l.errored=S;return}let m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(S=>m[S]!=="status-pending"))return;let y=this.activeLevelKeys();for(let S=0;S<y.length;S++){let A=We(y[S].keyId||[]);if(m[A]==="expired"){var T;this.log(`Expired key ${ke(m)} in key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}"`),this.renewKeySession(t,e).catch(b=>this.handleError(b));break}}let v=m[u];if(v)d(v);else{var _;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(_=e.keyStatusTimeouts)[u]||(_[u]=self.setTimeout(()=>{var A;if(!e.mediaKeysSession)return;let b=this.getKeyStatus(t);if(b&&b!=="status-pending"){var x;return this.log(`No status for keyId ${u} in key-session "${(x=e.mediaKeysSession)==null?void 0:x.sessionId}". Using session key-status ${b} from other session.`),d(b)}this.log(`key status for ${u} in key-session "${(A=e.mediaKeysSession)==null?void 0:A.sessionId}" timed out after 1000ms`),v="internal-error",d(v)},1e3)),this.log(`No status for keyId ${u} (${ke(m)}).`)}};l.onkeystatuseschange=c,be(e.mediaKeysSession,"keystatuseschange",c);let h=l.useable;return this.log(`Generating key-session request for "${n}" keyId: ${u} URI: ${o} (init data type: ${i} length: ${r.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,r).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${u} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>h).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let m=(g=f.data)==null?void 0:g.details;return(m===k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===k.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(p=>e.keyStatuses[p]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){let t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((r,n)=>{if(typeof n=="string"&&typeof r=="object"){let l=n;n=r,r=l}let a="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===we.PLAYREADY&&a.length===16){let l=We(a);t[l]=r,kh(a)}let o=We(a);this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${i}"`),t[o]=r}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=OT(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:de.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},u=t.certLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,g,m)=>{a(h.data)},onError:(h,f,g,m)=>{o(new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:J({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,g)=>{o(new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,g)=>{o(new Error("aborted"))}};r.load(l,d,c)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(r=>this.updateKeySession(e,t,new Uint8Array(r)).catch(n=>{throw new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){let i=Ot(new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let d;for(let c=0,h=n.length;c<h;c++){var a,o;d=n[c];let f=(a=d.querySelector("name"))==null?void 0:a.textContent,g=(o=d.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let l=r.querySelector("Challenge"),u=l==null?void 0:l.textContent;if(!u)throw new Error("Cannot find <Challenge> in key message");return Lo(atob(u))}setupLicenseXHR(e,t,i,r,n){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,J(J({},i),{},{decryptdata:r}),n))).catch(o=>{if(!i.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,J(J({},i),{},{decryptdata:r}),n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t,i){return new Promise((r,n)=>{let a=wT(e.keySystem,this.config);if(!a)return n(new Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return n(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);let l=this.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(u.readyState===4)if(u.status===200){o.requestErrors=[];let d=u.response;this.log(`License received ${d instanceof ArrayBuffer?d.byteLength:d}`);let c=this.config.licenseResponseCallback;if(c)try{d=c.call(this.hls,u,a,J(J({},e),{},{decryptdata:t}))}catch(h){this.error(h)}r(d)}else{let d=l.errorRetry,c=d?d.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>c||u.status>=400&&u.status<500)n(new gt({type:Q.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:a,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${a}). Status: ${u.status} (${u.statusText})`));else{let h=c-o.requestErrors.length;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t,i).then(r,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,this.setupLicenseXHR(u,a,e,t,i).then(({xhr:d,licenseChallenge:c})=>{e.keySystem==we.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(d,c)),d.send(c)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,be(i,"encrypted",this.onMediaEncrypted),be(i,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(Se(e,"encrypted",this.onMediaEncrypted),Se(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Wi.clearKeyUriToKeyIdMap();let n=r.length;s.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{let l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:r}=e;r&&Object.keys(r).forEach(o=>self.clearTimeout(r[o]));let{drmSystemOptions:n}=this.config;return(Ty(n)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};wn.CDMCleanupPromise=void 0;function wT(s,e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t==null?void 0:t[s];if(r)return r.licenseUrl;if(s===we.WIDEVINE&&i)return i}function OT(s,e){let{drmSystems:t}=e,i=t==null?void 0:t[s];if(i)return i.serverCertificateUrl}function MT(s){if(s.keyFormat===et.FAIRPLAY)return s.uri;if(s.keyId===null)throw new Error("keyId is null");return We(s.keyId)}function to(s,e){let t=s.keyId,i=e.mediaKeysSession;if(t&&i){let r=e.mediaKeysSession.keyStatuses;if(r.size)return r.has(t)?r.get(t):e.keyStatuses[We(t)]}}function Cc(s,e){let t=s==="output-restricted",i=t?k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:k.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new gt({type:Q.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}var il=class{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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,u=this.hls;if(u.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let d=u.currentLevel;u.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=d)&&(d=d-1,u.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:u.currentLevel}),u.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},tu=function(){if(Tn!=null&&Tn.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let u=l.toLowerCase();return~o.indexOf(u)?u:!1}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let u=1;for(;u<arguments.length;u++){let d=arguments[u];for(let c in d)o[c]=d[c]}return o}function a(o,l,u){let d=this,c={enumerable:!0};d.hasBeenReset=!1;let h="",f=!1,g=o,m=l,p=u,y=null,T="",v=!0,_="auto",S="start",A=50,b="middle",x=50,L="middle";Object.defineProperty(d,"id",n({},c,{get:function(){return h},set:function(R){h=""+R}})),Object.defineProperty(d,"pauseOnExit",n({},c,{get:function(){return f},set:function(R){f=!!R}})),Object.defineProperty(d,"startTime",n({},c,{get:function(){return g},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");g=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},c,{get:function(){return m},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");m=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},c,{get:function(){return p},set:function(R){p=""+R,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},c,{get:function(){return y},set:function(R){y=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},c,{get:function(){return T},set:function(R){let I=i(R);if(I===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},c,{get:function(){return v},set:function(R){v=!!R,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},c,{get:function(){return _},set:function(R){if(typeof R!="number"&&R!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");_=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},c,{get:function(){return S},set:function(R){let I=r(R);if(!I)throw new SyntaxError("An invalid or illegal string was specified.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},c,{get:function(){return A},set:function(R){if(R<0||R>100)throw new Error("Position must be between 0 and 100.");A=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},c,{get:function(){return b},set:function(R){let I=r(R);if(!I)throw new SyntaxError("An invalid or illegal string was specified.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},c,{get:function(){return x},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");x=R,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},c,{get:function(){return L},set:function(R){let I=r(R);if(!I)throw new SyntaxError("An invalid or illegal string was specified.");L=I,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),sl=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function xf(s){function e(i,r,n,a){return(i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let 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}var rl=class{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 r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function If(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var nl=new tu(0,0,""),Qr=nl.align==="middle"?"middle":"center";function NT(s,e,t){let i=s;function r(){let o=xf(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let u=new rl;If(o,function(h,f){let g;switch(h){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){u.set(h,t[m].region);break}break;case"vertical":u.alt(h,f,["rl","lr"]);break;case"line":g=f.split(","),u.integer(h,g[0]),u.percent(h,g[0])&&u.set("snapToLines",!1),u.alt(h,g[0],["auto"]),g.length===2&&u.alt("lineAlign",g[1],["start",Qr,"end"]);break;case"position":g=f.split(","),u.percent(h,g[0]),g.length===2&&u.alt("positionAlign",g[1],["start",Qr,"end","line-left","line-right","auto"]);break;case"size":u.percent(h,f);break;case"align":u.alt(h,f,["start",Qr,"end","left","right"]);break}},/:/,/\s/),l.region=u.get("region",null),l.vertical=u.get("vertical","");let d=u.get("line","auto");d==="auto"&&nl.line===-1&&(d=-1),l.line=d,l.lineAlign=u.get("lineAlign","start"),l.snapToLines=u.get("snapToLines",!0),l.size=u.get("size",100),l.align=u.get("align",Qr);let c=u.get("position","auto");c==="auto"&&nl.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=r(),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=r(),a(),n(s,e)}function Lf(s){return s.replace(/<br(?: \/)?>/gi,`
|
|
46
|
+
`)}var al=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new sl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=Lf(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
|
|
47
47
|
`;)++a;let o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
|
|
48
|
-
`&&++a,t.buffer=n.slice(a),o}function r(n){
|
|
48
|
+
`&&++a,t.buffer=n.slice(a),o}function r(n){If(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case"HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new tu(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{NT(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||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+=`
|
|
49
49
|
`),t.cue.text+=n}continue;case"BADCUE":n||(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(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
50
50
|
|
|
51
|
-
`,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}},
|
|
51
|
+
`,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}};function Ws(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}var FT=/\r\n|\n\r|\n|\r/g,wc="Missing initPTS for VTT ",BT=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!H(t)||!H(i)||!H(r)||!H(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*r,t+=60*60*1e3*n,t};function iu(s,e,t){return Ws(s.toString())+Ws(e.toString())+Ws(t)}function UT(s,e,t,i,r,n,a){let o=new al,l=pt(new Uint8Array(s)).trim().replace(FT,`
|
|
52
52
|
`).split(`
|
|
53
|
-
`),u=[],d=e?
|
|
54
|
-
`)}),o.flush()}var
|
|
55
|
-
`:(n=i.childNodes)!=null&&n.length?nh(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function qv(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let u=Ta(e,i,l)||Ta(s,i,l)||Ta(r,i,l);return u&&(o[l]=u),o},{})}function Ta(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Od(s){return new Error(`Could not parse ttml timestamp ${s}`)}function _a(s,e){if(!s)return null;let t=eh(s);return t===null&&(sh.test(s)?t=Wv(s,e):rh.test(s)&&(t=Yv(s,e))),t}function Wv(s,e){let t=sh.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 Yv(s,e){let t=rh.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}var qi=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Co=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Nd(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(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(){let{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.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new qi(this,"textTrack1"),t=new qi(this,"textTrack2"),i=new qi(this,"textTrack3"),r=new qi(this,"textTrack4");this.cea608Parser1=new rn(1,e,t),this.cea608Parser2=new rn(3,i,r)}addCues(e,t,i,r,n){let a=!1;for(let o=n.length;o--;){let l=n[o],u=jv(l[0],l[1],t,i);if(u>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r)}else{let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;i===W.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,l):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let n=i.textTracks[r];if(Md(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,Hi(i[e]),Xc(i[e],r);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{Hi(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Nd(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Hi(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===va);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Uc(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?wr(a.textTracks):null;if(this.tracks.forEach((l,u)=>{let d;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&Md(o[h],l)){c=o[h],o[h]=null;break}c&&(d=c)}if(d)Hi(d);else{let c=ah(l);d=this.createTextTrack(c,l.name,l.lang),d&&(d.mode="disabled")}d&&this.textTracks.push(d)}),o!=null&&o.length){let l=o.filter(u=>u!==null).map(u=>u.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===W.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=t.frag,d=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=d}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===W.SUBTITLE)if(r.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let 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===va?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;wd(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{i.logger.log(`Failed to parse IMSC1: ${r}`),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,u=(t=i.initSegment)!=null&&t.data?ot(i.initSegment.data,new Uint8Array(r)).buffer:r;Kv(u,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,d=>{this._appendCues(d,i.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},d=>{let c=d.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(i,r),l.logger.log(`Failed to parse VTT cue: ${d}`),!(c&&o>i.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:d})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||wd(t,this.initPTS[e.cc],()=>{i.textCodec=va,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Qc(r,n))}else{let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===W.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(!(i.type===W.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let d=3&a;(d===0||d===1)&&(t[d].push(o),t[d].push(l))}}return t}};function ah(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function Md(s,e){return!!s&&s.kind===ah(e)&&no(e,s)}function jv(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Nd(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var zv=/\s/,Xv={newCue(s,e,t,i){let r=[],n,a,o,l,u,d=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=!0,l=0,u="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)zv.test(n.chars[p].uchar)&&o?l++:(u+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=ih(u.trim()),m=al(e,t,f);s!=null&&(c=s.cues)!=null&&c.getCueById(m)||(a=new d(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>Qc(s,h))),r}};function Qv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Jv=/(\d+)-(\d+)\/(\d+)/,nn=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||iE,this.controller=new self.AbortController,this.stats=new Rs}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=Zv(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&V(l)?l:u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(Ms(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},u-(f-r.loading.start)),!c.ok){let{status:p,statusText:g}=c;throw new Oo(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=tE(c.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&V(t.highWaterMark)?this.loadProgressively(c,r,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=c[o];p&&(r.loaded=r.total=p);let g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!V(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.details:null,r)})}getCacheAge(){let e=null;if(this.response){let 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,r=0,n){let a=new Yr,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let d=u.value,c=d.length;return t.loaded+=c,c<r||a.dataLength?(a.push(d),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,d.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function Zv(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ee({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function eE(s){let e=Jv.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function tE(s){let e=s.get("Content-Range");if(e){let i=eE(e);if(V(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function iE(s,e){return new self.Request(s.url,e)}var Oo=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},sE=/^age:\s*[\d.]+\s*$/im,an=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Rs,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let 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(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[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=n&&V(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let u=t.status,d=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){let m=d!=null?d:t.response;if(m!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(i,e,m,t);let v={url:t.responseURL,data:m,code:u};(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let c=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:u};if(Gr(c,h,!1,f))this.retry(c);else{var l;pe.error(`${u} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:u,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Gr(e,t,!0))this.retry(e);else{var i;pe.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=jo(e,i.retry),i.retry++,pe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0: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){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&sE.test(this.loader.getAllResponseHeaders())){let 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}},rE={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},nE=ge(ge({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:an,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Pa,bufferController:uo,capLevelController:Us,errorController:Ca,fpsController:po,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:dc,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:rE},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},aE()),{},{subtitleStreamController:Ao,subtitleTrackController:vo,timelineController:Co,audioStreamController:ro,audioTrackController:ao,emeController:Zr,cmcdController:mo,contentSteeringController:go,interstitialsController:bo});function aE(){return{cueHandler:Xv,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 oE(s,e,t){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"');let i=Mo(s),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,u=[];n.forEach(d=>{let c=`${a}Loading${d}`,h=e[c];if(h!==void 0&&l){u.push(c);let f=i[o].default;switch(e[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),u.length&&t.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${o}": ${Se(e[o])}`)}),ge(ge({},i),e)}function Mo(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Mo):Object.keys(s).reduce((e,t)=>(e[t]=Mo(s[t]),e),{}):s}function lE(s,e){let t=s.loader;t!==nn&&t!==an?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Qv()&&(s.loader=nn,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Cr=2,uE=.1,dE=.05,cE=100,No=class extends Kr{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(cE),this.mediaSource=t.mediaSource;let i=this.media=t.media;Ye(i,"playing",this.onMediaPlaying),Ye(i,"waiting",this.onMediaWaiting),Ye(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(Qe(i,"playing",this.onMediaPlaying),Qe(i,"waiting",this.onMediaWaiting),Qe(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,u=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!ie.getBuffered(a).length){this.nudgeRetry=0;return}let c=ie.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let x=Fd(this.hls.inFlightFragments,e),S=c.len>Cr,R=!h||x||h-e>Cr&&!f.getPartialFragment(e);if(S||R)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;let S=Math.max(h,c.start||0)-e,I=!!(m!=null&&m.live)?m.targetduration*2:Cr,A=xr(e,f);if(S>0&&(S<=I||A)){a.paused||this._trySkipBufferHole(A);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&g-v<p)T=this.stalled=v;else{this.stalled=g;return}let E=g-T;if(!o&&(E>=p||v)&&this.hls){var _;if(((_=this.mediaSource)==null?void 0:_.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let b=ie.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,E,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&r&&r.length>1&&e>r.end(0)){let n=ie.bufferedInfo(ie.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=ie.timeRangesToArray(r),o=ie.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=ie.bufferedInfo(a,e,0).bufferedIndex,u=a[o].end,d=a[o+1].start;if((l===-1||l>o)&&d-u<1&&e-u<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${d} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=xr(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=ie.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let u=(n=this.hls)==null?void 0:n.latestLevelDetails,d=xr(i,a);if((d||u!=null&&u.live&&i<u.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let n=i.getFragAtPos(t,W.MAIN),a=i.getFragAtPos(r,W.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:n}=this;if(!r&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Se(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!i||!n)return 0;let a=r.currentTime,o=ie.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let d=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(d||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){let p=i.getAppendedFrag(0,W.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var u;if(!((u=this.hls.loadLevelObj)!=null&&u.details)||Fd(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){let T=xr(v,i);if(T)v+=T.duration;else{g=!0;break}}if(g)return 0}}let f=Math.max(l+dE,a+uE);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:z.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(y.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Fd(s,e){let t=Ud(s.main);if(t&&t.start<=e)return t;let i=Ud(s.audio);return i&&i.start<=e?i:null}function Ud(s){if(!s)return null;switch(s.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return s.frag}function xr(s,e){return e.getAppendedFrag(s,W.MAIN)||e.getPartialFragment(s)}var hE=.25;function Fo(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function Sa(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r)}catch{n=new s(e,t,Se(r?ge({type:r},i):i))}return n}var Rr=(()=>{let s=Fo();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Uo=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,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),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,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),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Hi(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Xc(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Fo();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===tt.emsg&&!i||!r)continue;let u=Ic(n[o].data),d=n[o].pts,c=d+n[o].duration;c>Rr&&(c=Rr),c-d<=0&&(c=d+hE);for(let f=0;f<u.length;f++){let m=u[f];if(!Lc(m)){this.updateId3CueEnds(d,l);let p=Sa(a,d,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var i;let r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===Rr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let u;r==="audio"?u=d=>d.type===tt.audioId3&&l:r==="video"?u=d=>d.type===tt.emsg&&o:u=d=>d.type===tt.audioId3&&l||d.type===tt.emsg&&o,yo(n,t,i,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Fo();if(i&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=Sa(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:u}=e,d=Object.keys(u),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>!d.includes(g));for(let g=p.length;g--;){var f;let v=p[g],T=(f=c[v])==null?void 0:f.cues;delete c[v],T&&Object.keys(T).forEach(E=>{let _=T[E];if(_){_.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(_)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(d.length===0||!V(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){let g=d[p],v=u[g],T=v.startTime,E=c[g],_=(E==null?void 0:E.cues)||{},b=(E==null?void 0:E.durationKnown)||!1,x=Rr,{duration:S,endDate:R}=v;if(R&&S!==null)x=T+S,b=!0;else if(v.endOnNext&&!b){let A=d.reduce((L,P)=>{if(P!==v.id){let O=u[P];if(O.class===v.class&&O.startDate>v.startDate&&(!L||v.startDate<L.startDate))return O}return L},null);A&&(x=A.startTime,b=!0)}let I=Object.keys(v.attr);for(let A=0;A<I.length;A++){let L=I[A];if(!y0(L))continue;let P=_[L];if(P)b&&!(E!=null&&E.durationKnown)?P.endTime=x:Math.abs(P.startTime-T)>.01&&(P.startTime=T,P.endTime=x);else if(o){let O=v.attr[L];v0(L)&&(O=Kd(O));let F=Sa(o,T,x,{key:L,data:O},tt.dateRange);F&&(F.id=g,this.id3Track.addCue(F),_[L]=F,a&&(L==="X-ASSET-LIST"||L==="X-ASSET-URL")&&F.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:_,dateRange:v,durationKnown:b}}}}},Bo=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,u=Math.min(this.maxLatency,o+i.targetduration);if(l<u&&l>.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,u=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||u===0)&&(u=n!==void 0?n:a*r);let d=r;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let i=this.levelDetails;if(i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(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_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(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_UPDATED,this.onLevelUpdated,this),e.off(y.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===k.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},$o=class extends Ns{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{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.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{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.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,u=!1;t.levels.forEach(d=>{let c=d.attrs,{audioCodec:h,videoCodec:f}=d;h&&(d.audioCodec=h=Nr(h,i)||void 0),f&&(f=d.videoCodec=Gp(f));let{width:m,height:p,unknownCodecs:g}=d,v=(g==null?void 0:g.length)||0;if(o||(o=!!(m&&p)),l||(l=!!f),u||(u=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}let{CODECS:T,"FRAME-RATE":E,"HDCP-LEVEL":_,"PATHWAY-ID":b,RESOLUTION:x,"VIDEO-RANGE":S}=c,I=`${`${b||"."}-`}${d.bitrate}-${x}-${E}-${T}-${S}-${_}`;if(n[I])if(n[I].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let A=a[I]+=1;d.attrs["PATHWAY-ID"]=new Array(A+1).join(".");let L=this.createLevel(d);n[I]=L,r.push(L)}else n[I].addGroupId("audio",c.AUDIO),n[I].addGroupId("text",c.SUBTITLES);else{let A=this.createLevel(d);n[I]=A,a[I]=1,r.push(A)}}),this.filterAndSortMediaOptions(r,t,o,l,u)}createLevel(e){let t=new bi(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(r.message),t.supportedResult=Zd(r,[])}return t}isAudioSupported(e){return Is(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Is(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,n){var a;let o=[],l=[],u=e,d=((a=t.stats)==null?void 0:a.parsing)||{};if((i||r)&&n&&(u=u.filter(({videoCodec:T,videoRange:E,width:_,height:b})=>(!!T||!!(_&&b))&&Qp(E))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",E=T;t.levels.length&&(E=`one or more CODECS in variant not supported: ${Se(t.levels.map(b=>b.attrs.CODECS).filter((b,x,S)=>S.indexOf(b)===x))}`,this.warn(E),T+=` (${E})`);let _=new Error(T);this.hls.trigger(y.ERROR,{type:z.MEDIA_ERROR,details:k.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:_,reason:E})}}),d.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),Bd(o)),t.subtitles&&(l=t.subtitles,Bd(l));let c=u.slice(0);u.sort((T,E)=>{if(T.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==E.height)return T.height-E.height;if(T.frameRate!==E.frameRate)return T.frameRate-E.frameRate;if(T.videoRange!==E.videoRange)return Fr.indexOf(T.videoRange)-Fr.indexOf(E.videoRange);if(T.videoCodec!==E.videoCodec){let _=Mu(T.videoCodec),b=Mu(E.videoCodec);if(_!==b)return b-_}if(T.uri===E.uri&&T.codecSet!==E.codecSet){let _=Mr(T.codecSet),b=Mr(E.codecSet);if(_!==b)return b-_}return T.averageBitrate!==E.averageBitrate?T.averageBitrate-E.averageBitrate:0});let h=c[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==c.length)){for(let T=0;T<c.length;T++)if(c[T].pathwayId===u[0].pathwayId){h=c[T];break}}this._levels=u;for(let T=0;T<u.length;T++)if(u[T]===h){var f;this._firstLevel=T;let E=h.bitrate,_=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${E}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let b=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);b>_&&_===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}let m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(T=>!!T.url)};d.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let d=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:d,reason:d.message}),c)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);let u=a.details;if(!u||u.live){let d=this.switchParams(a.uri,r==null?void 0:r.details,u);this.loadPlaylist(d)}}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){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===ae.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===W.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));vc(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(y.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Bd(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function oh(){return self.SourceBuffer||self.WebKitSourceBuffer}function lh(){if(!Wt())return!1;let e=oh();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function fE(){if(!lh())return!1;let s=Wt();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Ls(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Ls(e,"audio"))))}function mE(){var s;let e=oh();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var gE=100,Go=class extends Ps{constructor(e,t,i){super(e,t,i,"stream-controller",W.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!V(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,W.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(gE),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e==null?void 0:e[t],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(y.BUFFER_EOS,p),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let u=a.details;if(!u||this.state===C.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}let d=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&Le(f)&&this.fragmentTracker.getState(f)!==Oe.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-u.startSN,v=u.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?_e.AUDIO:_e.VIDEO,v=(g===_e.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,W.MAIN)}f=this.getNextFragmentLoopLoading(f,u,o,W.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===Oe.NOT_LOADED||r===Oe.PARTIAL?Le(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,W.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],u=this.fragLastKbps;u&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*u)+1:i=0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;Ye(i,"playing",this.onMediaPlaying),Ye(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(Qe(i,"playing",this.onMediaPlaying),Qe(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&r&&!mE(),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){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let u=t.levelInfo,d=this.fragCurrent;d&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||(i=u.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,n||this.setStartPosition(o,c),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){let d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var u;let c=ie.bufferInfo(i,r,0);if(!((u=c.buffered)!=null&&u.length)){i.currentTime=r;return}if(c.start<=n){i.currentTime=r;return}let{nextStart:f}=ie.bufferedInfo(c.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=r}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=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}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let 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}let u=o.videoCodec,d=l.PTSKnown||!l.live,c=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Qr(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new ks(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[i.cc];f.push(n,c,h,u,i,r,l.totalduration,d,g,v)}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio!==0;if(Br(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),i.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=Br(t.url,this.hls);if(i){let 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=i?2:0,this.tick()}onBufferCreated(e,t){let i=t.tracks,r,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t,n=i.type===W.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}let o=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Le(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}let a=this.media;a&&(!this._hasEnoughToStart&&ie.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,t);break;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ae.LEVEL&&(this.state=C.IDLE);break;case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case k.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==_e.AUDIO||!this.altAudio){let i=(t===_e.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,W.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let n=this.getLevelDetails(),a=ie.getBuffered(e),o=a.length?a.start(0):0,l=o-i,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<u||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:r}=this,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(y.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:u}=a,{video:d,text:c,id3:h,initSegment:f}=r,{details:m}=u,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,f){let g=f.tracks;if(g){let _=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(u,g,_,n),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:_,id:t,tracks:g})}let v=f.initPTS,T=f.timescale,E=this.initPTS[o.cc];if(V(v)&&(!E||E.baseTime!==v||E.timescale!==T)){let _=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:_},i.trigger(y.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:_})}}if(d&&m){p&&d.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,T=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:E,endPTS:_,startDTS:b,endDTS:x}=d;if(l)l.elementaryStreams[d.type]={startPTS:E,endPTS:_,startDTS:b,endDTS:x};else if(d.firstKeyFrame&&d.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){let S=this.getMainFwdBufferInfo(),R=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,I=d.firstKeyFramePTS?d.firstKeyFramePTS:E;if(!v&&R<I-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,_,o.start,x,!0)}else v&&E-(m.appliedTimelineOffset||0)>Cr&&(o.gap=!0);o.setElementaryStreamInfo(d.type,E,_,b,x),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:T,endDTS:E}=p;l&&(l.elementaryStreams[_e.AUDIO]={startPTS:g,endPTS:v,startDTS:T,endDTS:E}),o.setElementaryStreamInfo(_e.AUDIO,g,v,T,E),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){let g={id:t,frag:o,details:m,samples:h.samples};i.trigger(y.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};i.trigger(y.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${Le(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let u=e.audioCodec,d=Ir(n.codec,u);d==="mp4a"&&(d="mp4a.40.5");let c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),u&&u!==d&&this.log(`Swapping manifest audio codec "${u}" for "${d}"`),n.levelCodec=d,n.id=W.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${d||""}/${u||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=W.MAIN;let u=a.codec;if((u==null?void 0:u.length)===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach(u=>{let c=t[u].initSegment;c!=null&&c.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:u,data:c,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,W.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(ie.isBuffered(e,i)?t=this.getAppendedFrag(i):ie.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return V(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(V(t)){let i=this.getLevelDetails(),r=this.currentFrag||(i?Ai(null,i.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ko=class extends Je{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=k.KEY_LOAD_ERROR,i,r,n){return new pt({type:z.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!Le(e)||!Le(a)||e.sn<a.sn)||!i&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=Dr(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=_s(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,k.KEY_LOAD_ERROR,u))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,k.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=ba(n),l=this.keyIdToKeyInfo[o];if((i=l)!=null&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(d=>{let{keyInfo:c}=d;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Ge(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,k.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=Dp(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Ge(o)}`),Qi.setKeyIdForUri(e.decryptdata.uri,o)):(o=Qi.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Ge(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Le(t))return Promise.resolve(i);let n=this.emeController.loadKey(i);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=i.keyLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:v}=m,T=ba(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(g,k.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,k.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,ge({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,k.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,k.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,d,c)})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let a=ba(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function ba(s){if(s.keyFormat!==Ke.FAIRPLAY){let e=s.keyId;if(e)return Ge(e)}return s.uri}function $d(s){let{type:e}=s;switch(e){case ae.AUDIO_TRACK:return W.AUDIO;case ae.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function Aa(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Vo=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{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),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{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),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,a=new n(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(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ae.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ae.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ae.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ae.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[ae.LEVEL];if(i){let r=i.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(i.abort(),delete this.loaders[ae.LEVEL])}}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let u=this.hls.logger,d=r.context;if(d&&d.levelOrTrack===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives)){d.url===e.url?u.log(`[playlist-loader]: ignore ${e.url} ongoing request`):u.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);return}u.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===ae.MANIFEST?n=i.manifestLoadPolicy.default:n=Ee({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),V((t=e.deliveryDirectives)==null?void 0:t.part)){let u;if(e.type===ae.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===ae.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===ae.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){let d=u.partTarget,c=u.targetduration;if(d&&c){let h=Math.max(d*3,c*.8)*1e3;n=Ee({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,d,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=u.data;d.parsing.start=performance.now(),Ti.isMediaPlaylist(m)||c.type!==ae.MANIFEST?this.handleTrackOrLevelPlaylist(u,d,c,h||null,f):this.handleMasterPlaylist(u,d,c,h)},onError:(u,d,c,h)=>{this.handleNetworkError(d,c,!1,u,h)},onTimeout:(u,d,c)=>{this.handleNetworkError(d,c,!0,void 0,u)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){let n=this.hls,a=e.data,o=Aa(e,i),l=Ti.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:u,levels:d,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,d.forEach(T=>{let{unknownCodecs:E}=T;if(E){let{preferManagedMediaSource:_}=this.hls.config,{audioCodec:b,videoCodec:x}=T;for(let S=E.length;S--;){let R=E[S];Is(R,"audio",_)?(T.audioCodec=b=b?`${b},${R}`:R,Xi.audio[b.substring(0,4)]=2,E.splice(S,1)):Is(R,"video",_)&&(T.videoCodec=x=x?`${x},${R}`:R,Xi.video[x.substring(0,4)]=2,E.splice(S,1))}}});let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Ti.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(E=>!E.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ae({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:g,captions:v,contentSteering:u,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,r,n){let a=this.hls,{id:o,level:l,type:u}=i,d=Aa(e,i),c=V(l)?l:V(o)?o:0,h=$d(i),f=Ti.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(u===ae.MANIFEST){let m={attrs:new Ae({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=t.loading.start+gc(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,n)}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(y.ERROR,{type:z.NETWORK_ERROR,details:k.MANIFEST_PARSING_ERROR,fatal:t.type===ae.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,i=!1,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ae.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ae.AUDIO_TRACK||e.type===ae.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=k.UNKNOWN,u=!1,d=this.getInternalLoader(e);switch(e.type){case ae.MANIFEST:l=i?k.MANIFEST_LOAD_TIMEOUT:k.MANIFEST_LOAD_ERROR,u=!0;break;case ae.LEVEL:l=i?k.LEVEL_LOAD_TIMEOUT:k.LEVEL_LOAD_ERROR,u=!1;break;case ae.AUDIO_TRACK:l=i?k.AUDIO_TRACK_LOAD_TIMEOUT:k.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case ae.SUBTITLE_TRACK:l=i?k.SUBTITLE_TRACK_LOAD_TIMEOUT:k.SUBTITLE_LOAD_ERROR,u=!1;break}d&&this.resetInternalLoader(e.type);let c={type:z.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(r){let h=(t==null?void 0:t.url)||e.url;c.response=ge({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,c)}handlePlaylistLoaded(e,t,i,r,n,a){let o=this.hls,{type:l,level:u,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:f}=r,m=Aa(t,r),p=$d(r),g=typeof r.level=="number"&&p===W.MAIN?u:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:z.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:z.NETWORK_ERROR,details:k.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:T,reason:T.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ae.MANIFEST:case ae.LEVEL:if(g){if(!d)g=0;else if(d!==o.levels[g]){let T=o.levels.indexOf(d);T>-1&&(g=T)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:d||o.levels[0],level:g||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===ae.MANIFEST});break;case ae.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case ae.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},Bs=class s{static get version(){return ws}static isMSESupported(){return lh()}static isSupported(){return fE()}static getMediaSource(){return Wt()}static get Events(){return y}static get MetadataSchema(){return tt}static get ErrorTypes(){return z}static get ErrorDetails(){return k}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:nE}static set DefaultConfig(e){s.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Qo,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=vp(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=oE(s.DefaultConfig,e,t);this.userConfig=e,i.progressive&&lE(i,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,u=new o(this),d=this.abrController=new r(this),c=new Oa(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,s):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),v=new Vo(this),T=i.contentSteeringController,E=T?new T(this):null,_=this.levelController=new $o(this,E),b=new Uo(this),x=new Ko(this.config,this.logger),S=this.streamController=new Go(this,c,x),R=this.gapController=new No(this,c);p.setStreamController(S),g.setStreamController(S);let I=[v,_,S];f&&I.splice(1,0,f),E&&I.splice(1,0,E),this.networkControllers=I;let A=[d,m,R,p,g,b,c];this.audioTrackController=this.createController(i.audioTrackController,I);let L=i.audioStreamController;L&&I.push(this.audioStreamController=new L(this,c,x)),this.subtitleTrackController=this.createController(i.subtitleTrackController,I);let P=i.subtitleStreamController;P&&I.push(this.subtititleStreamController=new P(this,c,x)),this.createController(i.timelineController,A),x.emeController=this.emeController=this.createController(i.emeController,A),this.cmcdController=this.createController(i.cmcdController,A),this.latencyController=this.createController(Bo,A),this.coreComponents=A,I.push(u);let O=u.onErrorOut;typeof O=="function"&&this.on(y.ERROR,O,u),this.on(y.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let 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,r){this._emitter.off(e,t,i,r)}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){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let r=e===y.ERROR;this.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.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;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:z.OTHER_ERROR,details:k.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(y.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=Ho.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[W.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[W.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[W.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Iv()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.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){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Xp(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=ic(t);return ec(e,i,navigator.mediaCapabilities)}};Bs.defaultConfig=void 0;var se=Bs,ye={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ue={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_RECONNECTING:2000003,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},Eh=s=>s===ye.VIDEO?"playback":s,jt=class $s extends Error{constructor(e,t=$s.MEDIA_ERR_CUSTOM,i,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=i!=null?i:t>=$s.MEDIA_ERR_NETWORK&&t<=$s.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=$s.defaultMessages[this.code])!=null?n:"")}};jt.MEDIA_ERR_ABORTED=1,jt.MEDIA_ERR_NETWORK=2,jt.MEDIA_ERR_DECODE=3,jt.MEDIA_ERR_SRC_NOT_SUPPORTED=4,jt.MEDIA_ERR_ENCRYPTED=5,jt.MEDIA_ERR_CUSTOM=100,jt.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var q=jt,pE=s=>s==null,El=(s,e)=>pE(e)?!1:s in e,dl={ANY:"any",MUTED:"muted"},qe={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},xi={MSE:"mse",NATIVE:"native"},Gs={HEADER:"header",QUERY:"query",NONE:"none"},Tl=Object.values(Gs),Mt={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},cl={HLS:Mt.M3U8},e_=Object.keys(cl),t_=[...Object.values(Mt),"hls","HLS"];var yE="en",hl={code:yE},Ie=(s,e,t,i,r=s)=>{r.addEventListener(e,t,i),s.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function vE(s,e,t){e&&t>e&&(t=e);for(let i=0;i<s.length;i++)if(s.start(i)<=t&&s.end(i)>=t)return!0;return!1}var mn=s=>{let e=s.indexOf("?");if(e<0)return[s];let t=s.slice(0,e),i=s.slice(e);return[t,i]},gn=s=>{let{type:e}=s;if(e){let t=e.toUpperCase();return El(t,cl)?cl[t]:e}return EE(s)},Th=s=>s==="VOD"?qe.ON_DEMAND:qe.LIVE,_h=s=>s==="EVENT"?Number.POSITIVE_INFINITY:s==="VOD"?Number.NaN:0,EE=s=>{let{src:e}=s;if(!e)return"";let t="";try{t=_l(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let i=t.lastIndexOf(".");if(i<0)return SE(s)?Mt.M3U8:"";let r=t.slice(i+1).toUpperCase();return El(r,Mt)?Mt[r]:""},fl=s=>{try{return new URL(s),!1}catch{return!0}},TE=s=>s.split(`
|
|
56
|
-
`).find((e,t,i)=>t>0&&i[t-1].startsWith("#EXT-X-STREAM-INF")),_l=(s,e)=>{var t;if(!fl(s))return new URL(s);let i=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:i;return e&&fl(e.toString())&&(r=new URL(e,i)),new URL(s,r)},_E="mux.com",SE=({src:s,customDomain:e=_E})=>{let t;try{t=new URL(`${s}`)}catch{return!1}let i=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return i&&r&&a&&o},bE=s=>{let e=(s!=null?s:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(i)}catch{return}},AE=({exp:s},e=Date.now())=>!s||s*1e3<e,xE=({sub:s},e)=>s!==e,RE=({aud:s},e)=>!s,IE=({aud:s},e)=>s!==e,Sh="en";function le(s,e=!0){var t,i;let r=e&&(i=(t=hl)==null?void 0:t[s])!=null?i:s,n=e?hl.code:Sh;return new LE(r,n)}var LE=class{constructor(s,e=(t=>(t=hl)!=null?t:Sh)()){this.message=s,this.locale=e}format(s){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var i;return(i=s[t])!=null?i:""})}toString(){return this.message}},DE=Object.values(dl),uh=s=>typeof s=="boolean"||typeof s=="string"&&DE.includes(s),kE=(s,e,t)=>{let{autoplay:i}=s,r=!1,n=!1,a=uh(i)?i:!!i,o=()=>{r||Ie(e,"playing",()=>{r=!0},{once:!0})};if(o(),Ie(e,"loadstart",()=>{r=!1,o(),ol(e,a)},{once:!0}),Ie(e,"loadstart",()=>{t||(s.streamType&&s.streamType!==qe.UNKNOWN?n=s.streamType===qe.LIVE:n=!Number.isFinite(e.duration)),ol(e,a)},{once:!0}),t&&t.once(se.Events.LEVEL_LOADED,(l,u)=>{var d;s.streamType&&s.streamType!==qe.UNKNOWN?n=s.streamType===qe.LIVE:n=(d=u.details.live)!=null?d:!1}),!a){let l=()=>{!n||Number.isFinite(s.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Ie(e,"play",()=>{e.preload==="metadata"?t.once(se.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=uh(l)?l:!!l,ol(e,a))}},ol=(s,e)=>{if(!e)return;let t=s.muted,i=()=>s.muted=t;switch(e){case dl.ANY:s.play().catch(()=>{s.muted=!0,s.play().catch(i)});break;case dl.MUTED:s.muted=!0,s.play().catch(i);break;default:s.play().catch(()=>{});break}},PE=({preload:s,src:e},t,i)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!i)return r(s),r;let n=!1,a=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,u=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),d())},d=()=>{!n&&e&&(n=!0,i.loadSource(e))};return Ie(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,d()},{once:!0}),u(s),u},wE=(s,e,t)=>{let{minPreloadSegments:i}=s;if(i==null||i<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,Ie(e,"ratechange",o);let l=(u,{frag:d})=>{n||d.type!=="main"||(r++,r>=i&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(se.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(se.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},CE=(s,e,t)=>{let{initialEstimateSegments:i}=s;if(i==null||i<=0||!t)return;let r=0;t.on(se.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<i&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function OE(s,e){var t;if(!("videoTracks"in s))return;let i=new WeakMap;e.on(se.Events.MANIFEST_PARSED,function(u,d){l();let c=s.addVideoTrack("main");c.selected=!0;for(let[h,f]of d.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);i.set(f,`${h}`),m.id=`${h}`}}),e.on(se.Events.AUDIO_TRACKS_UPDATED,function(u,d){o();for(let c of d.audioTracks){let h=c.default?"main":"alternative",f=s.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var u;let d=+((u=[...s.audioTracks].find(h=>h.enabled))==null?void 0:u.id),c=e.audioTracks.map(h=>h.id);d!=e.audioTrack&&c.includes(d)&&(e.audioTrack=d)};s.audioTracks.addEventListener("change",r),e.on(se.Events.LEVELS_UPDATED,function(u,d){var c;let h=s.videoTracks[(c=s.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=d.levels.map(m=>i.get(m));for(let m of s.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=u=>{let d=u.target.selectedIndex;d!=e.nextLevel&&(e.nextLevel=d)};(t=s.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let u of s.videoTracks)s.removeVideoTrack(u)},o=()=>{for(let u of s.audioTracks)s.removeAudioTrack(u)},l=()=>{a(),o()};e.once(se.Events.DESTROYING,()=>{var u,d;l(),(u=s.audioTracks)==null||u.removeEventListener("change",r),(d=s.videoRenditions)==null||d.removeEventListener("change",n)})}var ll=s=>"time"in s?s.time:s.startTime;function ME(s,e){e.on(se.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let u=(o=a.subtitleTrack)!=null?o:a.closedCaptions,d=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(u==null?void 0:u.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${d}`;bh(s,a.kind,a.label,u==null?void 0:u.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(s.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:u,type:d,default:c})=>r.id==="default"&&c||l==r.language&&u===r.label&&d.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};s.textTracks.addEventListener("change",t),e.on(se.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=s.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(u=>{var d;(d=o.cues)!=null&&d.getCueById(u.id)||o.addCue(u)}),l&&(o.mode="disabled")}),e.once(se.Events.DESTROYING,()=>{s.textTracks.removeEventListener("change",t),s.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let i=()=>{Array.from(s.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=s.querySelector(o),u=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",u)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(se.Events.MANIFEST_LOADED,i),e.once(se.Events.MEDIA_ATTACHED,i)}function bh(s,e,t,i,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,i&&(a.srclang=i),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),s.append(a),a.track}function Vs(s,e,t){var i;return(i=Array.from(s.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:i.track}async function Ah(s,e,t,i){let r=Vs(s,t,i);return r||(r=bh(s,i,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>ll(a)-ll(n)).forEach(n=>{var a,o;let l=n.value,u=ll(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(u,n.endTime,i==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let d=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=u),c=(a=r==null?void 0:r.cues)==null?void 0:a[d],h=c?c.startTime:Number.isFinite(s.duration)?s.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[d-1];f&&(f.endTime=u),r==null||r.addCue(new VTTCue(u,h,i==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),s.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Sl="cuepoints",xh=Object.freeze({label:Sl});async function bl(s,e,t=xh){return Ah(s,e,t.label,"metadata")}var ml=s=>({time:s.startTime,value:JSON.parse(s.text)});function Rh(s,e={label:Sl}){let t=Vs(s,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,i=>ml(i)):[]}function Al(s,e={label:Sl}){var t,i;let r=Vs(s,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return ml(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return ml(a||r.activeCues[0])}async function NE(s,e=xh){return new Promise(t=>{Ie(s,"loadstart",async()=>{let i=await bl(s,[],e);Ie(s,"cuechange",()=>{let r=Al(s);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}var xl="chapters",Ih=Object.freeze({label:xl}),gl=s=>({startTime:s.startTime,endTime:s.endTime,value:s.text});async function Rl(s,e,t=Ih){return Ah(s,e,t.label,"chapters")}function Lh(s,e={label:xl}){var t;let i=Vs(s,e.label,"chapters");return(t=i==null?void 0:i.cues)!=null&&t.length?Array.from(i.cues,r=>gl(r)):[]}function Il(s,e={label:xl}){var t,i;let r=Vs(s,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return gl(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return gl(a||r.activeCues[0])}async function FE(s,e=Ih){return new Promise(t=>{Ie(s,"loadstart",async()=>{let i=await Rl(s,[],e);Ie(s,"cuechange",()=>{let r=Il(s);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}function Dh(s,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-s.currentTime*1e3)}return typeof s.getStartDate=="function"?s.getStartDate():new Date(NaN)}function kh(s,e){if(e&&e.playingDate)return e.playingDate;if(typeof s.getStartDate=="function"){let t=s.getStartDate();return new Date(t.getTime()+s.currentTime*1e3)}return new Date(NaN)}var dh={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},UE=s=>{if(s===ye.VIDEO)return dh.VIDEO;if(s===ye.DRM)return dh.DRM},BE=(s,e)=>{var t,i;let r=Eh(s),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(i=e.tokens)==null?void 0:i[r]:El(n,e)?e[n]:void 0},hn=(s,e,t,i,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=le("Your device appears to be offline",r),T,E=q.MEDIA_ERR_NETWORK,_=new q(v,E,!1,T);return _.errorCategory=e,_.muxCode=ue.NETWORK_OFFLINE,_.data=s,_}let l="status"in s?s.status:s.code,u=Date.now(),d=q.MEDIA_ERR_NETWORK;if(l===200)return;let c=Eh(e),h=BE(e,t),f=UE(e),[m]=mn((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=bE(h);if(h&&!p){let v=le("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),T=le("Compact JWT string: {token}",r).format({token:h}),E=new q(v,d,!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_MALFORMED,E.data=s,E}if(l>=500){let v=new q("",d,i!=null?i:!0);return v.errorCategory=e,v.muxCode=ue.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(AE(p,u)){let v={timeStyle:"medium",dateStyle:"medium"},T=le("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),E=le("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(u)}),_=new q(T,d,!0,E);return _.errorCategory=e,_.muxCode=ue.NETWORK_TOKEN_EXPIRED,_.data=s,_}if(xE(p,m)){let v=le("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),T=le("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),E=new q(v,d,!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_SUB_MISMATCH,E.data=s,E}if(RE(p,f)){let v=le("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=le("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),E=new q(v,d,!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_AUD_MISSING,E.data=s,E}if(IE(p,f)){let v=le("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=le("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),E=new q(v,d,!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_AUD_MISMATCH,E.data=s,E}}else{let v=le("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),T=le("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new q(v,d,i!=null?i:!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_MISSING,E.data=s,E}if(l===412){let v=le("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),T=le("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new q(v,d,i!=null?i:!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_NOT_READY,E.streamType=t.streamType===qe.LIVE?"live":t.streamType===qe.ON_DEMAND?"on-demand":"unknown",E.data=s,E}if(l===404){let v=le("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),T=le("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new q(v,d,i!=null?i:!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_NOT_FOUND,E.data=s,E}if(l===400){let v=le("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),T=le("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new q(v,d,i!=null?i:!0,T);return E.errorCategory=e,E.muxCode=ue.NETWORK_INVALID_URL,E.data=s,E}let g=new q("",d,i!=null?i:!0);return g.errorCategory=e,g.muxCode=ue.NETWORK_UNKNOWN_ERROR,g.data=s,g},ch=se.DefaultConfig.capLevelController,$E={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function GE(s){let e=s.toLowerCase().trim();return $E[e]}var pl=class Ks extends ch{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?Ks.maxAutoResolution.set(e,t):Ks.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=Ks.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,i)=>this.isLevelAllowed(t)&&i<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),i=this.getMaxAutoResolution();if(!i)return super.getMaxLevel(e);let r=GE(i);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(u=>u===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),i=this.getValidLevels(e);if(!i[t])return t;let r=Math.min(i[t].width,i[t].height),n=Ks.minMaxResolution;return r>=n?t:ch.getMaxLevelByMediaSize(i,n*(16/9),n)}};pl.minMaxResolution=720,pl.maxAutoResolution=new WeakMap;var KE=pl,yl=KE,VE="com.apple.fps.1_0",HE="application/vnd.apple.mpegurl",qE=({mediaEl:s,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:i,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in s)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=le("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new q(h,q.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=ye.DRM,f.muxCode=ue.ENCRYPTED_CDM_ERROR,i(s,f),()=>{}}let n=s,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||u();let f=await a;if(h.initData===null||f==null)return;let m=WE(h.initData,f);d(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),i(n,f)}})()},u=()=>{try{let h=new WebKitMediaKeys(VE);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new q(h,q.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=ye.DRM,f.muxCode=ue.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},d=h=>{let f=n.webkitKeys.createSession(HE,h),m=async v=>{try{let T=v.message,E=await t(T);f.update(E)}catch(T){console.error("Error on FairPlay session message",T),i(s,T)}},p=v=>{let T=v.target.error;if(!T)return;console.error(`Internal Webkit Key Session Error - sysCode: ${T.systemCode} code: ${T.code}`);let E=le("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),_=new q(E,q.MEDIA_ERR_ENCRYPTED,!0);_.errorCategory=ye.DRM,_.muxCode=ue.ENCRYPTED_CDM_ERROR,i(s,_)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),s.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in s&&s.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in s&&s.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),s.addEventListener("teardown",g),o=g},c=()=>{s.removeEventListener("webkitneedkey",l),s.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return s.addEventListener("webkitneedkey",l),s.addEventListener("teardown",c,{once:!0}),c},WE=(s,e)=>{let t=jE(YE(s)),i=new Uint8Array(s),r=new Uint8Array(t),n=new Uint8Array(e),a=i.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,u=c=>{o.set(c,l),l+=c.byteLength},d=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,u(c)};return u(i),d(r),d(n),o},YE=s=>new TextDecoder("utf-16le").decode(s).replace("skd://","").slice(1);function jE(s){let e=new ArrayBuffer(s.length*2),t=new DataView(e);for(let i=0;i<s.length;i++)t.setUint16(i*2,s.charCodeAt(i),!0);return e}var zE=({mediaEl:s,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:i,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}s.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await u(h,f)}catch(h){i(s,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(m=>(r(),m)).catch(()=>{let m=le("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new q(m,q.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=ye.DRM,p.muxCode=ue.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,i(s,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=le("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new q(p,q.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=ye.DRM,g.muxCode=ue.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){i(s,m);return}await s.setMediaKeys(f)},u=async(c,h)=>{let f=s.mediaKeys.createSession(),m=async v=>{let T=v.message,E=await t(T);try{await f.update(E)}catch{let _=le("Failed to update DRM license. This may be an issue with the player or your protected content."),b=new q(_,q.MEDIA_ERR_ENCRYPTED,!0);b.errorCategory=ye.DRM,b.muxCode=ue.ENCRYPTED_UPDATE_LICENSE_FAILED,i(s,b)}},p=()=>{let v=T=>{let E;if(T==="internal-error"){let _=le("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");E=new q(_,q.MEDIA_ERR_ENCRYPTED,!0),E.errorCategory=ye.DRM,E.muxCode=ue.ENCRYPTED_CDM_ERROR}else if(T==="output-restricted"||T==="output-downscaled"){let _=le("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");E=new q(_,q.MEDIA_ERR_ENCRYPTED,!1),E.errorCategory=ye.DRM,E.muxCode=ue.ENCRYPTED_OUTPUT_RESTRICTED}E&&i(s,E)};f.keyStatuses.forEach(T=>v(T))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in s&&s.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),s.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in s&&s.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),s.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in s&&s.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let T=le("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),E=new q(T,q.MEDIA_ERR_ENCRYPTED,!0);return E.errorCategory=ye.DRM,E.muxCode=ue.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(E)}})},d=async()=>{s.removeEventListener("encrypted",o),s.removeEventListener("teardown",d),a&&await a(),await s.setMediaKeys(null).catch(()=>{})};return s.addEventListener("encrypted",o),s.addEventListener("teardown",d,{once:!0}),d},XE=({hls:s,mediaEl:e,src:t,muxMediaState:i,saveAndDispatchError:r,maxRetries:n})=>{var a;let o,l=0,u=!1,d=!1,c=!1,h=()=>{o!=null&&(clearTimeout(o),o=void 0)},f=S=>(S==null?void 0:S.muxCode)===ue.NETWORK_RECONNECTING,m=()=>!e.paused&&e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA,p=()=>{let S=i.get(e);if(f(S==null?void 0:S.error))return;let R=new q(le("Attempting to reconnect..."),q.MEDIA_ERR_NETWORK,!1);R.errorCategory=ye.VIDEO,R.muxCode=ue.NETWORK_RECONNECTING,S&&(S.error=R),e.dispatchEvent(new CustomEvent("error",{detail:R}))},g=()=>{if(!c&&t){s.loadSource(t);return}s.startLoad(e.currentTime)},v=()=>{u=!1,d=!0,h();let S=new q(le("Network error, try reloading."),q.MEDIA_ERR_NETWORK,!0);S.errorCategory=ye.VIDEO,S.reload=!0,r(e,S)},T=()=>{if(o!=null||u)return;if(l>=n){v();return}u=!0;let S=Math.min(1e3*2**l,3e4);o=setTimeout(()=>{o=void 0,l+=1,g()},S)},E=()=>{let S=i.get(e);!(S!=null&&S.networkError)||d||m()&&(p(),T())},_=()=>{let S=i.get(e);S&&(S.networkError=!0),u=!1,E()},b=()=>{let S=i.get(e);S!=null&&S.networkError&&(l=0,d=!1,h(),u=!0,g())};(a=globalThis.addEventListener)==null||a.call(globalThis,"online",b);let x=()=>{let S=i.get(e);S&&(!S.networkError&&!f(S.error)||(S.networkError=!1,u=!1,l=0,d=!1,h(),S.error&&(S.error=null,e.dispatchEvent(new Event("emptied")))))};return s.on(se.Events.FRAG_BUFFERED,x),Ie(e,"playing",()=>{let S=i.get(e);S!=null&&S.networkError&&(u=!1,l=0,d=!1,h(),S.error&&(S.error=null))}),Ie(e,"waiting",E),e.addEventListener("teardown",()=>{var S;(S=globalThis.removeEventListener)==null||S.call(globalThis,"online",b),h()},{once:!0}),{handleHlsError:(S,R)=>{var I,A;if(S.type!==se.ErrorTypes.NETWORK_ERROR)return!1;let L=(A=(I=S.response)==null?void 0:I.code)!=null?A:0;return(R.muxCode===ue.NETWORK_OFFLINE||L===0||L>=500)&&S.fatal?(_(),!0):!1},onManifestLoaded:()=>{c=!0,u=!1,h()}}},dn={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},QE=s=>{if(s.includes("fps"))return dn.FAIRPLAY;if(s.includes("playready"))return dn.PLAYREADY;if(s.includes("widevine"))return dn.WIDEVINE},JE=(s,e)=>{let t=TE(s);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(fl(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let i;try{i=_l(t,e)}catch(r){return Promise.reject(r)}return fetch(i).then(r=>r.status!==200?Promise.reject(r):r.text())},ZE=s=>{let e=s.split(`
|
|
57
|
-
`).filter(i=>i.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let i of e){let r=tT(i),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},eT=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function tT(s){let e=[...s.matchAll(eT)];return Object.fromEntries(e.map(([,t,i])=>[t,i]))}var iT=s=>{var e,t,i;let r=s.split(`
|
|
58
|
-
`),n=(t=((e=r.find(u=>u.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=Th(n),o=_h(n),l;if(a===qe.LIVE){let u=r.find(d=>d.startsWith("#EXT-X-PART-INF"));if(u)l=+u.split(":")[1].split("=")[1]*2;else{let d=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(i=d==null?void 0:d.split(":"))==null?void 0:i[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},sT=async(s,e)=>{if(e===Mt.MP4)return{streamType:qe.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===Mt.M3U8){let t=await fetch(s);if(!t.ok)return Promise.reject(t);let i=await t.text(),r=await JE(i,t.url);return{...ZE(i),...iT(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${s}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},rT=async(s,e,t=gn({src:s}))=>{var i,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:u,sessionData:d}=await sT(s,t),c=d==null?void 0:d["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&Ll((i=c.URI)!=null?i:c.VALUE,e),((r=ve.get(e))!=null?r:{}).liveEdgeStartOffset=u,((n=ve.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=ve.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Ll=async(s,e)=>{var t,i;try{let r=await fetch(s);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((i=ve.get(e))!=null?i:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},nT=s=>{var e;let t=s.type,i=Th(t),r=_h(t),n,a=!!((e=s.partList)!=null&&e.length);return i===qe.LIVE&&(n=a?s.partTarget*2:s.targetduration*3),{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},aT=(s,e,t)=>{var i,r,n,a,o,l,u,d;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=nT(s);if(c===qe.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=ve.get(e))!=null?o:{}).seekable=p}((l=ve.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=ve.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((d=ve.get(e))!=null?d:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},hh,fh,Ph=(fh=(hh=globalThis==null?void 0:globalThis.navigator)==null?void 0:hh.userAgent)!=null?fh:"",mh,gh,ph,oT=(ph=(gh=(mh=globalThis==null?void 0:globalThis.navigator)==null?void 0:mh.userAgentData)==null?void 0:gh.platform)!=null?ph:"",lT=Ph.toLowerCase().includes("android")||["x11","android"].some(s=>oT.toLowerCase().includes(s)),uT=s=>/^((?!chrome|android).)*safari/i.test(Ph)&&!!s.canPlayType("application/vnd.apple.mpegurl"),ve=new WeakMap,Nt="mux.com",yh,vh,wh=(vh=(yh=se).isSupported)==null?void 0:vh.call(yh),dT=s=>lT||!uT(s),Ch=()=>{if(typeof window!="undefined")return hr.utils.now()},cT=hr.utils.generateUUID,Oh=({playbackId:s,customDomain:e=Nt,maxResolution:t,minResolution:i,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:u,tokens:{playback:d=u}={},extraSourceParams:c={}}={})=>{if(!s)return;let[h,f=""]=mn(s),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return d||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),d&&m.searchParams.set("token",d)):(t&&m.searchParams.set("max_resolution",t),i&&(m.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},pn=s=>{if(!s)return;let[e]=s.split("?");return e||void 0},yn=s=>{if(!s||!s.startsWith("https://stream."))return;let[e]=new URL(s).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},hT=s=>{var e,t,i;return(e=s==null?void 0:s.metadata)!=null&&e.video_id?s.metadata.video_id:Hh(s)&&(i=(t=pn(s.playbackId))!=null?t:yn(s.src))!=null?i:s.src},Dl=s=>{var e;return(e=ve.get(s))==null?void 0:e.error},Mh=s=>{var e;return(e=ve.get(s))==null?void 0:e.metadata},fn=s=>{var e,t;return(t=(e=ve.get(s))==null?void 0:e.streamType)!=null?t:qe.UNKNOWN},Nh=s=>{var e,t;return(t=(e=ve.get(s))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},vn=s=>{var e,t;return(t=(e=ve.get(s))==null?void 0:e.seekable)!=null?t:s.seekable},Fh=s=>{var e;let t=(e=ve.get(s))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let i=vn(s);return i.length?i.end(i.length-1)-t:Number.NaN},Uh=s=>{var e;return(e=ve.get(s))==null?void 0:e.coreReference},kl=.034,fT=(s,e,t=kl)=>Math.abs(s-e)<=t,Bh=(s,e,t=kl)=>s>e||fT(s,e,t),mT=(s,e=kl)=>s.paused&&Bh(s.currentTime,s.duration,e),$h=(s,e)=>{var t,i,r;if(!e||!s.buffered.length)return;if(s.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(s.currentTime<s.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(s.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=s.buffered.start(s.buffered.length-1),d=s.buffered.end(s.buffered.length-1);return l>u&&l<d},Pl=(s,e)=>s.ended||s.loop?s.ended:e&&$h(s,e)?!0:mT(s),wl=(s,e,t)=>{Cl(e,t,s);let{metadata:i={}}=s,{view_session_id:r=cT()}=i,n=hT(s);i.view_session_id=r,i.video_id=n,s.metadata=i;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};s.drmTypeCb=a,s.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;s.useWebkitFairplay=!0;let p=s.muxDataKeepSession;s.muxDataKeepSession=!0;let g=(h=ve.get(e))==null?void 0:h.coreReference;wl(s,e,g),s.muxDataKeepSession=p,s.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},ve.set(e,{retryCount:0});let o=yT(s,e),l=PE(s,e,o);s!=null&&s.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?se:void 0}):qh(s,e,o),AT(s,e,o),NE(e),FE(e);let u=kE(s,e,o);wE(s,e,o),CE(s,e,o);let d={engine:o,setAutoplay:u,setPreload:l},c=ve.get(e);return c&&(c.coreReference=d),d},gT=()=>{let s=new Date(0).toUTCString(),e=new Set(["muxData"]);document.cookie.split(";").forEach(t=>{let i=t.split("=")[0].trim();i.startsWith("muxData")&&e.add(i)}),e.forEach(t=>{document.cookie=`${t}=;expires=${s};path=/`})},ul=new WeakMap,pT=(s,e,t)=>{e&&(e.mux&&(e.mux.deleted||e.mux.destroy(),delete e.mux),!ul.has(e)&&ul.set(e,Promise.resolve().then(()=>{var i,r;ul.delete(e);let n=ve.get(e);if(!n||e.mux&&!e.mux.deleted)return;let a=(r=(i=n.coreReference)!=null?i:t)==null?void 0:r.engine;qh(s,e,a)})))},Gh=(s,e,t)=>{if(!e)return;let i=!!s.disableCookies,r=ve.get(e);!r||r.muxDataDisableCookies===i||(pT(s,e,t),i&&Promise.resolve().then(()=>{s.disableCookies&&gT()}))},Cl=(s,e,t)=>{let i=e==null?void 0:e.engine;s!=null&&s.mux&&!s.mux.deleted&&(t!=null&&t.muxDataKeepSession?i&&s.mux.removeHLSJS():(s.mux.destroy(),delete s.mux)),i&&(i.detachMedia(),i.destroy()),s&&(s.hasAttribute("src")&&(s.removeAttribute("src"),s.load()),s.removeEventListener("error",Yh),s.removeEventListener("error",vl),s.removeEventListener("durationchange",Wh),ve.delete(s),s.dispatchEvent(new Event("teardown")))};function Kh(s,e){var t;let i=gn(s);if(i!==Mt.M3U8)return!0;let r=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=s,a=n===xi.MSE,o=n===xi.NATIVE,l=wh&&(a||dT(e));return r&&(o||!l)}var yT=(s,e)=>{let{debug:t,streamType:i,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:u}=s,d=gn(s)===Mt.M3U8,c=Kh(s,e);if(d&&!c&&wh){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...u!=null?{abrEwmaDefaultEstimate:u*1e3}:{}},f=vT(i),m=ET(s),p=[Gs.QUERY,Gs.HEADER].includes(a)?{useHeaders:a===Gs.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=bT(s,o),v=new se({debug:t,startPosition:r,cmcd:p,xhrSetup:(T,E)=>{var _,b;if(a&&a!==Gs.QUERY)return;let x=_l(E);if(!x.searchParams.has("CMCD"))return;let S=((b=(_=x.searchParams.get("CMCD"))==null?void 0:_.split(","))!=null?b:[]).filter(R=>R.startsWith("sid")||R.startsWith("cid")).join(",");x.searchParams.set("CMCD",S),T.open("GET",x)},...h,...g,...f,...m,...o});return g.capLevelController===yl&&l!==void 0&&yl.setMaxAutoResolution(v,l),v.on(se.Events.MANIFEST_PARSED,async function(T,E){var _,b;let x=(_=E.sessionData)==null?void 0:_["com.apple.hls.chapters"];(x!=null&&x.URI||x!=null&&x.VALUE.toLocaleLowerCase().startsWith("http"))&&Ll((b=x==null?void 0:x.URI)!=null?b:x==null?void 0:x.VALUE,e)}),v}},vT=s=>s===qe.LIVE?{backBufferLength:8}:{},ET=s=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:i}=s,r=pn(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:cn(s,"fairplay"),serverCertificateUrl:Vh(s,"fairplay")},"com.widevine.alpha":{licenseUrl:cn(s,"widevine")},"com.microsoft.playready":{licenseUrl:cn(s,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let u=(l=o.videoCapabilities)==null?void 0:l.map(d=>({...d,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:u}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=QE(n);return i==null||i(l),o}))}},TT=async s=>{let e=await fetch(s);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},_T=async(s,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:s});if(t.status!==200)return Promise.reject(t);let i=await t.arrayBuffer();return new Uint8Array(i)},ST=(s,e)=>{let t={mediaEl:e,getAppCertificate:()=>TT(Vh(s,"fairplay")).catch(i=>{if(i instanceof Response){let r=hn(i,ye.DRM,s);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(i)}),getLicenseKey:i=>_T(i,cn(s,"fairplay")).catch(r=>{if(r instanceof Response){let n=hn(r,ye.DRM,s);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:Ot,drmTypeCb:()=>{var i;(i=s.drmTypeCb)==null||i.call(s,dn.FAIRPLAY)}};if(s.useWebkitFairplay)qE(t);else{let i={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=s.fallbackToWebkitFairplay)==null||n.call(s)},...t},r=zE(i)}},cn=({playbackId:s,tokens:{drm:e}={},customDomain:t=Nt},i)=>{let r=pn(s);return`https://license.${t.toLocaleLowerCase().endsWith(Nt)?t:Nt}/license/${i}/${r}?token=${e}`},Vh=({playbackId:s,tokens:{drm:e}={},customDomain:t=Nt},i)=>{let r=pn(s);return`https://license.${t.toLocaleLowerCase().endsWith(Nt)?t:Nt}/appcert/${i}/${r}?token=${e}`},Hh=({playbackId:s,src:e,customDomain:t})=>{if(s)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,r=new URL(e,i).hostname.toLocaleLowerCase();return r.includes(Nt)||!!t&&r.includes(t.toLocaleLowerCase())},bT=(s,e)=>{let t={};return t.capLevelToPlayerSize=s.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=yl,t.capLevelToPlayerSize=!0):t.capLevelController=Us,t},qh=(s,e,t)=>{var i;let{envKey:r,disableTracking:n,muxDataSDK:a=hr,muxDataSDKOptions:o={}}=s,l=Hh(s),u=ve.get(e);if(u&&(u.muxDataDisableCookies=!!s.disableCookies),!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:c,playerSoftwareVersion:h,beaconCollectionDomain:f,debug:m,disableCookies:p}=s,g={...s.metadata,video_title:((i=s==null?void 0:s.metadata)==null?void 0:i.video_title)||void 0},v=T=>typeof T.player_error_code=="string"?!1:typeof s.errorTranslator=="function"?s.errorTranslator(T):T;a.monitor(e,{debug:m,beaconCollectionDomain:f,hlsjs:t,Hls:t?se:void 0,automaticErrorTracking:!1,errorTranslator:v,disableCookies:p,...o,data:{...r?{env_key:r}:{},player_software_name:c,player_software:c,player_software_version:h,player_init_time:d,...g}})}},AT=(s,e,t)=>{var i,r,n;let a=Kh(s,e),{src:o,customDomain:l=Nt}=s,u=()=>{e.ended||s.disablePseudoEnded||!Pl(e,t)||($h(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,c,h=()=>{let f=vn(e),m,p;f.length>0&&(m=f.start(0),p=f.end(0)),(c!==p||d!==m)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=m,c=p};if(Ie(e,"durationchange",h),e&&a){let f=gn(s);if(typeof o=="string"){if(o.endsWith(".mp4")&&o.includes(l)){let g=yn(o),v=new URL(`https://stream.${l}/${g}/metadata.json`);Ll(v.toString(),e)}let m=()=>{if(fn(e)!==qe.LIVE||Number.isFinite(e.duration))return;let g=setInterval(h,1e3);e.addEventListener("teardown",()=>{clearInterval(g)},{once:!0}),Ie(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(g)})},p=async()=>rT(o,e,f).then(m).catch(g=>{if(g instanceof Response){let v=hn(g,ye.VIDEO,s);if(v){Ot(e,v);return}}else g instanceof Error});if(e.preload==="none"){let g=()=>{p(),e.removeEventListener("loadedmetadata",v)},v=()=>{p(),e.removeEventListener("play",g)};Ie(e,"play",g,{once:!0}),Ie(e,"loadedmetadata",v,{once:!0})}else p();(i=s.tokens)!=null&&i.drm?ST(s,e):Ie(e,"encrypted",()=>{let g=le("Attempting to play DRM-protected content without providing a DRM token."),v=new q(g,q.MEDIA_ERR_ENCRYPTED,!0);v.errorCategory=ye.DRM,v.muxCode=ue.ENCRYPTED_MISSING_TOKEN,Ot(e,v)},{once:!0}),e.setAttribute("src",o),s.startTime&&(((r=ve.get(e))!=null?r:{}).startTime=s.startTime,e.addEventListener("durationchange",Wh,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Yh),e.addEventListener("error",vl),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(m=>{m.remove()})},{once:!0}),Ie(e,"pause",u),Ie(e,"seeked",u),Ie(e,"play",()=>{e.ended||Bh(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else if(t&&o){t.once(se.Events.LEVEL_LOADED,(p,g)=>{aT(g.details,e,t),h(),fn(e)===qe.LIVE&&!Number.isFinite(e.duration)&&(t.on(se.Events.LEVEL_UPDATED,h),Ie(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(se.Events.LEVELS_UPDATED,h)}))});let f=(n=s.maxReconnectRetries)!=null?n:0,m=f>0?XE({hls:t,mediaEl:e,src:o,muxMediaState:ve,saveAndDispatchError:Ot,maxRetries:f}):void 0;t.on(se.Events.ERROR,(p,g)=>{var v,T;let E=xT(g,s);if(E.muxCode===ue.NETWORK_NOT_READY){let _=(v=ve.get(e))!=null?v:{},b=(T=_.retryCount)!=null?T:0;if(b<6){let x=b===0?5e3:6e4,S=new q(`Retrying in ${x/1e3} seconds...`,E.code,E.fatal);Object.assign(S,E),Ot(e,S);let R=setTimeout(()=>{_.retryCount=b+1,g.details==="manifestLoadError"&&g.url&&t.loadSource(g.url)},x);e.addEventListener("teardown",()=>clearTimeout(R),{once:!0});return}else{_.retryCount=0;let x=new q("Network error, try reloading.",E.code,E.fatal);Object.assign(x,E),x.reload=!0,Ot(e,x);return}}m!=null&&m.handleHlsError(g,E)||Ot(e,E)}),t.on(se.Events.MANIFEST_LOADED,()=>{m==null||m.onManifestLoaded();let p=ve.get(e);p!=null&&p.networkError||p&&p.error&&(p.error=null,p.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",vl),Ie(e,"waiting",u),OE(s,t),ME(e,t),t.attachMedia(e)}else console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Wh(s){var e;let t=s.target,i=(e=ve.get(t))==null?void 0:e.startTime;if(i&&vE(t.seekable,t.duration,i)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=i,r&&(t.preload="auto")}}async function Yh(s){if(!s.isTrusted)return;s.stopImmediatePropagation();let e=s.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,r=new q(t,i);if(e.src&&i===q.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Dl(e))!=null?n:e.error;(a==null?void 0:a.code)===q.MEDIA_ERR_SRC_NOT_SUPPORTED&&Ot(e,r)},500);return}if(e.src&&(i!==q.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}Ot(e,r)}function Ot(s,e){var t;e.fatal&&(((t=ve.get(s))!=null?t:{}).error=e,s.dispatchEvent(new CustomEvent("error",{detail:e})))}function vl(s){var e,t;if(!(s instanceof CustomEvent)||!(s.detail instanceof q))return;let i=s.target,r=s.detail;!r||!r.fatal||(((e=ve.get(i))!=null?e:{}).error=r,(t=i.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var xT=(s,e)=>{var t,i,r;s.fatal?console.error("getErrorFromHlsErrorData()",s):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",s);let n={[se.ErrorTypes.NETWORK_ERROR]:q.MEDIA_ERR_NETWORK,[se.ErrorTypes.MEDIA_ERROR]:q.MEDIA_ERR_DECODE,[se.ErrorTypes.KEY_SYSTEM_ERROR]:q.MEDIA_ERR_ENCRYPTED},a=d=>[se.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,se.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(d.details)?q.MEDIA_ERR_NETWORK:n[d.type],o=d=>{if(d.type===se.ErrorTypes.KEY_SYSTEM_ERROR)return ye.DRM;if(d.type===se.ErrorTypes.NETWORK_ERROR)return ye.VIDEO},l,u=a(s);if(u===q.MEDIA_ERR_NETWORK&&s.response){let d=(t=o(s))!=null?t:ye.VIDEO;l=(i=hn(s.response,d,e,s.fatal))!=null?i:new q("",u,s.fatal)}else if(u===q.MEDIA_ERR_ENCRYPTED)if(s.details===se.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let d=le("Attempting to play DRM-protected content without providing a DRM token.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_MISSING_TOKEN}else if(s.details===se.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let d=le("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(s.details===se.ErrorDetails.KEY_SYSTEM_NO_SESSION){let d=le("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(s.details===se.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let d=le("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(s.details===se.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let d=le("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(s.details===se.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let d=le("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_CDM_ERROR}else if(s.details===se.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let d=le("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new q(d,q.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_OUTPUT_RESTRICTED}else l=new q(s.error.message,q.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=ye.DRM,l.muxCode=ue.ENCRYPTED_ERROR;else l=new q("",u,s.fatal);return l.context||(l.context=`${s.url?`url: ${s.url}
|
|
53
|
+
`),u=[],d=e?fE(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,g=!1,m,p=!0;o.oncue=function(y){let T=t[i],v=t.ccOffset,_=(h-d)/9e4;if(g){if(T!=null&&T.new&&(v=t.ccOffset=T.start),_){if(!e){m=new Error(wc+"MPEGTS");return}v=_-t.presentationOffset}}else if(e)v=-e.baseTime/e.timescale;else{m=new Error(wc+"without X-TIMESTAMP-MAP");return}let S=y.endTime-y.startTime,A=mt((y.startTime+v-f)*9e4,r*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+S,0);let b=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(b)),y.id?i&&(y.id=`hlsjscc${i}_${y.id}`):y.id=iu(y.startTime,y.endTime,b),y.endTime>0&&u.push(y)},o.onparsingerror=function(y){m=y},o.onflush=function(){if(m){a(m);return}n(u)},l.forEach(y=>{if(p)if(y.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,y.slice(16).split(",").forEach(T=>{T.startsWith("LOCAL:")?c=T.slice(6):T.startsWith("MPEGTS:")&&(h=parseInt(T.slice(7)))});try{f=BT(c)/1e3}catch(T){m=T}return}else y===""&&(p=!1);o.parse(y+`
|
|
54
|
+
`)}),o.flush()}var ol="stpp.ttml.im1t",Df=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,kf=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,$T={left:"start",center:"center",right:"end",start:"start",end:"end"};function Oc(s,e,t,i){let r=ne(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>pt(o)),a=hE(e.baseTime,1,e.timescale);try{n.forEach(o=>t(GT(o,a)))}catch(o){i(o)}}function GT(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((c,h)=>(c[h]=r.getAttribute(`ttp:${h}`)||n[h],c),{});!r.getAttribute("ttp:tickRate")&&r.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));let o=r.getAttribute("xml:space")!=="preserve",l=Mc(io(r,"styling","style")),u=Mc(io(r,"layout","region")),d=io(r,"body","[begin]");return[].map.call(d,c=>{let h=Pf(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=ro(c.getAttribute("begin"),a),g=ro(c.getAttribute("dur"),a),m=ro(c.getAttribute("end"),a);if(f===null)throw Nc(c);if(m===null){if(g===null)throw Nc(c);m=f+g}let p=new tu(f-e,m-e,h);p.id=iu(p.startTime,p.endTime,p.text);let y=u[c.getAttribute("region")],T=l[c.getAttribute("style")],v=KT(y,T,l),{textAlign:_}=v;if(_){let S=$T[_];S&&(p.lineAlign=S),p.align=_}return Re(p,v),p}).filter(c=>c!==null)}function io(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Mc(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Pf(s,e){return[].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
|
|
55
|
+
`:(n=i.childNodes)!=null&&n.length?Pf(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function KT(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let u=so(e,i,l)||so(s,i,l)||so(r,i,l);return u&&(o[l]=u),o},{})}function so(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Nc(s){return new Error(`Could not parse ttml timestamp ${s}`)}function ro(s,e){if(!s)return null;let t=xf(s);return t===null&&(Df.test(s)?t=VT(s,e):kf.test(s)&&(t=HT(s,e))),t}function VT(s,e){let t=Df.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 HT(s,e){let t=kf.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}function su(s,e,t,i="",r="disabled"){let n=s.ownerDocument.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=r,s.appendChild(n),n}function qT(s){return s.forced&&Nv()?"forced":s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function ll(s,e){let 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){Te.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r)}catch(r){Te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(s.mode=t)}function ul(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=YT(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a])}r==="disabled"&&(s.mode=r)}function WT(s,e){if(e<=s[0].startTime)return 0;let t=s.length-1;if(e>s[t].endTime)return-1;let i=0,r=t,n;for(;i<=r;)if(n=Math.floor((r+i)/2),e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n;return s[i].startTime-e<e-s[r].startTime?i:r}function YT(s,e,t){let i=[],r=WT(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){let o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}var dl=class extends lr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,i=!1;if(this.currentTrack){var r;let o=(r=this.currentTrack.trackNode)==null?void 0:r.track.mode;o==="showing"?(t=this.trackId,i=!0):o==="hidden"&&(t=this.trackId)}if(!i)for(let o=0;o<this.tracksInGroup.length;o++){var n;let l=(n=this.tracksInGroup[o].trackNode)==null?void 0:n.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(i=>{i.trackNode||(i.trackNode=su(this.media,qT(i),i.name,i.lang))});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;(t==null?void 0:t.mode)==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){let i=t.media;this.media=i;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(n=>{let a=n.trackNode;a&&(a.track.mode="hidden",a.remove(),n.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} 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){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=i;let a=[];if(this.tracks.forEach(d=>{(d.textCodec===ol?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(d.groupId)>-1?(d.id=a.length,a.push(d)):d.trackNode&&(d.trackNode.remove(),d.trackNode=void 0))}),a.length===this.tracksInGroup.length){let d=!1;for(let c=0;c<a.length;c++)if(a[c]!==this.tracksInGroup[c]){d=!0;break}if(!d)return}a.length&&this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let d=Ht(o,a);if(d>-1)n=a[d];else{let c=Ht(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,u),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||Vi(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(ur(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(ur(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===de.SUBTITLE_TRACK&&t.context.id===this.trackId&&tr(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&Vi(e,i))return i;let r=Ht(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),n}else{if(i)return null;{let n=Ht(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",r=t.trackNode.track;r.mode!==i&&(r.mode=i)}})}setSubtitleTrack(e,t=!1){let i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!H(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,n=i[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){r&&this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!n.details&&!n.details.live;if(n===r&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));let{id:o,groupId:l="",name:u,type:d,url:c}=n;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:u,type:d,url:c});let h=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(h)}},an=2,jT=100,cl=class extends vn{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(jT),this.mediaSource=t.mediaSource;let i=this.media=t.media;be(i,"playing",this.onMediaPlaying),be(i,"waiting",this.onMediaWaiting),be(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(Se(i,"playing",this.onMediaPlaying),Se(i,"waiting",this.onMediaWaiting),Se(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,u=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&this.stallResolved(e);return}if(d){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!oe.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let c=oe.bufferInfo(a,e,0),h=this.fragmentTracker;h&&this.hls&&Uc(c,e,h,this.hls);let f=c.nextStart||0;if(o&&h&&this.hls){let A=Fc(this.hls.inFlightFragments,e),b=c.len>an,x=!f||A||f-e>an&&!h.getPartialFragment(e);if(b||x)return;this.moved=!1}let g=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&h){if(!(c.len>0)&&!f)return;let b=Math.max(f,c.start||0)-e,L=!!(g!=null&&g.live)?g.targetduration*2:an,R=Ks(e,h);if(b>0&&(b<=L||R)){a.paused||this._trySkipBufferHole(R);return}}let m=n.detectStallWithCurrentTimeMs,p=self.performance.now(),y=this.waiting,T=this.stalled;if(T===null)if(y>0&&p-y<m)T=this.stalled=y;else{this.stalled=p;return}let v=p-T;if(!o&&(v>=m||y&&this.moved)&&this.hls){var _;if(((_=this.mediaSource)==null?void 0:_.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==e){let A=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${A} > ${e}`);return}}let S=oe.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(S,v,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&r&&r.length>1&&e>r.end(0)){let n=oe.bufferedInfo(oe.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=oe.timeRangesToArray(r),o=oe.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=oe.bufferedInfo(a,e,0).bufferedIndex,u=a[o].end,d=a[o+1].start;if((l===-1||l>o)&&d-u<1&&e-u<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${d} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=Ks(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=oe.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let u=(n=this.hls)==null?void 0:n.latestLevelDetails,d=Ks(i,a);if((d||u!=null&&u.live&&i<u.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let n=i.getFragAtPos(t,j.MAIN),a=i.getFragAtPos(r,j.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:n}=this;if(!r&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ke(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:i,hls:r}=this,n=r==null?void 0:r.config;if(!i||!t||!n)return 0;let a=i.currentTime,o=oe.bufferInfo(i,a,0);Uc(o,a,t,r);let l=a<o.start?o.start:o.nextStart;if(l){let d=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&i.readyState<3,h=l-a;if(h>0&&(d||c)){if(h>n.maxBufferHole){let y=!1;if(a===0){let T=t.getAppendedFrag(0,j.MAIN);T&&l<T.end&&(y=!0)}if(!y&&e){var u;if(!((u=r.loadLevelObj)!=null&&u.details)||Fc(r.inFlightFragments,l))return 0;let v=!1,_=e.end;for(;_<l;){let S=Ks(_,t),A=S?S.duration:0;if(A>0)_+=A;else{v=!0;break}}if(v)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:g}=n,m=++this.skipRetry>f,p=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,i.currentTime=p),!(e!=null&&e.gap)||m){let y=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),T={type:Q.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:m,error:y,reason:y.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?T.part=e:T.frag=e),r.trigger(E.ERROR,T)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Fc(s,e){let t=Bc(s.main);if(t&&t.start<=e)return t;let i=Bc(s.audio);return i&&i.start<=e?i:null}function Bc(s){if(!s)return null;switch(s.state){case O.IDLE:case O.STOPPED:case O.ENDED:case O.ERROR:return null}return s.frag}function Ks(s,e){return e.getAppendedFrag(s,j.MAIN)||e.getPartialFragment(s)}function Uc(s,e,t,i){let r=i.latestLevelDetails,n=Ks(e,t);if(bn(i.config)&&!s.nextStart&&r&&n&&i.interstitialsManager){let a="type"in n?n:n.fragment,o=Ih(r,a.sn);(o==null?void 0:o.level)===a.level&&Kh(o,i.interstitialsManager.playerQueue,e)&&(s.nextStart=o.start)}}var zT=.25;function hl(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function no(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r)}catch{n=new s(e,t,ke(r?J({type:r},i):i))}return n}var Jr=(()=>{let s=hl();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),fl=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return su(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=hl();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===nt.emsg&&!i||!r)continue;let u=ih(n[o].data),d=n[o].pts,c=d+n[o].duration;c>Jr&&(c=Jr),c-d<=0&&(c=d+zT);for(let f=0;f<u.length;f++){let g=u[f];if(!sh(g)){this.updateId3CueEnds(d,l);let m=no(a,d,c,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var i;let r=(i=this.id3Track)==null?void 0:i.track.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===Jr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let u;r==="audio"?u=d=>d.type===nt.audioId3&&l:r==="video"?u=d=>d.type===nt.emsg&&o:u=d=>d.type===nt.audioId3&&l||d.type===nt.emsg&&o,ul(n.track,t,i,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=hl();if(i&&r&&!a){let{fragmentStart:m,fragmentEnd:p}=e,y=this.assetCue;y?(y.startTime=m,y.endTime=p):o&&(y=this.assetCue=no(o,m,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),y&&(y.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(y),y.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:u}=e,d=Object.keys(u),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.track.cues)!=null&&h.length){let m=Object.keys(c).filter(p=>d.indexOf(p)===-1);for(let p=m.length;p--;){var f;let y=m[p],T=(f=c[y])==null?void 0:f.cues;delete c[y],T&&Object.keys(T).forEach(v=>{let _=T[v];if(_){_.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(_)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(d.length===0||!H(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<d.length;m++){let p=d[m],y=u[p],T=y.startTime,v=c[p],_=(v==null?void 0:v.cues)||{},S=(v==null?void 0:v.durationKnown)||!1,A=Jr,{duration:b,endDate:x}=y;if(x&&b!==null)A=T+b,S=!0;else if(y.endOnNext&&!S){let R=d.reduce((I,P)=>{if(P!==y.id){let w=u[P];if(w.class===y.class&&w.startDate>y.startDate&&(!I||y.startDate<I.startDate))return w}return I},null);R&&(A=R.startTime,S=!0)}let L=Object.keys(y.attr);for(let R=0;R<L.length;R++){let I=L[R];if(!my(I))continue;let P=_[I];if(P)S&&!(v!=null&&v.durationKnown)?P.endTime=A:Math.abs(P.startTime-T)>.01&&(P.startTime=T,P.endTime=A);else if(o){let w=y.attr[I];py(I)&&(w=rh(w));let U=no(o,T,A,{key:I,data:w},nt.dateRange);U&&(U.id=p,this.id3Track.track.addCue(U),_[I]=U,a&&(I==="X-ASSET-LIST"||I==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}c[p]={cues:_,dateRange:y,durationKnown:S}}}}};function Cf(){return self.SourceBuffer||self.WebKitSourceBuffer}function wf(){if(!pi())return!1;let e=Cf();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function XT(){if(!wf())return!1;let s=pi();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(er(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(er(e,"audio"))))}function QT(){var s;let e=Cf();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var $t={DISABLED:0,SWITCHING:1,SWITCHED:2},JT=100,On=class extends rr{constructor(e,t,i){super(e,t,i,"stream-controller",j.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=$t.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!H(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,j.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${n} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(JT),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=O.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case O.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e==null?void 0:e[t],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=O.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=O.IDLE;break}break}case O.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===O.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let m={type:this.targetBufferType()};this.hls.trigger(E.BUFFER_EOS,m),this.state=O.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let u=a.details;if(!u||this.state===O.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=O.WAITING_LEVEL,this.startFragRequested=!1;return}let d=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ne(f)&&this.fragmentTracker.getState(f)!==Me.OK){var g;let p=((g=this.backtrackFragment)!=null?g:f).sn-u.startSN,y=u.fragments[p-1];y&&f.cc===y.cc&&(f=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?Le.AUDIO:Le.VIDEO,y=(p===Le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p)}f=this.getNextFragmentLoopLoading(f,u,o,j.MAIN,c)}f&&(this.exceedsMaxBuffer(o,c,f)||this.loadFragment(f,a,h))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===Me.NOT_LOADED||r===Me.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==$t.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===$t.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying;if(i){let r=i.level;this.hls.trigger(E.FRAG_CHANGED,{frag:i,previousFrag:e}),(e==null?void 0:e.level)!==r&&this.hls.trigger(E.LEVEL_SWITCHED,{level:r})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===$t.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;be(i,"playing",this.onMediaPlaying),be(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(Se(i,"playing",this.onMediaPlaying),Se(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=$t.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&r&&!QT(),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){let{levels:i}=this;if(!i||this.state!==O.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let u=t.levelInfo,d=this.fragCurrent;d&&(this.state===O.FRAG_LOADING||this.state===O.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||(i=u.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,n||this.setStartPosition(o,c),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===O.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=O.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){let d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${n} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r}`),this.config.liveSyncMode==="buffered"){var u;let c=oe.bufferInfo(i,r,0);if(!((u=c.buffered)!=null&&u.length)){i.currentTime=r;return}if(c.start<=n){i.currentTime=r;return}let{nextStart:f}=oe.bufferedInfo(c.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=r}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=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}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let 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}let u=o.videoCodec,d=l.PTSKnown||!l.live,c=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Cn(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,m=g!==-1,{decryptRange:p,byteRange:y}=pn(i,r,this.iframesOnly),T=new sr(i.level,i.sn,i.stats.chunkCount,y?y.end-y.start:n.byteLength,g,m,i.duration,this.iframesOnly,p),v=this.initPTS[i.cc];f.push(n,c,h,u,i,r,l.totalduration,d,T,v)}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio!==$t.DISABLED;if(gn(t.url,i))this.altAudio=$t.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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();if(r){this.altAudio=$t.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),i.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=gn(t.url,this.hls);if(i){let 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=i?$t.SWITCHED:$t.DISABLED,this.tick()}onBufferCreated(e,t){let i=t.tracks,r,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t,n=i.type===j.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}let l=!1;if(Ne(i)&&(l=!!i.gap&&!i.tagList.some(u=>u[0]==="GAP")),this.fragBufferedComplete(i,r),l){var a;i.stats.retry++;let u=(a=this.levels)==null?void 0:a[i.level];u&&u.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&oe.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,t);break;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===de.LEVEL&&(this.state=O.IDLE);break;case k.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case k.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=O.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Le.AUDIO||!this.altAudio){let i=(t===Le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let n=this.getLevelDetails(),a=oe.getBuffered(e),o=a.length?a.start(0):0,l=o-i,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<u||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:r}=this,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=O.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(E.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:u}=a,{video:d,text:c,id3:h,initSegment:f}=r,{details:g}=u,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=O.PARSING,f){let p=f.tracks;if(p){let _=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(u,p,_,n),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:_,id:t,tracks:p})}let y=f.initPTS,T=f.timescale,v=this.initPTS[o.cc];if(H(y)&&(!v||v.baseTime!==y||v.timescale!==T)){let _=f.trackId;this.initPTS[o.cc]={baseTime:y,timescale:T,trackId:_};let S=this.initPTS.slice(0);i.trigger(E.INIT_PTS_FOUND,{timestampOffsets:S,frag:o,id:t,initPTS:y,timescale:T,trackId:_})}}if(d&&g){m&&d.type==="audiovideo"&&this.logMuxedErr(o);let p=g.fragments[o.sn-1-g.startSN],y=o.sn===g.startSN,T=!p||o.cc>p.cc;if(r.independent!==!1){let{startPTS:v,endPTS:_,startDTS:S,endDTS:A}=d;if(l)l.elementaryStreams[d.type]={startPTS:v,endPTS:_,startDTS:S,endDTS:A};else if(d.firstKeyFrame&&d.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){let b=this.getMainFwdBufferInfo(),x=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,L=d.firstKeyFramePTS?d.firstKeyFramePTS:v;if(!y&&x<L-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,_,o.start,A,!0)}else y&&v-(g.appliedTimelineOffset||0)>an&&(o.gap=!0);o.setElementaryStreamInfo(d.type,v,_,S,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,y||T)}else if(y||T)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:p,endPTS:y,startDTS:T,endDTS:v}=m;l&&(l.elementaryStreams[Le.AUDIO]={startPTS:p,endPTS:y,startDTS:T,endDTS:v}),o.setElementaryStreamInfo(Le.AUDIO,p,y,T,v),this.bufferFragmentData(m,o,l,n)}if(g&&h!=null&&h.samples.length){let p={id:t,frag:o,details:g,samples:h.samples};i.trigger(E.FRAG_PARSING_METADATA,p)}if(g&&c){let p={id:t,frag:o,details:g,samples:c.samples};i.trigger(E.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${Ne(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let u=e.audioCodec,d=sn(n.codec,u);if(d==="mp4a"&&(d="mp4a.40.5"),this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&!Mv()&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&Fv()&&n.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),u&&u!==d&&this.log(`Swapping manifest audio codec "${u}" for "${d}"`),n.levelCodec=d,n.id=j.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${d||""}/${u||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=j.MAIN;let u=a.codec;if((u==null?void 0:u.length)===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;l.forEach(u=>{let c=t[u].initSegment;c!=null&&c.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:u,data:c,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,j.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return H(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(H(t)){let i=this.getLevelDetails(),r=this.currentFrag||(i?ms(null,i.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Mn=class extends On{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:i}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case O.STOPPED:case O.ENDED:case O.ERROR:this.state=O.IDLE}this.state===O.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(E.BUFFERED_TO_END,this.onBufferedToEnd);let n=this.media;i&&n&&this.seekTo(r)&&(this.currentOp=[r,t],this.nextOp=void 0,this.flushPipeline(r,!0))}seekTo(e){let t=this.media;if(t){var i;let r=(i=this.getLevelDetails())==null?void 0:i.edge,n=r!==void 0?r:t.duration;if(e>=n&&(e=n-.01),oe.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,j.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&i.length>1;){let n=i.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=i.filter(a=>!!a.data),this.cachedSize=i.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:i,payload:r}=e;this.cacheFragmentData&&!i&&r!=null&&r.byteLength&&!t.data&&Ne(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if((r===Me.NOT_LOADED||r===Me.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let i=e.decryptdata;return(i==null?void 0:i.keyFormat)!=="identity"||!!i.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let i=e.stats=new js;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=O.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(E.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:i,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=O.STOPPED,i!=null&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!r),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Sn(oe.getBuffered(this.media)):"none"}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let i=this.media;if(i){let r=oe.bufferInfo(i,e,0),n=r.len?r.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,j.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(E.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(E.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,j.MAIN);return!!(t!=null&&t.endList)}},gl=class extends Mn{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let i=(t=this._img)==null?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case O.STOPPED:case O.ENDED:case O.ERROR:this.state=O.IDLE}if(this.state===O.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===O.IDLE){let i=this.getBufferedAt(e);i&&(this.fragCurrent=i,this.updateImage(i,null))}}else{let i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){let r=e.data;r||this.fragmentTracker.removeFragment(e);let n=this._img;if(n&&r){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,n.onload=()=>{if(!this.hls)return;let d=this.hls.levels[e.level];d!=null&&d.fragmentError&&(d.fragmentError=0,e.stats.retry=0);let c=self.performance.now(),h=t?t.stats:e.stats;h.buffering.end=e.stats.buffering.end=c,this.hls.trigger(E.FRAG_BUFFERED,{frag:e,part:t,stats:h,id:e.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",e,t,i)};let l=n.src;l&&self.URL.revokeObjectURL(l);let u=new Blob([r],{type:"image/jpeg"});n.src=self.URL.createObjectURL(u)}else this.state=O.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,r){if(!this.hls)return;let n=new Error(e);this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:i,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,i,r){super.bufferFragmentData(e,t,i,r,!0);let n=ne(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,i,r);return}let a=t;this.cacheSet(a,n[0]),this.updateImage(a,i,r)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){let i=this.getAppendedFrag(t);if(i&&!Gs(i,this.fragPlaying))return this.fragPlaying=i,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},ZT=10,e_="Image I-Frame player does not accept HTMLMediaElements",$c={seekOnAppend:!0},Zr,ao,ml=class extends at{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Zr||(Zr=t_(t)),ao||(ao=i_(Zr)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(E.MANIFEST_LOADING,this.clearAsset,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.clearAsset,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;let r=(i=this.hls)==null?void 0:i.pathwayPriority;t.length&&r&&this.iframeInstances.forEach(n=>{n.pathwayPriority=r})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===j.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;let r=this.hls;r&&r.hasEnoughToStart&&(((i=r.mainForwardBufferInfo)==null?void 0:i.len)||0)>ZT&&this.iframeInstances.forEach(n=>{if(!n.loadingEnabled){var a;n.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Zr,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let i=(t=this.hls)==null?void 0:t.iframeVariants.filter(r=>r.imageCodec);return this.createInstance(ao,i,e,"image-")}createInstance(e,t,i,r){let{hls:n}=this;if(!n)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:u,loadLevel:d,bandwidthEstimate:c,sessionId:h}=n,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${r||""}iframe-player-${this.instanceCounter++}`,p=n.levels,y=u||p[d],T=Ah(y,o.videoPreference),v=(y==null?void 0:y.pathwayId)||".",_=J(J({},o),{},{loggerId:m,primarySessionId:h,videoPreference:T,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),S=new e(_,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(A=>!A.url),this.iframeInstances.push(S),S.trigger(E.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:v},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),S}};function t_(s){return class extends s{constructor(t,i,r,n){t.streamController||(t.streamController=Mn),super(t),this._url=i,this.streamController.setInitPts(r),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,i=$c){if(t<0)return;let r=J(J({},$c),i);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,r)}}}function i_(s){return class extends s{constructor(t,i,r,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=gl),t.capLevelController=void 0,t.bufferController=void 0,super(t,i,r,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(e_)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var mi=.025,Nn=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function s_(s,e,t){return`${s.identifier}-${t+1}-${Ws(e)}`}var pl=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return Gc(t,e)?on(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=on(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=H(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return Gc(t,e)?on(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<mi))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Nn.Range:Nn.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return r_(this)}};function on(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<mi)?e.start:e.start+e.duration}function Gc(s,e){return e>s.start-mi&&e<s.start+s.duration+mi}function Of(s,e,t){let i=new self.URL(s,t);return i.protocol!=="data:"&&gi(i,"_HLS_primary_id",e),i}function oo(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function r_(s){return`["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function us(s){let e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var vl=class{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=!0};n.once(E.LEVEL_LOADED,a),n.once(E.AUDIO_TRACK_LOADED,a),n.once(E.SUBTITLE_TRACK_LOADED,a),n.on(E.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(E.BUFFER_APPENDED,()=>{let d=this.bufferedEnd;this.reachedPlayout(d)&&(this._bufferedEosTime=d,n.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Of(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if((i=this.hls)!=null&&i.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=oe.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=oe.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,i){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,i){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${us(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},lo=.033,yl=class extends at{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=r[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let n=i[r];t&&t!=="primary"&&(n=n[t]);let a=n.start,o=i[r].event,l=o!=null&&o.cue.pre?o.duration:n.end;if(e===a||e>a&&e<l)return r}return-1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let n=i[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if(((i=t[r].event)==null?void 0:i.identifier)===e)return r}return-1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let n=0;n<r;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t,i=0){let r=e.main.details,{dateRanges:n}=r,a=this.events,o=this.parseDateRanges(n,{url:r.url},t),l=Object.keys(n),u=a?a.filter(d=>l.indexOf(d.identifier)===-1):[];o.length&&o.sort((d,c)=>{let h=d.cue.pre,f=d.cue.post,g=c.cue.pre,m=c.cue.post;if(h&&!g)return-1;if(g&&!h||f&&!m)return 1;if(m&&!f)return-1;if(!h&&!g&&!f&&!m){let p=d.startTime,y=c.startTime;if(p!==y)return p-y}return d.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=o,u.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,u,i)}updateSchedule(e,t=[],i=0,r=!1){let n=this.events||[];if(n.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(n,e,i);(r||t.length||(a==null?void 0:a.length)!==o.length||o.some((u,d)=>Math.abs(u.playout.start-a[d].playout.start)>.005||Math.abs(u.playout.end-a[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let u=this.eventMap[o];u?u.setDateRange(l):(u=new pl(l,t),this.eventMap[o]=u,i===!1&&(u.appendInPlace=i)),r.push(u)}}return r}parseSchedule(e,t,i=0){let r=[],n=t.main.details,a=n.live?1/0:n.edge,o=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,d=0;if(e.forEach((c,h)=>{let f=c.cue.pre,g=c.cue.post,m=e[h-1]||null,p=c.appendInPlace,y=g?a:c.startOffset,T=c.duration,v=c.timelineOccupancy===Nn.Range?T:0,_=f&&n.live?i+(c.resumeOffset||0):0,S=_||c.resumptionOffset,A=(m==null?void 0:m.startTime)===y,b=y+c.cumulativeDuration,x=p?b+T:y+S;if(f||!g&&y<=0){let R=d;d+=v,c.timelineStart=b;let I=o;o+=T,r.push({event:c,start:b,end:x,playout:{start:I,end:o},integrated:{start:R,end:d}})}else if(y<=a){if(!A){let P=y-u;if(P>lo){let w=u,B=d;d+=P;let U=o;o+=P;let C={previousEvent:e[h-1]||null,nextEvent:c,start:w,end:w+P,playout:{start:U,end:o},integrated:{start:B,end:d}};r.push(C)}else P>0&&m&&(m.cumulativeDuration+=P,r[r.length-1].end=y)}g&&(x=b),c.timelineStart=b;let R=d;d+=v;let I=o;o+=T,r.push({event:c,start:b,end:x,playout:{start:I,end:o},integrated:{start:R,end:d}})}else return;let L=_||c.resumeTime;g||L>a?u=a:!f&&x&&c.appendInPlaceStarted&&L-x>lo?u=x:u=L}),u<a){var l;let c=u,h=d,f=a-u;d+=f;let g=o;o+=f,r.push({previousEvent:((l=r[r.length-1])==null?void 0:l.event)||null,nextEvent:null,start:u,end:c+f,playout:{start:g,end:o},integrated:{start:h,end:d}})}this.setDurations(a,o,d)}else r.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return r}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let u=o.cue.pre,d=o.cue.post,c=u?0:d?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=ms(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<lo&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=H(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>mi?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;let u=ms(null,o.fragments,i);if(!u)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let d=a==="audio"?.175:0;return Math.abs(u.start-i)<mi+d||Math.abs(u.end-i)<mi+d?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${u.start}-${u.end} sn: ${u.sn} cc: ${u.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let u=o.error?0:o.duration||0;i+=u}r&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function ft(s){return`[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}var El=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i=e.assetListUrl,r;try{r=Of(i,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,k.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(E.ERROR,f);return}t&&r.protocol!=="data:"&&gi(r,"_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={type:de.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},u=n.interstitialAssetListLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,g,m)=>{let p=h.data,y=p==null?void 0:p.ASSETS;if(!Array.isArray(y)){let T=this.assignAssetListError(e,k.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(E.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:m})},onError:(h,f,g,m)=>{let p=this.assignAssetListError(e,k.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,m,g);this.hls.trigger(E.ERROR,p)},onTimeout:(h,f,g)=>{let m=this.assignAssetListError(e,k.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,g);this.hls.trigger(E.ERROR,m)}};return o.load(l,d,c),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,r,n,a){return e.error=i,{type:Q.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}};function Kc(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function $i(s,e){return`[${s}] Advancing timeline position to ${e}`}var Tl=class extends at{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(i);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){let m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}let u=this.playingAsset;if(!u){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}let d=u.timelineStart,c=u.duration||0;if(a&&i<d||i>=d+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,u)}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(i>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],u=n.durations,d=i.map(m=>m.identifier),c=!!(o.length||d.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
56
|
+
Schedule: ${l.map(m=>ft(m))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);let g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),i.forEach(m=>{m.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){let p=m.assetItem.timelineStart,y=m.timelineOffset-p;if(y)try{m.timelineOffset=p}catch(T){Math.abs(y)>mi&&this.warn(`${T} ("${m.assetId}" ${m.timelineOffset}->${p})`)}}}),c||r){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:u,removedIds:d}),this.isInterstitial(a)&&d.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),g&&f!==h&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new El(e),this.schedule=new yl(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Se(e,"play",this.onPlay),Se(e,"pause",this.onPause),Se(e,"seeking",this.onSeeking),Se(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;be(i,"seeking",this.onSeeking),be(i,"timeupdate",this.onTimeupdate),be(i,"play",this.onPlay),be(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,g,m)=>{if(c){let p=c[h].start,y=c.event;if(y){if(h==="playout"||y.timelineOccupancy!==Nn.Point){let T=i(f);(T==null?void 0:T.interstitial)===y&&(p+=T.assetItem.startOffset+T[m])}}else{let T=g==="bufferedPos"?a():e[g];p+=T-c.start}return p}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let m=e.schedule.findItemIndexAtTime(c),p=(g=e.schedule.items)==null?void 0:g[m];if(p){let y=p[h].start-p.start;return c+y}}return c},a=()=>{let c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,g;let m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);let p=e.effectivePlayingItem,y=e.schedule.findItemIndexAtTime(c,h),T=(g=e.schedule.items)==null?void 0:g[y],v=e.getBufferingPlayer(),_=v==null?void 0:v.interstitial,S=_==null?void 0:_.appendInPlace,A=p&&e.itemsMatch(p,T);if(p&&(S||A)){let b=i(e.playingAsset),x=(b==null?void 0:b.media)||e.primaryMedia;if(x){let L=h==="primary"?x.currentTime:r(p,h,e.playingAsset,"timelinePos","currentTime"),R=c-L,I=(S?L:x.currentTime)+R;if(I>=0&&(!b||S||I<=b.duration)){x.currentTime=I;return}}}if(T){let b=c;if(h!=="primary"){let L=T[h].start,R=c-L;b=T.start+R}let x=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(x||T.event.appendInPlace)){let L=e.media||(S?v==null?void 0:v.media:null);L&&(L.currentTime=b)}else if(p){let L=e.findItemIndex(p);if(y>L){let I=e.schedule.findJumpRestrictedIndex(L+1,y);if(I>L){e.setSchedulePosition(I);return}}let R=0;if(x)e.timelinePos=b,e.checkBuffer();else{let I=T.event.assetList,P=c-(T[h]||T).start;for(let w=I.length;w--;){let B=I[w];if(B.duration&&P>=B.startOffset&&P<B.startOffset+B.duration){R=w;break}}}e.setSchedulePosition(y,R)}}},u=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},d={get bufferedEnd(){let c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let c=u(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=u(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=u();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=u())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=u())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return u()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return u()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){let c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){return n(e.seekableStart,"integrated")}},skip:()=>{let c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(c);if(h.appendInPlace){let g=c.playout.start+c.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!H(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ke(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,u=(i=this.detachedData)==null?void 0:i.mediaSource,d;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),d="Primary";else{let g=this.getBufferingPlayer();g?(n=g.transferMedia(),this.detachedData=n,d=`${g}`):u?d="detached MediaSource":d="detached media"}if(!n){if(u)n=this.detachedData,this.log(`using detachedData: MediaSource ${ke(n)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){let p=m.interstitial;this.clearInterstitial(m.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed";if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`),!c&&!o){e.attachMedia(t);return}let h=c&&n?J({},n):{media:t},f=this.schedule;if(f&&o){let g=e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!c&&l){let g=e,m=g.assetItem.timelineStart;if(m){let p=g.hls,y=Math.max(this.timelinePos-m,Number.EPSILON);p.startPosition!==y&&(this.log(`Set ${g} startPosition: ${y}`),p.config.startPosition=y,p.loadingEnabled&&p.startLoad(y))}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=i.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log($i("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log($i("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else i.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log($i("checkStart (playing item)",n.start));let a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),n=oo(i,r);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!H(e.resumeOffset)&&this.hls){let i=this.getLiveStartPos();if(t){let r=this.getBufferingPlayer(),n=r!=null&&r.interstitial.cue.pre?r.remaining:0;return i+n}return i}}getNextItemIndex(e,t){if(this.schedule){let i=this.livePrerollResumption(e.event,t);if(i!==void 0)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){let r=oo(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=n[t],o=a.event?this.getNextItemIndex(a):t+1,l=n.length;if(o>=l){this.setSchedulePosition(-1);return}let u=e.resumeTime;this.timelinePos<u&&(this.log($i("advanceAfterAssetEnded",u)),this.timelinePos=u,e.appendInPlace&&!n[o].event&&this.hls.startLoad(u+.01),this.checkBuffer(this.bufferedPos<u)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,n=i.getEvent(r);if(n){let a=i.findEventIndex(r),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&ft(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let c=a.event,h=this.playingAsset,f=h==null?void 0:h.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,n)||t!==void 0&&f!==c.assetList[t].identifier)){var l;let m=c.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${c.assetList.length} ${us(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:m,event:c,schedule:r.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,n),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${ft(a)}`),c.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once&&this.hls)){var u;this.updateSchedule();let m=(u=this.schedule)==null?void 0:u.items;if(n&&m){let p=this.findItemIndex(n),y=this.livePrerollResumption(c);if(y!==void 0){let T=y,v=this.getNextItemIndex(a);if(!this.isInterstitial(r[v])){var d;let _=(d=this.primaryDetails)==null?void 0:d.fragments;if(c.snapOptions.in&&_){let S=ms(null,_,y);S&&(T=Math.min(Math.max(r[v].start,on(T,S)),r[v].end))}}if(this.log($i("live join (preroll)",T)),this.timelinePos=T,v!==p&&(v||v===0)){this.advanceSchedule(v,m,void 0,a,o);return}}this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,i,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(d=>{let c=d.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let d=o.event;if(i===void 0){i=d.cue.pre?0:a.findAssetIndex(d,this.timelinePos);let g=oo(d,i-1);if(d.isAssetPastPlayoutLimit(g)||d.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(d,e,i);return}i=g}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(d,i);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ft(o)} ${d.appendInPlace?"append in place":""}`),d.hasPlayed=!1,this.hls.trigger(E.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=d.assetList[i];if(!f){this.advanceAfterAssetEnded(d,e,i||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let g=d.assetList.length;this.warn(`asset ${i+1}/${g} player destroyed ${d}`),h=this.createAssetPlayer(d,f,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&Kc(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Kc(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var r,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${ft(e)}`);let a=this.timelinePos;if((r=this.detachedData)!=null&&r.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log($i("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ft(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){let r=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let n=this.endedItem||this.playingItem,a=n!=null&&n.event?this.livePrerollResumption(n.event,i):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:u}=o;if(r<l||r>u&&!i){let d=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${l}-${u}]) snapping to liveSync ${d}`),d||l}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){var e;let t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,r=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||i&&i-t<r?i||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:oe.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log($i("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){let i=this.hls,{loadingEnabled:r,bufferingEnabled:n,startPosition:a}=i,o=i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${r} bufferingEnabled: ${n}`),!t&&o||!r||Math.abs(a-e)>.1){let l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){let u=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${u?ft(u):null}`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else n||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=J(J({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r;let n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace,n===-1?0:n),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;let u=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${u?ft(u):null}`),(u==null?void 0:u.end)===1/0){let c=this.playingItem,h=this.isInterstitial(c)&&c.event.appendInPlace;this.hls.startLoad(Math.max(l,u.start),h)}else{let c=this.getBufferingPlayer();c&&c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(E.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=J(J({},this.altSelection),{},{audio:i});return}let n=J(J({},r),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=J(J({},this.altSelection),{},{subtitles:i});return}let n=J(J({},r),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){let i=Fd(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=Fd(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){let r=t[i];if(r.cue.post){let n=this.getEventItem(r.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let i=e.end+.25,r=oe.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${ft(e)} (was ${ft(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let i=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;let r=this.mediaSelection;if(!r)return;let n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(i=this.schedule)==null||i.updateSchedule(r,[],n,e)}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let r=oe.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}updateBufferedPos(e,t,i){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var u;let d=this.findItemIndex(n),c=Math.min(d+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(u=h.event)!=null&&u.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){let f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>d&&l>o)this.bufferedToItem(h);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:n}=i;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ft(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,c)=>{let h=this.getAssetPlayer(d.identifier);h&&(c===u&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(u=>u.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let r=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(r,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(n,l)}}}}bufferedToEvent(e,t){let i=e.event,r=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(r||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart,u=this.playingItem,d=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,h=0;if((!d||d.interstitial.cue.pre)&&this.primaryLive&&(h=this.getLiveStartPos(),d&&(h+=d.remaining)),h&&!(e.cue.pre||e.cue.post)){let g=h-l;g>0&&(c=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${h?` live-start: ${h} start-offset: ${c} (timeline-start: ${l})`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let f=this.assetListLoader.loadAssetList(e,c);f&&(e.assetListLoader=f)}else if(!a&&r){for(let u=t;u<r;u++){let d=e.assetList[u],c=this.getAssetPlayerQueueIndex(d.identifier);(c===-1||this.playerQueue[c].destroyed)&&!d.error&&this.createAssetPlayer(e,d,u)}let l=e.assetList[t];if(l){let u=this.getAssetPlayer(l.identifier);return u&&u.loadSource(),u}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let i=this.primaryDetails;if(i&&e>=i.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,n,a){let o={parentIdentifier:e.identifier,identifier:s_(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let r=this.hls,n=r.userConfig,a=r.loadLevelObj||r.levels[r.currentLevel],o=Ah(a,n.videoPreference),l=r.audioTracks[r.audioTrack],u=r.subtitleTracks[r.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){let _=this.timelinePos-t.timelineStart;if(_>=0){let S=t.duration;S&&_<S&&(d=_)}}let c=t.identifier,h=J(J({},n),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:u||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=Re({},f,{contentId:Ws(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let g=new vl(this.HlsPlayerClass,h,e,t);this.playerQueue.push(g),e.assetList[i]=t;let m=!0,p=_=>{if(_.live){let b=new Error(`Interstitials MUST be VOD assets ${e}`),x={fatal:!0,type:Q.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},L=this.findEventIndex(e.identifier);this.handleAssetItemError(x,e,L,i,b.message);return}let S=_.edge-_.fragmentStart,A=t.duration;(m||A===null||S>A)&&(m=!1,this.log(`Interstitial asset "${c}" duration change ${A} > ${S}`),t.duration=S,this.updateSchedule())};g.on(E.LEVEL_UPDATED,(_,{details:S})=>p(S)),g.on(E.LEVEL_PTS_UPDATED,(_,{details:S})=>p(S)),g.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let y=(_,S)=>{let A=this.getAssetPlayer(c);if(A&&S.tracks){A.off(E.BUFFER_CODECS,y),A.tracks=S.tracks;let b=this.primaryMedia;this.bufferingAsset===A.assetItem&&b&&!A.media&&this.bufferAssetPlayer(A,b)}};g.on(E.BUFFER_CODECS,y);let T=()=>{let _=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${_}`),!_||!this.schedule)return;let S=this.getEventItem(e.identifier);S&&this.advanceAssetBuffering(S,_.assetItem)};g.on(E.BUFFERED_TO_END,T);let v=_=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let A=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,A,_)};return g.once(E.MEDIA_ENDED,v(i)),g.once(E.PLAYOUT_LIMIT_REACHED,v(1/0)),g.on(E.ERROR,(_,S)=>{if(!this.schedule)return;let A=this.getAssetPlayer(c);if(S.details===k.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(S.details===k.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(S,e,this.findEventIndex(e.identifier),i,`Asset player error ${S.error} ${e}`)}),g.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let S=new Error(`Asset player destroyed unexpectedly ${c}`),A={fatal:!0,type:Q.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(A,e,this.findEventIndex(e.identifier),i,S.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${us(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let r=this.playerQueue[i];this.log(`clear ${r} toSegment: ${t&&ft(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,u=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(d==null?void 0:d.identifier)!==l&&(d&&(this.clearAssetPlayer(d.identifier,i[r]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${u} ${us(o)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;let{interstitial:r,assetItem:n}=e,a=this.getEventItem(r.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,n);return}let o=this.getBufferingPlayer();if(o===e)return;let l=r.appendInPlace;if(l&&(o==null?void 0:o.interstitial.appendInPlace)===!1)return;let u=(o==null?void 0:o.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!Jc(u,e.tracks)){let d=new Error(`Asset ${us(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),c={fatal:!0,type:Q.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},h=r.findAssetIndex(n);this.handleAssetItemError(c,r,this.findEventIndex(r.identifier),h,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,u=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+u} in ${o} ${e} (media.currentTime: ${r})`),l&&(u/i.playbackRate<.5||o.bufferedInPlaceToEnd(i,o.currentTime))&&o.hls){let d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,n)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,r,n){if(e.details===k.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&us(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),u=this.playerQueue[l]||null,d=this.schedule.items,c=Re({},e,{fatal:!1,errorAction:Hs(!0),asset:a,assetListIndex:r,event:t,schedule:d,scheduleIndex:i,player:u});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=r;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):(h==null?void 0:h.identifier)===o?this.advanceAfterAssetEnded(t,i,r):(f==null?void 0:f.identifier)===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,r=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${ft(i)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);let u=this.updateItem(i,o);this.itemsMatch(i,u)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(r))return;let l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,u=n.duration,d=0;o.forEach((g,m)=>{let p=parseFloat(g.DURATION);this.createAsset(n,m,d,l+d,p,g.URI),d+=p}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${u}) ${n}`);let c=this.waitingItem,h=(c==null?void 0:c.event.identifier)===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){let g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((f==null?void 0:f.identifier)===a){let g=n.assetList[0];if(g){let m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){let p=this.primaryMedia;m&&p&&this.bufferAssetPlayer(m,p)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case k.ASSET_LIST_PARSING_ERROR:case k.ASSET_LIST_LOAD_ERROR:case k.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case k.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}let r=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${r==null?void 0:r.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},_l=class{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;let{media:i}=this,r=this.levelDetails;if(!i||!r||!this.hls)return;this.currentTime=i.currentTime;let n=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;let{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=n;if(!o||l===1||!r.live)return;let u=this.targetLatency;if(u===null)return;let d=a-u,c=Math.min(this.maxLatency,u+r.targetduration),h=d<c,f=bn(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(h&&d>.05&&this.forwardBufferLength>1&&!f){let g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20,p=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(i,p)}else i.playbackRate!==1&&i.playbackRate!==0&&this.changeMediaPlaybackRate(i,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:i,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,u=this.hls.userConfig,d=l&&r||i;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||d===0)&&(d=a!==void 0?a:o*n);let c=n;return d+Math.min(this.stallCount*t.liveSyncOnStallIncrease,c)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let i=this.levelDetails;if(i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this),e.on(E.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this),e.off(E.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;let r=this.hls,n=this.media||t.event.appendInPlace&&(r==null||(i=r.interstitialsManager)==null?void 0:i.playerQueue.reduce((a,o)=>a||o.media,null));r&&n&&n.playbackRate>1&&n.playbackRate<=r.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(e,t){var i;t.details===k.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Vc=500,Sl=class extends rr{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",j.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=O.IDLE,this.setInterval(Vc),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,part:r,success:n}=t;if(!n)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,l=(r||i).start;for(let d=0;d<a.length;d++)if(l>=a[d].start&&l<=a[d].end){o=a[d];break}let u=l+(r||i).duration;if(o?o.end=u:(o={start:l,end:u},a.push(o)),!r||u>=i.end){let d=this.fragmentTracker.fragBuffered(i);r&&d&&(d.range.subs={time:[{startPTS:i.start,endPTS:u}],partial:!0}),Ne(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,j.SUBTITLE)}}onError(e,t){let i=t.frag;(i==null?void 0:i.type)===j.SUBTITLE&&(t.details===k.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==O.STOPPED&&(this.state=O.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&rf(this.levels,t)){this.levels=t.map(i=>new qi(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new qi(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,j.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];if(!(r!=null&&r.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==O.STOPPED&&this.setInterval(Vc)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=this.mainDetails,d=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;if(!u){this.startFragRequested=!1;return}if(l.details){var c;d=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}a.alignedSliding||(_n(u,a,this),d=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,u&&!this.startFragRequested&&this.setStartPosition(u,d),o===r&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:i,payload:r}=e;!i||!(r!=null&&r.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(r,t,i)}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e;this.fragContextChanged(t)||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&hs(t.method))}decryptPayload(e,t,i){let r=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,Vl(r.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(E.FRAG_DECRYPTED,{frag:t,part:i,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:i}),i||(this.warn(`${a.name}: ${a.message}`),this.state=O.IDLE)})}doTick(){if(this.state===O.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:i,levels:r}=this,n=r[i],a=n==null?void 0:n.details;if(!a||this.waitForLive(n)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}let{config:o}=this,l=this.playhead,u=oe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:d,len:c}=u,h=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(c>h||c&&!this.buffering)return;let f=this.getNextFragment(d,a);if(!f)return;if(Ne(f)){var t;let g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===(m==null?void 0:m.cc)&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===Me.NOT_LOADED&&(f=m)}this.loadFragment(f,n,d)}}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);(r===Me.NOT_LOADED||r===Me.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new bl(this.tracksBuffered[this.currentTrackId]||[])}},bl=class{constructor(e){this.buffered=void 0;let t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},n_={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},Mf=s=>String.fromCharCode(n_[s]||s),wt=15,Ct=42,a_={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},o_={17:2,18:4,21:6,22:8,23:10,19:13,20:15},l_={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},u_={25:2,26:4,29:6,30:8,31:10,27:13,28:15},d_=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Al=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;Te.log(`${this.time} [${e}] ${i}`)}}},Gi=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},Rl=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),Fn=class{constructor(){this.styles=Rl}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Rl}setStyles(e){let t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},xl=class{constructor(){this.uchar=" ",this.penState=new Fn}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},Il=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Fn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ct;t++)this.chars.push(new xl);this.logger=e}equals(e){let t=this.chars,i=e.chars;for(let r=0;r<Ct;r++){let n=t[r],a=i[r];if(n.uchar!==a.uchar)return!1;let o=n.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Ct;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Ct;t++){let i=e[t];if(i.uchar!==" ")return!1;let r=i.penState.styles;if(r!==Rl&&(r.foreground!=="white"||r.underline||r.italics||r.background!=="black"||r.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Ct&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ct-1)}moveCursor(e){let t=Math.min(this.pos+e,Ct);if(e>1)for(let i=this.pos+1;i<t;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=Mf(e);if(this.pos>=Ct){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<Ct;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<Ct;i++){let r=this.chars[i].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Ys=class{constructor(e){this.rows=[],this.currRow=wt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<wt;t++)this.rows.push(new Il(e));this.logger=e}reset(){for(let e=0;e<wt;e++)this.rows[e].clear();this.currRow=wt-1}equals(e){let t=!0;for(let i=0;i<wt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<wt;t++){let i=this.rows[t].chars,r=e.rows[t].chars;for(let n=0;n<Ct;n++){let a=i[n],o=r[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<wt;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ke(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<wt;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let u=0;u<this.nrRollUpRows;u++)this.rows[t-this.nrRollUpRows+u+1].copy(a.rows[n+u])}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ke(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());let 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;let t=[],i="",r=-1;for(let n=0;n<wt;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
57
|
+
`)),i}getTextAndFormat(){return this.rows}},Ll=class{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 Ys(i),this.nonDisplayedMemory=new Ys(i),this.lastOutputScreen=new Ys(i),this.currRollUpRow=this.displayedMemory.rows[wt-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[wt-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;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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"){let 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){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+ke(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let 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))}},Bn=class{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=h_(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Al,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,(i=this.channels[e])==null||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new Ll(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let r=t[i]&127,n=t[i+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+Gi([t[i],t[i+1]])+"] -> ("+Gi([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(c_(r,n,l)){en(null,null,l),this.logger.log(3,()=>"Repeated command ("+Gi([r,n])+") is dropped");continue}en(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else en(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let d=this.currentChannel;d&&d>0?this.getChannel(d).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Gi([r,n])+" orig: "+Gi([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return!1;let n=e===20||e===21||e===23?1:2,a=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!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;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Gi([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;let a=e<=23?1:2;return t>=64&&t<=95?i=a===1?a_[e]:l_[e]:i=a===1?o_[e]:u_[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Mf(a)+"' in channel "+i),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+Gi(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=d_[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}en(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function en(s,e,t){t.a=s,t.b=e}function c_(s,e,t){return t.a===s&&t.b===e}function h_(){return{a:null,b:null}}var cs=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dl=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hc(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new cs(this,"textTrack1"),t=new cs(this,"textTrack2"),i=new cs(this,"textTrack3"),r=new cs(this,"textTrack4");this.cea608Parser1=new Bn(1,e,t),this.cea608Parser2=new Bn(3,i,r)}addCues(e,t,i,r,n){let a=!1;for(let l=n.length;l--;){let u=n[l],d=f_(u[0],u[1],t,i);if(d>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],i),a=!0,d/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let u=this.Cues.newCue(null,t,i,r);u.length&&l.push.apply(l,u)}else{let u=this.captionsTracks[e].track;this.Cues.newCue(u,t,i,r)}}else{var o;let l=this.Cues.newCue(null,t,i,r),u=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:u})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){let{unparsedVttFrags:r}=this;t===j.MAIN&&(this.initPTS=i),r.length&&(this.unparsedVttFrags=[],r.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,n):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,cueCache:r,media:n}=this,{label:a,languageCode:o}=t[e];n&&(r[e]=[],i[e]=su(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){let{captionsTracks:r,cueCache:n}=this;for(let a in r)r[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hc(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!rf(this.tracks,i)){let r=i.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===j.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=t.frag,d=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=d}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.level<this.tracks.length&&i.type===j.SUBTITLE){var n;if(r.byteLength||(n=i.initSegment)!=null&&(n=n.data)!=null&&n.byteLength){let a=i.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){let l=this.tracks[i.level],u=this.vttCCs;u[i.cc]||(u[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(l==null?void 0:l.textCodec)===ol?this._parseIMSC1(t):this._parseVTTs(t)}}else{let a="part"in t?t.part:null;this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:i}=e,r="part"in e?e.part:null,n=this.hls;Oc(i,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:a})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[i.cc]&&l===-1){o.push(e);return}let u=this.hls,d=(t=i.initSegment)==null?void 0:t.data,c=d?St(d,new Uint8Array(r)).buffer:r;UT(c,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!d?n:i).start,h=>{this._appendCues(h,i.level),u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},h=>{let f=h.message.startsWith("Missing initPTS");if(u.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${h}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:h})})}_fallbackToIMSC1(e){let{frag:t,payload:i}=e,r=this.tracks[t.level];r.textCodec||Oc(i,this.initPTS[t.cc],()=>{r.textCodec=ol,this._parseIMSC1(e)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){var r;let n=(r=this.tracks[t].trackNode)==null?void 0:r.track;if(!n||n.mode==="disabled")return;e.forEach(a=>ll(n,a))}else{let n=this.tracks[t];if(!n)return;let a=n.default?"default":"subtitles"+t;i.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===j.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(!(i.type===j.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;let{type:r,timeRanges:n}=t;if(r==="video"&&(i=n[r])!=null&&i.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var u;let d=(u=a[l])==null?void 0:u.track;if(d){let c=o[l];for(let h=0;h<c.length;h++)ll(d,c[h])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:i,endOffset:r,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a==="video"){let{captionsTracks:l,cueCache:u}=this;Object.keys(l).forEach(d=>ul(l[d].track,i,r)),Object.keys(u).forEach(d=>{let c=u[d];for(let h=c.length;h--;){let f=c[h];f.startTime>=i&&f.endTime<=r&&c.splice(h,1)}})}this.config.renderTextTracksNatively&&i===0&&n!==void 0&&this.tracks.forEach(l=>{var u;let d=(u=l.trackNode)==null?void 0:u.track;d&&ul(d,i,n)})}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let d=3&a;(d===0||d===1)&&(t[d].push(o),t[d].push(l))}}return t}};function f_(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Hc(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var g_=/\s/,m_={newCue(s,e,t,i){let r=[],n,a,o,l,u,d=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=!0,l=0,u="",!n.isEmpty()){var c;for(let m=0;m<n.chars.length;m++)g_.test(n.chars[m].uchar)&&o?l++:(u+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Lf(u.trim()),g=iu(e,t,f);s!=null&&(c=s.cues)!=null&&c.getCueById(g)||(a=new d(e,t,f),a.id=g,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>ll(s,h))),r}},Un=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new js}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(zs(e,t,!0))this.retry(e);else{var i;Te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Nl(e,i.retry),i.retry++,Te.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function p_(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var v_=/(\d+)-(\d+)\/(\d+)/,$n=class extends Un{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||__}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let r=y_(t,this.controller.signal),n=t.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&H(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(or(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var c;this.response=d;let h=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(h-i.loading.start)),!d.ok){let{status:g,statusText:m}=d;throw new kl(m||"fetch, bad network response",g,d)}i.loading.first=h,i.total=T_(d.headers)||i.total;let f=(c=this.callbacks)==null?void 0:c.onProgress;return f&&H(e.highWaterMark)?this.loadProgressively(d,i,t,e.highWaterMark,f):n?d.arrayBuffer():t.responseType==="json"?d.json():d.text()}).then(d=>{var c,h;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let g=d[a];g&&(i.loaded=i.total=g);let m={url:f.url,data:d,code:f.status},p=(c=this.callbacks)==null?void 0:c.onProgress;p&&!H(e.highWaterMark)&&p(i,t,d,f),(h=this.callbacks)==null||h.onSuccess(m,i,t,f)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let c=d&&d.code||0,h=d?d.message:null,f=e.loadPolicy.errorRetry,g=i.retry,m={url:t.url,data:void 0,code:c};if(zs(f,g,!1,m))this.retry(f);else{var p;Te.error(`${c} while loading ${t.url}`),(p=this.callbacks)==null||p.onError({code:c,text:h},t,d?d.details:null,i)}})}getCacheAge(){let e=null;if(this.response){let 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,r=0,n){let a=new An,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let d=u.value,c=d.length;return t.loaded+=c,c<r||a.dataLength?(a.push(d),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,d.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function y_(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Re({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function E_(s){let e=v_.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function T_(s){let e=s.get("Content-Range");if(e){let i=E_(e);if(H(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function __(s,e){return new self.Request(s.url,e)}var kl=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},S_=(s,e,t)=>Math.max(e,Math.min(s,t)),b_=/^age:\s*[\d.]+\s*$/im,Gn=class extends Un{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let 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()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n.call(this,i,t.url,t)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[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=n&&H(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let u=t.status,d=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){let g=d!=null?d:t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(i,e,g,t);let y={url:t.responseURL,data:g,code:u};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&Te.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(y,i,e,t);return}}let c=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:u};if(zs(c,h,!1,f))this.retry(c);else{var l;Te.error(`${u} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:u,text:t.statusText},e,t,i)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&b_.test(this.loader.getAllResponseHeaders())){let 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}},A_={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},R_=J(J({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Gn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:wh,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:A_},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:On,abrController:To,bufferController:Yo,capLevelController:dr,errorController:_o,fpsController:il,id3TrackController:fl,gapController:cl,latencyController:_l},x_()),{},{subtitleStreamController:Sl,subtitleTrackController:dl,timelineController:Dl,audioStreamController:Vo,audioTrackController:Ho,emeController:wn,cmcdController:Zo,contentSteeringController:el,iframeController:ml,interstitialsController:Tl});function x_(){return{cueHandler:m_,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 I_(s,e,t){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"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){let a=e.liveMaxUnchangedPlaylistRefresh,o=S_(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let i=Pl(s),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,u=[];n.forEach(d=>{let c=`${a}Loading${d}`,h=e[c];if(h!==void 0&&l){u.push(c);let f=i[o].default;switch(e[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),u.length&&t.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${o}": ${ke(e[o])}`)}),J(J({},i),e)}function Pl(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Pl):Object.keys(s).reduce((e,t)=>(e[t]=Pl(s[t]),e),{}):s}function L_(s,e){let t=s.loader;t!==$n&&t!==Gn?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):p_()&&(s.loader=$n,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Cl=class extends lr{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,u=!1,d=!1;t.levels.forEach(c=>{let h=c.attrs,f=qc(c,i),{audioCodec:g,videoCodec:m,imageCodec:p,width:y,height:T}=c;if(!f){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}o||(o=!!(y&&T)),l||(l=!!m),u||(u=!!g),d||(d=!!p);let{CODECS:v,"FRAME-RATE":_,"HDCP-LEVEL":S,"PATHWAY-ID":A,RESOLUTION:b,"VIDEO-RANGE":x}=h,R=`${`${A||"."}-`}${c.bitrate}-${b}-${_}-${v}-${x}-${S}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let I=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(I+1).join(".");let P=this.createLevel(c);n[R]=P,r.push(P)}else c.iframes||(n[R].addGroupId("audio",h.AUDIO),n[R].addGroupId("text",h.SUBTITLES));else{let I=this.createLevel(c);n[R]=I,a[R]=1,r.push(I)}}),this.filterAndSortMediaOptions(r,t,o,l,u,d)}createLevel(e){let t=new qi(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!Ff(i.videoCodec,this.hls.config.preferManagedMediaSource)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(r.message),t.supportedResult=Eh(r,[])}return t}filterAndSortMediaOptions(e,t,i,r,n,a){var o;let l=[],u=[],d=e,c=((o=t.stats)==null?void 0:o.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((i||r)&&n&&(d=d.filter(({videoCodec:S,videoRange:A,width:b,height:x})=>(!!S||!!(b&&x))&&Xv(A))),r&&a&&(d=d.filter(S=>!S.imageCodec)),d.length===0){Promise.resolve().then(()=>{if(this.hls){let S="no level with compatible codecs found in manifest",A=S;t.levels.length&&(A=`one or more CODECS in variant not supported: ${ke(t.levels.map(x=>x.attrs.CODECS).filter((x,L,R)=>R.indexOf(x)===L))}`,this.warn(A),S+=` (${A})`);let b=new Error(S);this.hls.trigger(E.ERROR,{type:Q.MEDIA_ERROR,details:k.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:b,reason:A})}}),c.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(S=>!S.audioCodec||Nf(S.audioCodec,h)),Wc(l)),t.subtitles&&(u=t.subtitles,Wc(u));let f=d.slice(0);d.sort((S,A)=>{if(S.attrs["HDCP-LEVEL"]!==A.attrs["HDCP-LEVEL"])return(S.attrs["HDCP-LEVEL"]||"")>(A.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&S.height!==A.height)return S.height-A.height;if(S.frameRate!==A.frameRate)return S.frameRate-A.frameRate;if(S.videoRange!==A.videoRange)return hn.indexOf(S.videoRange)-hn.indexOf(A.videoRange);if(S.videoCodec!==A.videoCodec){let b=Cd(S.videoCodec),x=Cd(A.videoCodec);if(b!==x)return x-b}if(S.uri===A.uri&&S.codecSet!==A.codecSet){let b=dn(S.codecSet),x=dn(A.codecSet);if(b!==x)return x-b}return S.averageBitrate!==A.averageBitrate?S.averageBitrate-A.averageBitrate:0});let g=f[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==f.length)){for(let S=0;S<f.length;S++)if(f[S].pathwayId===d[0].pathwayId){g=f[S];break}}this._levels=d;for(let S=0;S<d.length;S++)if(d[S]===g){var m;this._firstLevel=S;let A=g.bitrate,b=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${A}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){let x=Math.min(A,this.hls.config.abrEwmaDefaultEstimateMax);x>b&&b===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}let p=t.iframeVariants.filter(S=>qc(S,h));this._iframeVariants=p;let y=n&&!r,T=this.hls.config,v=!!(T.audioStreamController&&T.audioTrackController),_={levels:d,audioTracks:l,subtitleTracks:u,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:v&&!y&&l.some(S=>!!S.url)};c.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,_)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let d=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:d,reason:d.message}),c)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,l);let u=a.details;if(!u||u.live){let d=this.switchParams(a.uri,r==null?void 0:r.details,u);this.loadPlaylist(d)}}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){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===de.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===j.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(E.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let r=this.hls.config.abrSwitchInterval;if(r>0){let n=performance.now(),a=n-this.lastABRSwitchTime,o=r*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${r}s)`);return}this.lastABRSwitchTime=n,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${r}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));$h(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(E.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Nf(s,e){return Zs(s,"audio",e)}function Ff(s,e){return Zs(s,"video",e)}function qc(s,e){let{audioCodec:t,videoCodec:i}=s;t&&(s.audioCodec=t=cn(t,e)||void 0),i&&(i=s.videoCodec=Gv(i));let{unknownCodecs:r}=s;return!((r==null?void 0:r.length)||0||t&&!Nf(t,e)||i&&!Ff(i,e))}function Wc(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var wl=class extends at{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyLoaderInfo){let r=this.keyLoaderInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);let r=e.decryptdata;if(!r){let a=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(ui(e,k.KEY_LOAD_ERROR,a))}let n=e;switch(r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(n):t?t.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(ui(e,k.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let i=_v(e.initSegment.data);if(i.length){let r=i[0],n=e.decryptdata.uri;if(r.some(a=>a!==0))this.log(`Using keyId found in init segment ${We(r)} keyUri: ${n}`),Wi.setKeyIdForUri(n,r);else{let a=Wi.addKeyIdForUri(n);this.log(`Patching empty keyId with ${We(a)} keyUri: ${n}`),r=a}e.decryptdata.keyId=r}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(ui(e,k.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(ui(e,k.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let r=this.keyLoaderInfo[i];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(u=>(t.key=r.decryptdata.key,J(J({},u),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+We(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let n=this.config,a=n.loader,o=new a(n);e.keyLoader=o;let l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((u,d)=>{let c={type:de.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},h=n.keyLoadPolicy.default,f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,p,y,T)=>{let{frag:v,keyInfo:_,url:S}=y;if(!v.decryptdata||_!==this.keyLoaderInfo[S])return d(ui(v,k.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),T));_.decryptdata.key=v.decryptdata.key=new Uint8Array(m.data),v.keyLoader=_.loader=_.keyLoadPromise=null,u({frag:v,keyInfo:_})},onError:(m,p,y,T)=>{this.resetLoader(p),d(ui(e,k.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),y,J({url:i,data:void 0},m)))},onTimeout:(m,p,y)=>{this.resetLoader(p),d(ui(e,k.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(m,p,y)=>{this.resetLoader(p),d(ui(e,k.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};o.load(c,f,g)})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[r],n&&n.destroy()}};function ui(s,e=k.KEY_LOAD_ERROR,t,i,r){return new _t({type:Q.NETWORK_ERROR,details:e,fatal:!1,frag:s,response:r,error:t,networkDetails:i||null})}function Yc(s){let{type:e}=s;switch(e){case de.AUDIO_TRACK:return j.AUDIO;case de.SUBTITLE_TRACK:return j.SUBTITLE;default:return j.MAIN}}function uo(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Ol=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,a=new n(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(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:de.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:de.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:de.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:de.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[de.LEVEL];if(i){let r=i.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(i.abort(),delete this.loaders[de.LEVEL])}}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let u=this.hls.logger,d=r.context;if((d==null?void 0:d.levelOrTrack)===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives)){d.url===e.url?u.log(`[playlist-loader]: ignore ${e.url} ongoing request`):u.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);return}u.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===de.MANIFEST?n=i.manifestLoadPolicy.default:n=Re({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),H((t=e.deliveryDirectives)==null?void 0:t.part)){let u;if(e.type===de.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===de.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===de.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){let d=u.partTarget,c=u.targetduration;if(d&&c){let h=Math.max(d*3,c*.8)*1e3;n=Re({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,d,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let g=u.data;d.parsing.start=performance.now(),fi.isMediaPlaylist(g)||c.type!==de.MANIFEST?this.handleTrackOrLevelPlaylist(u,d,c,h||null,f):this.handleMasterPlaylist(u,d,c,h)},onError:(u,d,c,h)=>{this.handleNetworkError(d,c,!1,u,h)},onTimeout:(u,d,c)=>{this.handleNetworkError(d,c,!0,void 0,u)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){let n=this.hls,a=e.data,o=uo(e,i),l=fi.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:u,levels:d,iframeVariants:c,sessionData:h,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,d.forEach(v=>{let{unknownCodecs:_}=v;if(_){let{preferManagedMediaSource:S}=this.hls.config,{audioCodec:A,videoCodec:b}=v;for(let x=_.length;x--;){let L=_[x];Zs(L,"audio",S)?(v.audioCodec=A=A?`${A},${L}`:L,gs.audio[A.substring(0,4)]=2,_.splice(x,1)):Zs(L,"video",S)&&(v.videoCodec=b=b?`${b},${L}`:L,gs.video[b.substring(0,4)]=2,_.splice(x,1))}}});let{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":T}=fi.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(_=>!_.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Oe({}),bitrate:0,url:""})),n.trigger(E.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:y,iframeVariants:c,captions:T,contentSteering:u,url:o,stats:t,networkDetails:r,sessionData:h,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,r,n){let a=this.hls,{id:o,level:l,type:u}=i,d=uo(e,i),c=H(l)?l:H(o)?o:0,h=Yc(i),f=fi.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(u===de.MANIFEST){let g={attrs:new Oe({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=t.loading.start+Fh(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,n)}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(E.ERROR,{type:Q.NETWORK_ERROR,details:k.MANIFEST_PARSING_ERROR,fatal:t.type===de.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,i=!1,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===de.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===de.AUDIO_TRACK||e.type===de.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=k.UNKNOWN,u=!1,d=this.getInternalLoader(e);switch(e.type){case de.MANIFEST:l=i?k.MANIFEST_LOAD_TIMEOUT:k.MANIFEST_LOAD_ERROR,u=!0;break;case de.LEVEL:l=i?k.LEVEL_LOAD_TIMEOUT:k.LEVEL_LOAD_ERROR,u=!1;break;case de.AUDIO_TRACK:l=i?k.AUDIO_TRACK_LOAD_TIMEOUT:k.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case de.SUBTITLE_TRACK:l=i?k.SUBTITLE_TRACK_LOAD_TIMEOUT:k.SUBTITLE_LOAD_ERROR,u=!1;break}d&&this.resetInternalLoader(e.type);let c={type:Q.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(r){let h=e.url;t&&"url"in t&&(h=t.url),c.response=J({url:h,data:void 0},r)}this.hls.trigger(E.ERROR,c)}handlePlaylistLoaded(e,t,i,r,n,a){let o=this.hls,{type:l,level:u,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:f}=r,g=uo(t,r),m=Yc(r),p=typeof r.level=="number"&&m===j.MAIN?u:void 0;d&&"iframes"in d&&d.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);let y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:Q.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:r,level:p,parent:m,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:Q.NETWORK_ERROR,details:k.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:r,level:p,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case de.MANIFEST:case de.LEVEL:if(p){if(!d)p=0;else if(d!==o.levels[p]){let T=o.levels.indexOf(d);T>-1&&(p=T)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:d||o.levels[0],level:p||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===de.MANIFEST,context:r});break;case de.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f,context:r});break;case de.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f,context:r});break}}},hr=class s{static get version(){return nr}static isMSESupported(){return wf()}static isSupported(){return XT()}static getMediaSource(){return pi()}static get Events(){return E}static get MetadataSchema(){return nt}static get ErrorTypes(){return Q}static get ErrorDetails(){return k}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:R_}static set DefaultConfig(e){s.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ql,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=j0(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=I_(s.DefaultConfig,e,t);this.userConfig=e,i.progressive&&L_(i,t);let{streamController:r,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:u,id3TrackController:d,iframeController:c,gapController:h}=i,f=new l(this),g=this.abrController=new n(this),m=new So(this),p=i.interstitialsController,y=p?this.interstitialsController=new p(this,s):null,T=a?this.bufferController=new a(this,m):null,v=o?this.capLevelController=new o(this):null,_=u?new u(this):null,S=i.cmcdController,A=S?this.cmcdController=new S(this):null,b=new Ol(this),x=i.contentSteeringController,L=x?new x(this):null,R=this.levelController=new Cl(this,L),I=d?new d(this):void 0,P=new wl(this.config,this.logger),w=this.streamController=new r(this,m,P),B=this.gapController=h?new h(this,m):void 0;v&&v.setStreamController(w);let U=[b,R,w];y&&U.splice(1,0,y),L&&U.splice(1,0,L),this.networkControllers=U;let C=[g];T&&C.push(T),B&&C.push(B),v&&C.push(v),_&&(_.setStreamController(w),C.push(_)),I&&C.push(I),C.push(m),this.audioTrackController=this.createController(i.audioTrackController,U);let N=i.audioStreamController;N&&U.push(this.audioStreamController=new N(this,m,P)),this.subtitleTrackController=this.createController(i.subtitleTrackController,U);let F=i.subtitleStreamController;F&&U.push(this.subtititleStreamController=new F(this,m,P)),this.createController(i.timelineController,C),P.emeController=this.emeController=this.createController(i.emeController,C),A&&C.push(A),this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=c?new c(this,s):void 0,U.push(f);let G=f.onErrorOut;typeof G=="function"&&this.on(E.ERROR,G,f),this.on(E.MANIFEST_LOADED,b.onManifestLoaded,b)}createController(e,t){if(e){let 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,r){this._emitter.off(e,t,i,r)}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){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let r=e===E.ERROR;this.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:Q.OTHER_ERROR,details:k.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(E.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(E.MEDIA_DETACHING,e),this._media=null,this.trigger(E.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(E.MEDIA_DETACHING,i),this.trigger(E.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();let i=this.media,r=this._url,n=this._url=Ml.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&r&&(r!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==O.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[j.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[j.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[j.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,i=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=eh()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.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){let t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){zv(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){let e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=bh(t);return Th(e,i,navigator.mediaCapabilities)}};hr.defaultConfig=void 0;var ce=hr,xe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ye={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_RECONNECTING:2000003,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},Yf=s=>s===xe.VIDEO?"playback":s,yi=class gr extends Error{constructor(e,t=gr.MEDIA_ERR_CUSTOM,i,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=i!=null?i:t>=gr.MEDIA_ERR_NETWORK&&t<=gr.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=gr.defaultMessages[this.code])!=null?n:"")}};yi.MEDIA_ERR_ABORTED=1,yi.MEDIA_ERR_NETWORK=2,yi.MEDIA_ERR_DECODE=3,yi.MEDIA_ERR_SRC_NOT_SUPPORTED=4,yi.MEDIA_ERR_ENCRYPTED=5,yi.MEDIA_ERR_CUSTOM=100,yi.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var z=yi,D_=s=>s==null,vu=(s,e)=>D_(e)?!1:s in e,ou={ANY:"any",MUTED:"muted"},it={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Yi={MSE:"mse",NATIVE:"native"},mr={HEADER:"header",QUERY:"query",NONE:"none"},yu=Object.values(mr),ti={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},lu={HLS:ti.M3U8},pb=Object.keys(lu),vb=[...Object.values(ti),"hls","HLS"];var k_="en",uu={code:k_},Be=(s,e,t,i,r=s)=>{r.addEventListener(e,t,i),s.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function P_(s,e,t){e&&t>e&&(t=e);for(let i=0;i<s.length;i++)if(s.start(i)<=t&&s.end(i)>=t)return!0;return!1}var Xn=s=>{let e=s.indexOf("?");if(e<0)return[s];let t=s.slice(0,e),i=s.slice(e);return[t,i]},Qn=s=>{let{type:e}=s;if(e){let t=e.toUpperCase();return vu(t,lu)?lu[t]:e}return C_(s)},jf=s=>s==="VOD"?it.ON_DEMAND:it.LIVE,zf=s=>s==="EVENT"?Number.POSITIVE_INFINITY:s==="VOD"?Number.NaN:0,C_=s=>{let{src:e}=s;if(!e)return"";let t="";try{t=Eu(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let i=t.lastIndexOf(".");if(i<0)return M_(s)?ti.M3U8:"";let r=t.slice(i+1).toUpperCase();return vu(r,ti)?ti[r]:""},du=s=>{try{return new URL(s),!1}catch{return!0}},w_=s=>s.split(`
|
|
58
|
+
`).find((e,t,i)=>t>0&&i[t-1].startsWith("#EXT-X-STREAM-INF")),Eu=(s,e)=>{var t;if(!du(s))return new URL(s);let i=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:i;return e&&du(e.toString())&&(r=new URL(e,i)),new URL(s,r)},O_="mux.com",M_=({src:s,customDomain:e=O_})=>{let t;try{t=new URL(`${s}`)}catch{return!1}let i=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return i&&r&&a&&o},N_=s=>{let e=(s!=null?s:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(i)}catch{return}},F_=({exp:s},e=Date.now())=>!s||s*1e3<e,B_=({sub:s},e)=>s!==e,U_=({aud:s},e)=>!s,$_=({aud:s},e)=>s!==e,Xf="en";function me(s,e=!0){var t,i;let r=e&&(i=(t=uu)==null?void 0:t[s])!=null?i:s,n=e?uu.code:Xf;return new G_(r,n)}var G_=class{constructor(s,e=(t=>(t=uu)!=null?t:Xf)()){this.message=s,this.locale=e}format(s){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var i;return(i=s[t])!=null?i:""})}toString(){return this.message}},K_=Object.values(ou),Bf=s=>typeof s=="boolean"||typeof s=="string"&&K_.includes(s),V_=(s,e,t)=>{let{autoplay:i}=s,r=!1,n=!1,a=Bf(i)?i:!!i,o=()=>{r||Be(e,"playing",()=>{r=!0},{once:!0})};if(o(),Be(e,"loadstart",()=>{r=!1,o(),ru(e,a)},{once:!0}),Be(e,"loadstart",()=>{t||(s.streamType&&s.streamType!==it.UNKNOWN?n=s.streamType===it.LIVE:n=!Number.isFinite(e.duration)),ru(e,a)},{once:!0}),t&&t.once(ce.Events.LEVEL_LOADED,(l,u)=>{var d;s.streamType&&s.streamType!==it.UNKNOWN?n=s.streamType===it.LIVE:n=(d=u.details.live)!=null?d:!1}),!a){let l=()=>{!n||Number.isFinite(s.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Be(e,"play",()=>{e.preload==="metadata"?t.once(ce.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=Bf(l)?l:!!l,ru(e,a))}},ru=(s,e)=>{if(!e)return;let t=s.muted,i=()=>s.muted=t;switch(e){case ou.ANY:s.play().catch(()=>{s.muted=!0,s.play().catch(i)});break;case ou.MUTED:s.muted=!0,s.play().catch(i);break;default:s.play().catch(()=>{});break}},H_=({preload:s,src:e},t,i)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!i)return r(s),r;let n=!1,a=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,u=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),d())},d=()=>{!n&&e&&(n=!0,i.loadSource(e))};return Be(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,d()},{once:!0}),u(s),u},q_=(s,e,t)=>{let{minPreloadSegments:i}=s;if(i==null||i<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,Be(e,"ratechange",o);let l=(u,{frag:d})=>{n||d.type!=="main"||(r++,r>=i&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(ce.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(ce.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},W_=(s,e,t)=>{let{initialEstimateSegments:i}=s;if(i==null||i<=0||!t)return;let r=0;t.on(ce.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<i&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function Y_(s,e){var t;if(!("videoTracks"in s))return;let i=new WeakMap;e.on(ce.Events.MANIFEST_PARSED,function(u,d){l();let c=s.addVideoTrack("main");c.selected=!0;for(let[h,f]of d.levels.entries()){let g=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);i.set(f,`${h}`),g.id=`${h}`}}),e.on(ce.Events.AUDIO_TRACKS_UPDATED,function(u,d){o();for(let c of d.audioTracks){let h=c.default?"main":"alternative",f=s.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var u;let d=+((u=[...s.audioTracks].find(h=>h.enabled))==null?void 0:u.id),c=e.audioTracks.map(h=>h.id);d!=e.audioTrack&&c.includes(d)&&(e.audioTrack=d)};s.audioTracks.addEventListener("change",r),e.on(ce.Events.LEVELS_UPDATED,function(u,d){var c;let h=s.videoTracks[(c=s.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=d.levels.map(g=>i.get(g));for(let g of s.videoRenditions)g.id&&!f.includes(g.id)&&h.removeRendition(g)});let n=u=>{let d=u.target.selectedIndex;d!=e.nextLevel&&(e.nextLevel=d)};(t=s.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let u of s.videoTracks)s.removeVideoTrack(u)},o=()=>{for(let u of s.audioTracks)s.removeAudioTrack(u)},l=()=>{a(),o()};e.once(ce.Events.DESTROYING,()=>{var u,d;l(),(u=s.audioTracks)==null||u.removeEventListener("change",r),(d=s.videoRenditions)==null||d.removeEventListener("change",n)})}var nu=s=>"time"in s?s.time:s.startTime;function j_(s,e){e.on(ce.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let u=(o=a.subtitleTrack)!=null?o:a.closedCaptions,d=e.subtitleTracks.findIndex(({lang:h,name:f,type:g})=>h==(u==null?void 0:u.lang)&&f===a.label&&g.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${d}`;Qf(s,a.kind,a.label,u==null?void 0:u.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(s.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:u,type:d,default:c})=>r.id==="default"&&c||l==r.language&&u===r.label&&d.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};s.textTracks.addEventListener("change",t),e.on(ce.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=s.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(u=>{var d;(d=o.cues)!=null&&d.getCueById(u.id)||o.addCue(u)}),l&&(o.mode="disabled")}),e.once(ce.Events.DESTROYING,()=>{s.textTracks.removeEventListener("change",t),s.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let i=()=>{Array.from(s.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=s.querySelector(o),u=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",u)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(ce.Events.MANIFEST_LOADED,i),e.once(ce.Events.MEDIA_ATTACHED,i)}function Qf(s,e,t,i,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,i&&(a.srclang=i),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),s.append(a),a.track}function vr(s,e,t){var i;return(i=Array.from(s.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:i.track}async function Jf(s,e,t,i){let r=vr(s,t,i);return r||(r=Qf(s,i,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>nu(a)-nu(n)).forEach(n=>{var a,o;let l=n.value,u=nu(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(u,n.endTime,i==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let d=Array.prototype.findIndex.call(r==null?void 0:r.cues,g=>g.startTime>=u),c=(a=r==null?void 0:r.cues)==null?void 0:a[d],h=c?c.startTime:Number.isFinite(s.duration)?s.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[d-1];f&&(f.endTime=u),r==null||r.addCue(new VTTCue(u,h,i==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),s.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Tu="cuepoints",Zf=Object.freeze({label:Tu});async function _u(s,e,t=Zf){return Jf(s,e,t.label,"metadata")}var cu=s=>({time:s.startTime,value:JSON.parse(s.text)});function eg(s,e={label:Tu}){let t=vr(s,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,i=>cu(i)):[]}function Su(s,e={label:Tu}){var t,i;let r=vr(s,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return cu(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return cu(a||r.activeCues[0])}async function z_(s,e=Zf){return new Promise(t=>{Be(s,"loadstart",async()=>{let i=await _u(s,[],e);Be(s,"cuechange",()=>{let r=Su(s);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}var bu="chapters",tg=Object.freeze({label:bu}),hu=s=>({startTime:s.startTime,endTime:s.endTime,value:s.text});async function Au(s,e,t=tg){return Jf(s,e,t.label,"chapters")}function ig(s,e={label:bu}){var t;let i=vr(s,e.label,"chapters");return(t=i==null?void 0:i.cues)!=null&&t.length?Array.from(i.cues,r=>hu(r)):[]}function Ru(s,e={label:bu}){var t,i;let r=vr(s,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return hu(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return hu(a||r.activeCues[0])}async function X_(s,e=tg){return new Promise(t=>{Be(s,"loadstart",async()=>{let i=await Au(s,[],e);Be(s,"cuechange",()=>{let r=Ru(s);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}function sg(s,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-s.currentTime*1e3)}return typeof s.getStartDate=="function"?s.getStartDate():new Date(NaN)}function rg(s,e){if(e&&e.playingDate)return e.playingDate;if(typeof s.getStartDate=="function"){let t=s.getStartDate();return new Date(t.getTime()+s.currentTime*1e3)}return new Date(NaN)}var Uf={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},Q_=s=>{if(s===xe.VIDEO)return Uf.VIDEO;if(s===xe.DRM)return Uf.DRM},J_=(s,e)=>{var t,i;let r=Yf(s),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(i=e.tokens)==null?void 0:i[r]:vu(n,e)?e[n]:void 0},jn=(s,e,t,i,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let y=me("Your device appears to be offline",r),T,v=z.MEDIA_ERR_NETWORK,_=new z(y,v,!1,T);return _.errorCategory=e,_.muxCode=ye.NETWORK_OFFLINE,_.data=s,_}let l="status"in s?s.status:s.code,u=Date.now(),d=z.MEDIA_ERR_NETWORK;if(l===200)return;let c=Yf(e),h=J_(e,t),f=Q_(e),[g]=Xn((a=t.playbackId)!=null?a:"");if(!l||!g)return;let m=N_(h);if(h&&!m){let y=me("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),T=me("Compact JWT string: {token}",r).format({token:h}),v=new z(y,d,!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_TOKEN_MALFORMED,v.data=s,v}if(l>=500){let y=new z("",d,i!=null?i:!0);return y.errorCategory=e,y.muxCode=ye.NETWORK_UNKNOWN_ERROR,y}if(l===403)if(m){if(F_(m,u)){let y={timeStyle:"medium",dateStyle:"medium"},T=me("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),v=me("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",y).format((o=m.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",y).format(u)}),_=new z(T,d,!0,v);return _.errorCategory=e,_.muxCode=ye.NETWORK_TOKEN_EXPIRED,_.data=s,_}if(B_(m,g)){let y=me("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),T=me("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:g,tokenPlaybackId:m.sub}),v=new z(y,d,!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_TOKEN_SUB_MISMATCH,v.data=s,v}if(U_(m,f)){let y=me("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=me("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),v=new z(y,d,!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_TOKEN_AUD_MISSING,v.data=s,v}if($_(m,f)){let y=me("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=me("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:m.aud}),v=new z(y,d,!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_TOKEN_AUD_MISMATCH,v.data=s,v}}else{let y=me("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),T=me("Specified playback ID: {playbackId}",r).format({playbackId:g}),v=new z(y,d,i!=null?i:!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_TOKEN_MISSING,v.data=s,v}if(l===412){let y=me("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),T=me("Specified playback ID: {playbackId}",r).format({playbackId:g}),v=new z(y,d,i!=null?i:!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_NOT_READY,v.streamType=t.streamType===it.LIVE?"live":t.streamType===it.ON_DEMAND?"on-demand":"unknown",v.data=s,v}if(l===404){let y=me("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),T=me("Specified playback ID: {playbackId}",r).format({playbackId:g}),v=new z(y,d,i!=null?i:!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_NOT_FOUND,v.data=s,v}if(l===400){let y=me("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),T=me("Specified playback ID: {playbackId}",r).format({playbackId:g}),v=new z(y,d,i!=null?i:!0,T);return v.errorCategory=e,v.muxCode=ye.NETWORK_INVALID_URL,v.data=s,v}let p=new z("",d,i!=null?i:!0);return p.errorCategory=e,p.muxCode=ye.NETWORK_UNKNOWN_ERROR,p.data=s,p},fu=ce.DefaultConfig.capLevelController;fu||console.error("MinCapLevelController - hls.js DefaultConfig.capLevelController is unavailable");var Z_={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function eS(s){let e=s.toLowerCase().trim();return Z_[e]}var gu=class pr extends fu{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?pr.maxAutoResolution.set(e,t):pr.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=pr.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,i)=>this.isLevelAllowed(t)&&i<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),i=this.getMaxAutoResolution();if(!i)return super.getMaxLevel(e);let r=eS(i);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(u=>u===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),i=this.getValidLevels(e);if(!i[t])return t;let r=Math.min(i[t].width,i[t].height),n=pr.minMaxResolution;return r>=n?t:fu.getMaxLevelByMediaSize(i,n*(16/9),n)}};gu.minMaxResolution=720,gu.maxAutoResolution=new WeakMap;var tS=gu,mu=tS,iS="com.apple.fps.1_0",sS="application/vnd.apple.mpegurl",rS=({mediaEl:s,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:i,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in s)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=me("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=xe.DRM,f.muxCode=ye.ENCRYPTED_CDM_ERROR,i(s,f),()=>{}}let n=s,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||u();let f=await a;if(h.initData===null||f==null)return;let g=nS(h.initData,f);d(g)}catch(f){console.error("Could not start encrypted playback due to exception",f),i(n,f)}})()},u=()=>{try{let h=new WebKitMediaKeys(iS);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=xe.DRM,f.muxCode=ye.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},d=h=>{let f=n.webkitKeys.createSession(sS,h),g=async y=>{try{let T=y.message,v=await t(T);f.update(v)}catch(T){console.error("Error on FairPlay session message",T),i(s,T)}},m=y=>{let T=y.target.error;if(!T)return;console.error(`Internal Webkit Key Session Error - sysCode: ${T.systemCode} code: ${T.code}`);let v=me("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),_=new z(v,z.MEDIA_ERR_ENCRYPTED,!0);_.errorCategory=xe.DRM,_.muxCode=ye.ENCRYPTED_CDM_ERROR,i(s,_)},p=()=>{f.removeEventListener("webkitkeymessage",g),f.removeEventListener("webkitkeyerror",m),s.removeEventListener("teardown",p),"webkitCurrentPlaybackTargetIsWireless"in s&&s.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",p),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in s&&s.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",p,{once:!0}),f.addEventListener("webkitkeymessage",g),f.addEventListener("webkitkeyerror",m),s.addEventListener("teardown",p),o=p},c=()=>{s.removeEventListener("webkitneedkey",l),s.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return s.addEventListener("webkitneedkey",l),s.addEventListener("teardown",c,{once:!0}),c},nS=(s,e)=>{let t=oS(aS(s)),i=new Uint8Array(s),r=new Uint8Array(t),n=new Uint8Array(e),a=i.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,u=c=>{o.set(c,l),l+=c.byteLength},d=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,u(c)};return u(i),d(r),d(n),o},aS=s=>new TextDecoder("utf-16le").decode(s).replace("skd://","").slice(1);function oS(s){let e=new ArrayBuffer(s.length*2),t=new DataView(e);for(let i=0;i<s.length;i++)t.setUint16(i*2,s.charCodeAt(i),!0);return e}var lS=({mediaEl:s,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:i,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}s.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await u(h,f)}catch(h){i(s,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(g=>(r(),g)).catch(()=>{let g=me("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),m=new z(g,z.MEDIA_ERR_ENCRYPTED,!0);m.errorCategory=xe.DRM,m.muxCode=ye.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,i(s,m)});if(!h)return;let f=await h.createMediaKeys();try{let g=await e();await f.setServerCertificate(g).catch(()=>{let m=me("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),p=new z(m,z.MEDIA_ERR_ENCRYPTED,!0);return p.errorCategory=xe.DRM,p.muxCode=ye.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(p)})}catch(g){i(s,g);return}await s.setMediaKeys(f)},u=async(c,h)=>{let f=s.mediaKeys.createSession(),g=async y=>{let T=y.message,v=await t(T);try{await f.update(v)}catch{let _=me("Failed to update DRM license. This may be an issue with the player or your protected content."),S=new z(_,z.MEDIA_ERR_ENCRYPTED,!0);S.errorCategory=xe.DRM,S.muxCode=ye.ENCRYPTED_UPDATE_LICENSE_FAILED,i(s,S)}},m=()=>{let y=T=>{let v;if(T==="internal-error"){let _=me("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");v=new z(_,z.MEDIA_ERR_ENCRYPTED,!0),v.errorCategory=xe.DRM,v.muxCode=ye.ENCRYPTED_CDM_ERROR}else if(T==="output-restricted"||T==="output-downscaled"){let _=me("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");v=new z(_,z.MEDIA_ERR_ENCRYPTED,!1),v.errorCategory=xe.DRM,v.muxCode=ye.ENCRYPTED_OUTPUT_RESTRICTED}v&&i(s,v)};f.keyStatuses.forEach(T=>y(T))};f.addEventListener("keystatuseschange",m),f.addEventListener("message",g);let p=async()=>{f.removeEventListener("keystatuseschange",m),f.removeEventListener("message",g),"webkitCurrentPlaybackTargetIsWireless"in s&&s.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",p),s.removeEventListener("teardown",p),await f.close().catch(y=>{console.warn("There was an error when closing EME session",y)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in s&&s.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",p,{once:!0}),s.addEventListener("teardown",p,{once:!0}),a=p,await f.generateRequest(c,h).catch(async y=>{if(y.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in s&&s.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let T=me("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),v=new z(T,z.MEDIA_ERR_ENCRYPTED,!0);return v.errorCategory=xe.DRM,v.muxCode=ye.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",y),Promise.reject(v)}})},d=async()=>{s.removeEventListener("encrypted",o),s.removeEventListener("teardown",d),a&&await a(),await s.setMediaKeys(null).catch(()=>{})};return s.addEventListener("encrypted",o),s.addEventListener("teardown",d,{once:!0}),d},uS=({hls:s,mediaEl:e,src:t,muxMediaState:i,saveAndDispatchError:r,maxRetries:n})=>{var a;let o,l=0,u=!1,d=!1,c=!1,h=()=>{o!=null&&(clearTimeout(o),o=void 0)},f=b=>(b==null?void 0:b.muxCode)===ye.NETWORK_RECONNECTING,g=()=>!e.paused&&e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA,m=()=>{let b=i.get(e);if(f(b==null?void 0:b.error))return;let x=new z(me("Attempting to reconnect..."),z.MEDIA_ERR_NETWORK,!1);x.errorCategory=xe.VIDEO,x.muxCode=ye.NETWORK_RECONNECTING,b&&(b.error=x),e.dispatchEvent(new CustomEvent("error",{detail:x}))},p=()=>{if(!c&&t){s.loadSource(t);return}s.startLoad(e.currentTime)},y=()=>{u=!1,d=!0,h();let b=new z(me("Network error, try reloading."),z.MEDIA_ERR_NETWORK,!0);b.errorCategory=xe.VIDEO,b.reload=!0,r(e,b)},T=()=>{if(o!=null||u)return;if(l>=n){y();return}u=!0;let b=Math.min(1e3*2**l,3e4);o=setTimeout(()=>{o=void 0,l+=1,p()},b)},v=()=>{let b=i.get(e);!(b!=null&&b.networkError)||d||g()&&(m(),T())},_=()=>{let b=i.get(e);b&&(b.networkError=!0),u=!1,v()},S=()=>{let b=i.get(e);b!=null&&b.networkError&&(l=0,d=!1,h(),u=!0,p())};(a=globalThis.addEventListener)==null||a.call(globalThis,"online",S);let A=()=>{let b=i.get(e);b&&(!b.networkError&&!f(b.error)||(b.networkError=!1,u=!1,l=0,d=!1,h(),b.error&&(b.error=null,e.dispatchEvent(new Event("emptied")))))};return s.on(ce.Events.FRAG_BUFFERED,A),Be(e,"playing",()=>{let b=i.get(e);b!=null&&b.networkError&&(u=!1,l=0,d=!1,h(),b.error&&(b.error=null))}),Be(e,"waiting",v),e.addEventListener("teardown",()=>{var b;(b=globalThis.removeEventListener)==null||b.call(globalThis,"online",S),h()},{once:!0}),{handleHlsError:(b,x)=>{var L,R;if(b.type!==ce.ErrorTypes.NETWORK_ERROR)return!1;let I=(R=(L=b.response)==null?void 0:L.code)!=null?R:0;return(x.muxCode===ye.NETWORK_OFFLINE||I===0||I>=500)&&b.fatal?(_(),!0):!1},onManifestLoaded:()=>{c=!0,u=!1,h()}}},Wn={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},dS=s=>{if(s.includes("fps"))return Wn.FAIRPLAY;if(s.includes("playready"))return Wn.PLAYREADY;if(s.includes("widevine"))return Wn.WIDEVINE},cS=(s,e)=>{let t=w_(s);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(du(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let i;try{i=Eu(t,e)}catch(r){return Promise.reject(r)}return fetch(i).then(r=>r.status!==200?Promise.reject(r):r.text())},hS=s=>{let e=s.split(`
|
|
59
|
+
`).filter(i=>i.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let i of e){let r=gS(i),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},fS=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function gS(s){let e=[...s.matchAll(fS)];return Object.fromEntries(e.map(([,t,i])=>[t,i]))}var mS=s=>{var e,t,i;let r=s.split(`
|
|
60
|
+
`),n=(t=((e=r.find(u=>u.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=jf(n),o=zf(n),l;if(a===it.LIVE){let u=r.find(d=>d.startsWith("#EXT-X-PART-INF"));if(u)l=+u.split(":")[1].split("=")[1]*2;else{let d=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(i=d==null?void 0:d.split(":"))==null?void 0:i[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},pS=async(s,e)=>{if(e===ti.MP4)return{streamType:it.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===ti.M3U8){let t=await fetch(s);if(!t.ok)return Promise.reject(t);let i=await t.text(),r=await cS(i,t.url);return{...hS(i),...mS(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${s}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},vS=async(s,e,t=Qn({src:s}))=>{var i,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:u,sessionData:d}=await pS(s,t),c=d==null?void 0:d["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&xu((i=c.URI)!=null?i:c.VALUE,e),((r=Ie.get(e))!=null?r:{}).liveEdgeStartOffset=u,((n=Ie.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Ie.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},xu=async(s,e)=>{var t,i;try{let r=await fetch(s);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((i=Ie.get(e))!=null?i:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},yS=s=>{var e;let t=s.type,i=jf(t),r=zf(t),n,a=!!((e=s.partList)!=null&&e.length);return i===it.LIVE&&(n=a?s.partTarget*2:s.targetduration*3),{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},ES=(s,e,t)=>{var i,r,n,a,o,l,u,d;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:g}=yS(s);if(c===it.LIVE){g?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let m=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var y;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(y=t.liveSyncPosition)!=null?y:e.seekable.end(p)}});((o=Ie.get(e))!=null?o:{}).seekable=m}((l=Ie.get(e))!=null?l:{}).liveEdgeStartOffset=f,((u=Ie.get(e))!=null?u:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((d=Ie.get(e))!=null?d:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},$f,Gf,ng=(Gf=($f=globalThis==null?void 0:globalThis.navigator)==null?void 0:$f.userAgent)!=null?Gf:"",Kf,Vf,Hf,TS=(Hf=(Vf=(Kf=globalThis==null?void 0:globalThis.navigator)==null?void 0:Kf.userAgentData)==null?void 0:Vf.platform)!=null?Hf:"",_S=ng.toLowerCase().includes("android")||["x11","android"].some(s=>TS.toLowerCase().includes(s)),SS=s=>/^((?!chrome|android).)*safari/i.test(ng)&&!!s.canPlayType("application/vnd.apple.mpegurl"),Ie=new WeakMap,ii="mux.com",qf,Wf,ag=(Wf=(qf=ce).isSupported)==null?void 0:Wf.call(qf),bS=s=>_S||!SS(s),og=()=>{if(typeof window!="undefined")return Ur.utils.now()},AS=Ur.utils.generateUUID,lg=({playbackId:s,customDomain:e=ii,maxResolution:t,minResolution:i,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:u,tokens:{playback:d=u}={},extraSourceParams:c={}}={})=>{if(!s)return;let[h,f=""]=Xn(s),g=new URL(`https://stream.${e}/${h}.m3u8${f}`);return d||g.searchParams.has("token")?(g.searchParams.forEach((m,p)=>{p!="token"&&g.searchParams.delete(p)}),d&&g.searchParams.set("token",d)):(t&&g.searchParams.set("max_resolution",t),i&&(g.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),r&&g.searchParams.set("rendition_order",r),n&&g.searchParams.set("program_start_time",`${n}`),a&&g.searchParams.set("program_end_time",`${a}`),o&&g.searchParams.set("asset_start_time",`${o}`),l&&g.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([m,p])=>{p!=null&&g.searchParams.set(m,p)})),g.toString()},Jn=s=>{if(!s)return;let[e]=s.split("?");return e||void 0},Zn=s=>{if(!s||!s.startsWith("https://stream."))return;let[e]=new URL(s).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},RS=s=>{var e,t,i;return(e=s==null?void 0:s.metadata)!=null&&e.video_id?s.metadata.video_id:yg(s)&&(i=(t=Jn(s.playbackId))!=null?t:Zn(s.src))!=null?i:s.src},Iu=s=>{var e;return(e=Ie.get(s))==null?void 0:e.error},ug=s=>{var e;return(e=Ie.get(s))==null?void 0:e.metadata},zn=s=>{var e,t;return(t=(e=Ie.get(s))==null?void 0:e.streamType)!=null?t:it.UNKNOWN},dg=s=>{var e,t;return(t=(e=Ie.get(s))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},ea=s=>{var e,t;return(t=(e=Ie.get(s))==null?void 0:e.seekable)!=null?t:s.seekable},cg=s=>{var e;let t=(e=Ie.get(s))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let i=ea(s);return i.length?i.end(i.length-1)-t:Number.NaN},hg=s=>{var e;return(e=Ie.get(s))==null?void 0:e.coreReference},Lu=.034,xS=(s,e,t=Lu)=>Math.abs(s-e)<=t,fg=(s,e,t=Lu)=>s>e||xS(s,e,t),IS=(s,e=Lu)=>s.paused&&fg(s.currentTime,s.duration,e),gg=(s,e)=>{var t,i,r;if(!e||!s.buffered.length)return;if(s.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(s.currentTime<s.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(s.currentTime<=o.start)return!1;let l=o.start+o.duration/2,u=s.buffered.start(s.buffered.length-1),d=s.buffered.end(s.buffered.length-1);return l>u&&l<d},Du=(s,e)=>s.ended||s.loop?s.ended:e&&gg(s,e)?!0:IS(s),ku=(s,e,t)=>{Pu(e,t,s);let{metadata:i={}}=s,{view_session_id:r=AS()}=i,n=RS(s);i.view_session_id=r,i.video_id=n,s.metadata=i;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};s.drmTypeCb=a,s.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,g=e.currentTime;s.useWebkitFairplay=!0;let m=s.muxDataKeepSession;s.muxDataKeepSession=!0;let p=(h=Ie.get(e))==null?void 0:h.coreReference;ku(s,e,p),s.muxDataKeepSession=m,s.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=g}).catch(()=>{}),e.currentTime=g},Ie.set(e,{retryCount:0});let o=kS(s,e),l=H_(s,e,o);s!=null&&s.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?ce:void 0}):Eg(s,e,o),FS(s,e,o),z_(e),X_(e);let u=V_(s,e,o);q_(s,e,o),W_(s,e,o);let d={engine:o,setAutoplay:u,setPreload:l},c=Ie.get(e);return c&&(c.coreReference=d),d},LS=()=>{let s=new Date(0).toUTCString(),e=new Set(["muxData"]);document.cookie.split(";").forEach(t=>{let i=t.split("=")[0].trim();i.startsWith("muxData")&&e.add(i)}),e.forEach(t=>{document.cookie=`${t}=;expires=${s};path=/`})},au=new WeakMap,DS=(s,e,t)=>{e&&(e.mux&&(e.mux.deleted||e.mux.destroy(),delete e.mux),!au.has(e)&&au.set(e,Promise.resolve().then(()=>{var i,r;au.delete(e);let n=Ie.get(e);if(!n||e.mux&&!e.mux.deleted)return;let a=(r=(i=n.coreReference)!=null?i:t)==null?void 0:r.engine;Eg(s,e,a)})))},mg=(s,e,t)=>{if(!e)return;let i=!!s.disableCookies,r=Ie.get(e);!r||r.muxDataDisableCookies===i||(DS(s,e,t),i&&Promise.resolve().then(()=>{s.disableCookies&&LS()}))},Pu=(s,e,t)=>{let i=e==null?void 0:e.engine;s!=null&&s.mux&&!s.mux.deleted&&(t!=null&&t.muxDataKeepSession?i&&s.mux.removeHLSJS():(s.mux.destroy(),delete s.mux)),i&&(i.detachMedia(),i.destroy()),s&&(s.hasAttribute("src")&&(s.removeAttribute("src"),s.load()),s.removeEventListener("error",_g),s.removeEventListener("error",pu),s.removeEventListener("durationchange",Tg),Ie.delete(s),s.dispatchEvent(new Event("teardown")))};function pg(s,e){var t;let i=Qn(s);if(i!==ti.M3U8)return!0;let r=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=s,a=n===Yi.MSE,o=n===Yi.NATIVE,l=ag&&(a||bS(e));return r&&(o||!l)}var kS=(s,e)=>{let{debug:t,streamType:i,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:u}=s,d=Qn(s)===ti.M3U8,c=pg(s,e);if(d&&!c&&ag){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...u!=null?{abrEwmaDefaultEstimate:u*1e3}:{}},f=PS(i),g=CS(s),m=[mr.QUERY,mr.HEADER].includes(a)?{useHeaders:a===mr.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,p=NS(s,o),y=new ce({debug:t,startPosition:r,cmcd:m,xhrSetup:(T,v)=>{var _,S;if(a&&a!==mr.QUERY)return;let A=Eu(v);if(!A.searchParams.has("CMCD"))return;let b=((S=(_=A.searchParams.get("CMCD"))==null?void 0:_.split(","))!=null?S:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");A.searchParams.set("CMCD",b),T.open("GET",A)},...h,...p,...f,...g,...o});return p.capLevelController===mu&&l!==void 0&&mu.setMaxAutoResolution(y,l),y.on(ce.Events.MANIFEST_PARSED,async function(T,v){var _,S;let A=(_=v.sessionData)==null?void 0:_["com.apple.hls.chapters"];(A!=null&&A.URI||A!=null&&A.VALUE.toLocaleLowerCase().startsWith("http"))&&xu((S=A==null?void 0:A.URI)!=null?S:A==null?void 0:A.VALUE,e)}),y}},PS=s=>s===it.LIVE?{backBufferLength:8}:{},CS=s=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:i}=s,r=Jn(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Yn(s,"fairplay"),serverCertificateUrl:vg(s,"fairplay")},"com.widevine.alpha":{licenseUrl:Yn(s,"widevine")},"com.microsoft.playready":{licenseUrl:Yn(s,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let u=(l=o.videoCapabilities)==null?void 0:l.map(d=>({...d,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:u}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=dS(n);return i==null||i(l),o}))}},wS=async s=>{let e=await fetch(s);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},OS=async(s,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:s});if(t.status!==200)return Promise.reject(t);let i=await t.arrayBuffer();return new Uint8Array(i)},MS=(s,e)=>{let t={mediaEl:e,getAppCertificate:()=>wS(vg(s,"fairplay")).catch(i=>{if(i instanceof Response){let r=jn(i,xe.DRM,s);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(i)}),getLicenseKey:i=>OS(i,Yn(s,"fairplay")).catch(r=>{if(r instanceof Response){let n=jn(r,xe.DRM,s);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:ei,drmTypeCb:()=>{var i;(i=s.drmTypeCb)==null||i.call(s,Wn.FAIRPLAY)}};if(s.useWebkitFairplay)rS(t);else{let i={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=s.fallbackToWebkitFairplay)==null||n.call(s)},...t},r=lS(i)}},Yn=({playbackId:s,tokens:{drm:e}={},customDomain:t=ii},i)=>{let r=Jn(s);return`https://license.${t.toLocaleLowerCase().endsWith(ii)?t:ii}/license/${i}/${r}?token=${e}`},vg=({playbackId:s,tokens:{drm:e}={},customDomain:t=ii},i)=>{let r=Jn(s);return`https://license.${t.toLocaleLowerCase().endsWith(ii)?t:ii}/appcert/${i}/${r}?token=${e}`},yg=({playbackId:s,src:e,customDomain:t})=>{if(s)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,r=new URL(e,i).hostname.toLocaleLowerCase();return r.includes(ii)||!!t&&r.includes(t.toLocaleLowerCase())},NS=(s,e)=>{let t={};return t.capLevelToPlayerSize=s.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=mu,t.capLevelToPlayerSize=!0):t.capLevelController=dr,t},Eg=(s,e,t)=>{var i;let{envKey:r,disableTracking:n,muxDataSDK:a=Ur,muxDataSDKOptions:o={}}=s,l=yg(s),u=Ie.get(e);if(u&&(u.muxDataDisableCookies=!!s.disableCookies),!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:c,playerSoftwareVersion:h,beaconCollectionDomain:f,debug:g,disableCookies:m}=s,p={...s.metadata,video_title:((i=s==null?void 0:s.metadata)==null?void 0:i.video_title)||void 0},y=T=>typeof T.player_error_code=="string"?!1:typeof s.errorTranslator=="function"?s.errorTranslator(T):T;a.monitor(e,{debug:g,beaconCollectionDomain:f,hlsjs:t,Hls:t?ce:void 0,automaticErrorTracking:!1,errorTranslator:y,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:c,player_software:c,player_software_version:h,player_init_time:d,...p}})}},FS=(s,e,t)=>{var i,r,n;let a=pg(s,e),{src:o,customDomain:l=ii}=s,u=()=>{e.ended||s.disablePseudoEnded||!Du(e,t)||(gg(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,c,h=()=>{let f=ea(e),g,m;f.length>0&&(g=f.start(0),m=f.end(0)),(c!==m||d!==g)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=g,c=m};if(Be(e,"durationchange",h),e&&a){let f=Qn(s);if(typeof o=="string"){if(o.endsWith(".mp4")&&o.includes(l)){let p=Zn(o),y=new URL(`https://stream.${l}/${p}/metadata.json`);xu(y.toString(),e)}let g=()=>{if(zn(e)!==it.LIVE||Number.isFinite(e.duration))return;let p=setInterval(h,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),Be(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>vS(o,e,f).then(g).catch(p=>{if(p instanceof Response){let y=jn(p,xe.VIDEO,s);if(y){ei(e,y);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",y)},y=()=>{m(),e.removeEventListener("play",p)};Be(e,"play",p,{once:!0}),Be(e,"loadedmetadata",y,{once:!0})}else m();(i=s.tokens)!=null&&i.drm?MS(s,e):Be(e,"encrypted",()=>{let p=me("Attempting to play DRM-protected content without providing a DRM token."),y=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);y.errorCategory=xe.DRM,y.muxCode=ye.ENCRYPTED_MISSING_TOKEN,ei(e,y)},{once:!0}),e.setAttribute("src",o),s.startTime&&(((r=Ie.get(e))!=null?r:{}).startTime=s.startTime,e.addEventListener("durationchange",Tg,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",_g),e.addEventListener("error",pu),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(g=>{g.remove()})},{once:!0}),Be(e,"pause",u),Be(e,"seeked",u),Be(e,"play",()=>{e.ended||fg(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else if(t&&o){t.once(ce.Events.LEVEL_LOADED,(m,p)=>{ES(p.details,e,t),h(),zn(e)===it.LIVE&&!Number.isFinite(e.duration)&&(t.on(ce.Events.LEVEL_UPDATED,h),Be(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(ce.Events.LEVELS_UPDATED,h)}))});let f=(n=s.maxReconnectRetries)!=null?n:0,g=f>0?uS({hls:t,mediaEl:e,src:o,muxMediaState:Ie,saveAndDispatchError:ei,maxRetries:f}):void 0;t.on(ce.Events.ERROR,(m,p)=>{var y,T;let v=BS(p,s);if(v.muxCode===ye.NETWORK_NOT_READY){let _=(y=Ie.get(e))!=null?y:{},S=(T=_.retryCount)!=null?T:0;if(S<6){let A=S===0?5e3:6e4,b=new z(`Retrying in ${A/1e3} seconds...`,v.code,v.fatal);Object.assign(b,v),ei(e,b);let x=setTimeout(()=>{_.retryCount=S+1,p.details==="manifestLoadError"&&p.url&&t.loadSource(p.url)},A);e.addEventListener("teardown",()=>clearTimeout(x),{once:!0});return}else{_.retryCount=0;let A=new z("Network error, try reloading.",v.code,v.fatal);Object.assign(A,v),A.reload=!0,ei(e,A);return}}g!=null&&g.handleHlsError(p,v)||ei(e,v)}),t.on(ce.Events.MANIFEST_LOADED,()=>{g==null||g.onManifestLoaded();let m=Ie.get(e);m!=null&&m.networkError||m&&m.error&&(m.error=null,m.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",pu),Be(e,"waiting",u),Y_(s,t),j_(e,t),t.attachMedia(e)}else console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Tg(s){var e;let t=s.target,i=(e=Ie.get(t))==null?void 0:e.startTime;if(i&&P_(t.seekable,t.duration,i)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=i,r&&(t.preload="auto")}}async function _g(s){if(!s.isTrusted)return;s.stopImmediatePropagation();let e=s.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,r=new z(t,i);if(e.src&&i===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Iu(e))!=null?n:e.error;(a==null?void 0:a.code)===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&ei(e,r)},500);return}if(e.src&&(i!==z.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}ei(e,r)}function ei(s,e){var t;e.fatal&&(((t=Ie.get(s))!=null?t:{}).error=e,s.dispatchEvent(new CustomEvent("error",{detail:e})))}function pu(s){var e,t;if(!(s instanceof CustomEvent)||!(s.detail instanceof z))return;let i=s.target,r=s.detail;!r||!r.fatal||(((e=Ie.get(i))!=null?e:{}).error=r,(t=i.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var BS=(s,e)=>{var t,i,r;s.fatal?console.error("getErrorFromHlsErrorData()",s):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",s);let n={[ce.ErrorTypes.NETWORK_ERROR]:z.MEDIA_ERR_NETWORK,[ce.ErrorTypes.MEDIA_ERROR]:z.MEDIA_ERR_DECODE,[ce.ErrorTypes.KEY_SYSTEM_ERROR]:z.MEDIA_ERR_ENCRYPTED},a=d=>[ce.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,ce.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(d.details)?z.MEDIA_ERR_NETWORK:n[d.type],o=d=>{if(d.type===ce.ErrorTypes.KEY_SYSTEM_ERROR)return xe.DRM;if(d.type===ce.ErrorTypes.NETWORK_ERROR)return xe.VIDEO},l,u=a(s);if(u===z.MEDIA_ERR_NETWORK&&s.response){let d=(t=o(s))!=null?t:xe.VIDEO;l=(i=jn(s.response,d,e,s.fatal))!=null?i:new z("",u,s.fatal)}else if(u===z.MEDIA_ERR_ENCRYPTED)if(s.details===ce.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let d=me("Attempting to play DRM-protected content without providing a DRM token.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_MISSING_TOKEN}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let d=me("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_NO_SESSION){let d=me("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let d=me("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let d=me("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let d=me("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_CDM_ERROR}else if(s.details===ce.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let d=me("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new z(d,z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_OUTPUT_RESTRICTED}else l=new z(s.error.message,z.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=xe.DRM,l.muxCode=ye.ENCRYPTED_ERROR;else l=new z("",u,s.fatal);return l.context||(l.context=`${s.url?`url: ${s.url}
|
|
59
61
|
`:""}${s.response&&(s.response.code||s.response.text)?`response: ${s.response.code}, ${s.response.text}
|
|
60
62
|
`:""}${s.reason?`failure reason: ${s.reason}
|
|
61
63
|
`:""}${s.level?`level: ${s.level}
|
|
@@ -64,7 +66,7 @@ Schedule: ${l.map(p=>mt(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Remo
|
|
|
64
66
|
`:""}${s.error?`error: ${s.error}
|
|
65
67
|
`:""}${s.event?`event: ${s.event}
|
|
66
68
|
`:""}${s.err?`error message: ${(r=s.err)==null?void 0:r.message}
|
|
67
|
-
`:""}`),l.data=s,l};var
|
|
69
|
+
`:""}`),l.data=s,l};var Ag=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"],Rg=["autopictureinpicture","disablepictureinpicture","disableremoteplayback","autoplay","controls","controlslist","crossorigin","loop","muted","playsinline","poster","preload","src"];function US(s){return`
|
|
68
70
|
<style>
|
|
69
71
|
:host {
|
|
70
72
|
display: inline-flex;
|
|
@@ -78,10 +80,10 @@ Schedule: ${l.map(p=>mt(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Remo
|
|
|
78
80
|
}
|
|
79
81
|
</style>
|
|
80
82
|
<slot name="media">
|
|
81
|
-
<audio${
|
|
83
|
+
<audio${Pg(s)}></audio>
|
|
82
84
|
</slot>
|
|
83
85
|
<slot></slot>
|
|
84
|
-
`}function
|
|
86
|
+
`}function $S(s){return`
|
|
85
87
|
<style>
|
|
86
88
|
:host {
|
|
87
89
|
display: inline-block;
|
|
@@ -103,12 +105,12 @@ Schedule: ${l.map(p=>mt(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Remo
|
|
|
103
105
|
}
|
|
104
106
|
</style>
|
|
105
107
|
<slot name="media">
|
|
106
|
-
<video${
|
|
108
|
+
<video${Pg(s)}></video>
|
|
107
109
|
</slot>
|
|
108
110
|
<slot></slot>
|
|
109
|
-
`}function
|
|
110
|
-
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" part="logo" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 1600 500"><g fill="#fff"><path d="M994.287 93.486c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m0-93.486c-34.509 0-62.484 27.976-62.484 62.486v187.511c0 68.943-56.09 125.033-125.032 125.033s-125.03-56.09-125.03-125.033V62.486C681.741 27.976 653.765 0 619.256 0s-62.484 27.976-62.484 62.486v187.511C556.772 387.85 668.921 500 806.771 500c137.851 0 250.001-112.15 250.001-250.003V62.486c0-34.51-27.976-62.486-62.485-62.486M1537.51 468.511c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m-275.883-218.509-143.33 143.329c-24.402 24.402-24.402 63.966 0 88.368 24.402 24.402 63.967 24.402 88.369 0l143.33-143.329 143.328 143.329c24.402 24.4 63.967 24.402 88.369 0 24.403-24.402 24.403-63.966.001-88.368l-143.33-143.329.001-.004 143.329-143.329c24.402-24.402 24.402-63.965 0-88.367s-63.967-24.402-88.369 0L1349.996 161.63 1206.667 18.302c-24.402-24.401-63.967-24.402-88.369 0s-24.402 63.965 0 88.367l143.329 143.329v.004ZM437.511 468.521c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31M461.426 4.759C438.078-4.913 411.2.432 393.33 18.303L249.999 161.632 106.669 18.303C88.798.432 61.922-4.913 38.573 4.759 15.224 14.43-.001 37.214-.001 62.488v375.026c0 34.51 27.977 62.486 62.487 62.486 34.51 0 62.486-27.976 62.486-62.486V213.341l80.843 80.844c24.404 24.402 63.965 24.402 88.369 0l80.843-80.844v224.173c0 34.51 27.976 62.486 62.486 62.486s62.486-27.976 62.486-62.486V62.488c0-25.274-15.224-48.058-38.573-57.729" style="fill-rule:nonzero"/></g></svg>`,
|
|
111
|
-
${
|
|
111
|
+
`}function kg(s,{tag:e,is:t}){var n,a,o,l,u,xg,c,h,f,g,m,p,ji,Cu,wu,Ig,Ou,Lg,Dg;let i=(a=(n=globalThis.document)==null?void 0:n.createElement)==null?void 0:a.call(n,e,{is:t}),r=i?GS(i):[];return o=class extends s{constructor(){super(...arguments);te(this,p);te(this,c,!1);te(this,h,null);te(this,f,new Map);te(this,g);te(this,m);fe(this,"get");fe(this,"set");fe(this,"call")}static get observedAttributes(){var I,P,w;return Ae(I=o,u,xg).call(I),[...(w=(P=i==null?void 0:i.constructor)==null?void 0:P.observedAttributes)!=null?w:[],...Rg]}get nativeEl(){var R,I,P,w,B;return Ae(this,p,ji).call(this),(B=(w=(I=(R=D(this,h))!=null?R:this.querySelector(":scope > [slot=media]"))!=null?I:this.querySelector(e))!=null?w:(P=this.shadowRoot)==null?void 0:P.querySelector(e))!=null?B:null}set nativeEl(R){Z(this,h,R)}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(R){this.toggleAttribute("muted",R)}get src(){return this.getAttribute("src")}set src(R){this.setAttribute("src",`${R}`)}get preload(){var R,I;return(I=this.getAttribute("preload"))!=null?I:(R=this.nativeEl)==null?void 0:R.preload}set preload(R){this.setAttribute("preload",`${R}`)}init(){if(!this.shadowRoot){this.attachShadow({mode:"open"});let R=KS(this.attributes);t&&(R.is=t),e&&(R.part=e),this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(R)}this.nativeEl.muted=this.hasAttribute("muted");for(let R of r)Ae(this,p,Lg).call(this,R);Ae(this,p,Cu).call(this)}handleEvent(R){R.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(R.type,{detail:R.detail}))}attributeChangedCallback(R,I,P){Ae(this,p,ji).call(this),Ae(this,p,Dg).call(this,R,I,P)}connectedCallback(){Ae(this,p,ji).call(this),D(this,m)||Ae(this,p,Cu).call(this)}disconnectedCallback(){var R,I,P;(R=D(this,g))==null||R.disconnect(),Z(this,g,void 0),D(this,m)&&((I=this.shadowRoot)==null||I.removeEventListener("slotchange",D(this,m)),Z(this,m,void 0));for(let w of this.constructor.Events)(P=this.shadowRoot)==null||P.removeEventListener(w,this,!0);D(this,f).forEach(w=>w.remove()),D(this,f).clear(),Z(this,h,null)}},l=new WeakMap,u=new WeakSet,xg=function(){if(D(this,l))return;Z(this,l,!0);let R=new Set(this.observedAttributes);R.delete("muted");for(let I of r)if(!(I in this.prototype))if(typeof i[I]=="function")this.prototype[I]=function(...P){return Ae(this,p,ji).call(this),(()=>{var U;if(this.call)return this.call(I,...P);let B=(U=this.nativeEl)==null?void 0:U[I];return B==null?void 0:B.apply(this.nativeEl,P)})()};else{let P={get(){var B,U,C;Ae(this,p,ji).call(this);let w=I.toLowerCase();if(R.has(w)){let N=this.getAttribute(w);return N===null?!1:N===""?!0:N}return(C=(B=this.get)==null?void 0:B.call(this,I))!=null?C:(U=this.nativeEl)==null?void 0:U[I]}};I!==I.toUpperCase()&&(P.set=function(w){Ae(this,p,ji).call(this);let B=I.toLowerCase();if(R.has(B)){w===!0||w===!1||w==null?this.toggleAttribute(B,!!w):this.setAttribute(B,w);return}if(this.set){this.set(I,w);return}this.nativeEl&&(this.nativeEl[I]=w)}),Object.defineProperty(this.prototype,I,P)}},c=new WeakMap,h=new WeakMap,f=new WeakMap,g=new WeakMap,m=new WeakMap,p=new WeakSet,ji=function(){D(this,c)||(Z(this,c,!0),this.init())},Cu=function(){var R,I;Z(this,g,new MutationObserver(Ae(this,p,Ig).bind(this))),Z(this,m,()=>Ae(this,p,wu).call(this)),(R=this.shadowRoot)==null||R.addEventListener("slotchange",D(this,m)),Ae(this,p,wu).call(this);for(let P of this.constructor.Events)(I=this.shadowRoot)==null||I.addEventListener(P,this,!0)},wu=function(){var w;let R=new Map(D(this,f)),I=(w=this.shadowRoot)==null?void 0:w.querySelector("slot:not([name])");(I==null?void 0:I.assignedElements({flatten:!0}).filter(B=>["track","source"].includes(B.localName))).forEach(B=>{var C,N;R.delete(B);let U=D(this,f).get(B);U||(U=B.cloneNode(),D(this,f).set(B,U),(C=D(this,g))==null||C.observe(B,{attributes:!0})),(N=this.nativeEl)==null||N.append(U),Ae(this,p,Ou).call(this,U)}),R.forEach((B,U)=>{B.remove(),D(this,f).delete(U)})},Ig=function(R){var I;for(let P of R)if(P.type==="attributes"){let{target:w,attributeName:B}=P,U=D(this,f).get(w);U&&B&&(U.setAttribute(B,(I=w.getAttribute(B))!=null?I:""),Ae(this,p,Ou).call(this,U))}},Ou=function(R){R&&R.localName==="track"&&R.default&&(R.kind==="chapters"||R.kind==="metadata")&&R.track.mode==="disabled"&&(R.track.mode="hidden")},Lg=function(R){if(Object.prototype.hasOwnProperty.call(this,R)){let I=this[R];delete this[R],this[R]=I}},Dg=function(R,I,P){var w,B,U;["id","class"].includes(R)||!o.observedAttributes.includes(R)&&this.constructor.observedAttributes.includes(R)||(P===null?(w=this.nativeEl)==null||w.removeAttribute(R):((B=this.nativeEl)==null?void 0:B.getAttribute(R))!==P&&((U=this.nativeEl)==null||U.setAttribute(R,P)))},te(o,u),fe(o,"getTemplateHTML",e.endsWith("audio")?US:$S),fe(o,"shadowRootOptions",{mode:"open"}),fe(o,"Events",Ag),te(o,l,!1),o}function GS(s){let e=[];for(let t=Object.getPrototypeOf(s);t&&t!==HTMLElement.prototype;t=Object.getPrototypeOf(t)){let i=Object.getOwnPropertyNames(t);e.push(...i)}return e}function Pg(s){let e="";for(let t in s){if(!Rg.includes(t))continue;let i=s[t];i===""?e+=` ${t}`:e+=` ${t}="${i}"`}return e}function KS(s){let e={};for(let t of s)e[t.name]=t.value;return e}var Sg,yr=kg((Sg=globalThis.HTMLElement)!=null?Sg:class{},{tag:"video"}),bg,Tb=kg((bg=globalThis.HTMLElement)!=null?bg:class{},{tag:"audio"});var Og=s=>{throw TypeError(s)},Mu=(s,e,t)=>e.has(s)||Og("Cannot "+t),$e=(s,e,t)=>(Mu(s,e,"read from private field"),t?t.call(s):e.get(s)),bt=(s,e,t)=>e.has(s)?Og("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),Mt=(s,e,t,i)=>(Mu(s,e,"write to private field"),i?i.call(s,t):e.set(s,t),t),ta=(s,e,t)=>(Mu(s,e,"access private method"),t),VS=()=>{try{return"0.31.3"}catch{}return"UNKNOWN"},HS=VS(),qS=()=>HS,WS=`
|
|
112
|
+
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" part="logo" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 1600 500"><g fill="#fff"><path d="M994.287 93.486c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m0-93.486c-34.509 0-62.484 27.976-62.484 62.486v187.511c0 68.943-56.09 125.033-125.032 125.033s-125.03-56.09-125.03-125.033V62.486C681.741 27.976 653.765 0 619.256 0s-62.484 27.976-62.484 62.486v187.511C556.772 387.85 668.921 500 806.771 500c137.851 0 250.001-112.15 250.001-250.003V62.486c0-34.51-27.976-62.486-62.485-62.486M1537.51 468.511c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m-275.883-218.509-143.33 143.329c-24.402 24.402-24.402 63.966 0 88.368 24.402 24.402 63.967 24.402 88.369 0l143.33-143.329 143.328 143.329c24.402 24.4 63.967 24.402 88.369 0 24.403-24.402 24.403-63.966.001-88.368l-143.33-143.329.001-.004 143.329-143.329c24.402-24.402 24.402-63.965 0-88.367s-63.967-24.402-88.369 0L1349.996 161.63 1206.667 18.302c-24.402-24.401-63.967-24.402-88.369 0s-24.402 63.965 0 88.367l143.329 143.329v.004ZM437.511 468.521c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31M461.426 4.759C438.078-4.913 411.2.432 393.33 18.303L249.999 161.632 106.669 18.303C88.798.432 61.922-4.913 38.573 4.759 15.224 14.43-.001 37.214-.001 62.488v375.026c0 34.51 27.977 62.486 62.487 62.486 34.51 0 62.486-27.976 62.486-62.486V213.341l80.843 80.844c24.404 24.402 63.965 24.402 88.369 0l80.843-80.844v224.173c0 34.51 27.976 62.486 62.486 62.486s62.486-27.976 62.486-62.486V62.488c0-25.274-15.224-48.058-38.573-57.729" style="fill-rule:nonzero"/></g></svg>`,M={BEACON_COLLECTION_DOMAIN:"beacon-collection-domain",CUSTOM_DOMAIN:"custom-domain",DEBUG:"debug",DISABLE_TRACKING:"disable-tracking",DISABLE_COOKIES:"disable-cookies",DISABLE_PSEUDO_ENDED:"disable-pseudo-ended",MAX_RECONNECT_RETRIES:"max-reconnect-retries",DRM_TOKEN:"drm-token",PLAYBACK_TOKEN:"playback-token",ENV_KEY:"env-key",MAX_RESOLUTION:"max-resolution",MIN_RESOLUTION:"min-resolution",MAX_AUTO_RESOLUTION:"max-auto-resolution",RENDITION_ORDER:"rendition-order",PROGRAM_START_TIME:"program-start-time",PROGRAM_END_TIME:"program-end-time",ASSET_START_TIME:"asset-start-time",ASSET_END_TIME:"asset-end-time",METADATA_URL:"metadata-url",PLAYBACK_ID:"playback-id",PLAYER_SOFTWARE_NAME:"player-software-name",PLAYER_SOFTWARE_VERSION:"player-software-version",PLAYER_INIT_TIME:"player-init-time",PREFER_CMCD:"prefer-cmcd",PREFER_PLAYBACK:"prefer-playback",START_TIME:"start-time",STREAM_TYPE:"stream-type",TARGET_LIVE_WINDOW:"target-live-window",LIVE_EDGE_OFFSET:"live-edge-offset",TYPE:"type",LOGO:"logo",CAP_RENDITION_TO_PLAYER_SIZE:"cap-rendition-to-player-size",INITIAL_BANDWIDTH_ESTIMATE_KBPS:"initial-bandwidth-estimate-kbps",INITIAL_ESTIMATE_SEGMENTS:"initial-estimate-segments",MIN_PRELOAD_SEGMENTS:"min-preload-segments"},YS=Object.values(M),Cg=qS(),wg="mux-video",Er,ia,Tr,sa,ra,na,aa,oa,_r,la,vt,Ei,ua,Sr,Mg=class extends yr{constructor(){super(),bt(this,vt),bt(this,Er),bt(this,ia),bt(this,Tr,{}),bt(this,sa,{}),bt(this,ra),bt(this,na),bt(this,aa),bt(this,oa),bt(this,_r,""),bt(this,la,s=>{var e;let t=ug(this.nativeEl),i=(e=this.metadata)!=null?e:{};this.metadata={...t,...i},(t==null?void 0:t["com.mux.video.branding"])==="mux-free-plan"&&(Mt(this,_r,"default"),this.updateLogo())}),bt(this,ua),Mt(this,ia,og())}static get NAME(){return wg}static get VERSION(){return Cg}static get observedAttributes(){var s;return[...YS,...(s=yr.observedAttributes)!=null?s:[]]}static getLogoHTML(s){return!s||s==="false"?"":s==="default"?WS:`<img part="logo" src="${s}" />`}static getTemplateHTML(s={}){var e;return`
|
|
113
|
+
${yr.getTemplateHTML(s)}
|
|
112
114
|
<style>
|
|
113
115
|
:host {
|
|
114
116
|
position: relative;
|
|
@@ -133,11 +135,11 @@ Schedule: ${l.map(p=>mt(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Remo
|
|
|
133
135
|
}
|
|
134
136
|
</style>
|
|
135
137
|
<slot name="logo">
|
|
136
|
-
${this.getLogoHTML((e=s[
|
|
138
|
+
${this.getLogoHTML((e=s[M.LOGO])!=null?e:"")}
|
|
137
139
|
</slot>
|
|
138
|
-
`}get preferCmcd(){var s;return(s=this.getAttribute(w.PREFER_CMCD))!=null?s:void 0}set preferCmcd(s){s!==this.preferCmcd&&(s?Tl.includes(s)?this.setAttribute(w.PREFER_CMCD,s):console.warn(`Invalid value for preferCmcd. Must be one of ${Tl.join()}`):this.removeAttribute(w.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(w.PLAYER_INIT_TIME)?+this.getAttribute(w.PLAYER_INIT_TIME):De(this,Tn)}set playerInitTime(s){s!=this.playerInitTime&&(s==null?this.removeAttribute(w.PLAYER_INIT_TIME):this.setAttribute(w.PLAYER_INIT_TIME,`${+s}`))}get playerSoftwareName(){var s;return(s=De(this,An))!=null?s:af}set playerSoftwareName(s){yt(this,An,s)}get playerSoftwareVersion(){var s;return(s=De(this,bn))!=null?s:nf}set playerSoftwareVersion(s){yt(this,bn,s)}get _hls(){var s;return(s=De(this,st,zt))==null?void 0:s.engine}get mux(){var s;return(s=this.nativeEl)==null?void 0:s.mux}get error(){var s;return(s=Dl(this.nativeEl))!=null?s:null}get errorTranslator(){return De(this,xn)}set errorTranslator(s){yt(this,xn,s)}get src(){return this.getAttribute("src")}set src(s){s!==this.src&&(s==null?this.removeAttribute("src"):this.setAttribute("src",s))}get type(){var s;return(s=this.getAttribute(w.TYPE))!=null?s:void 0}set type(s){s!==this.type&&(s?this.setAttribute(w.TYPE,s):this.removeAttribute(w.TYPE))}get preload(){let s=this.getAttribute("preload");return s===""?"auto":["none","metadata","auto"].includes(s)?s:super.preload}set preload(s){s!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(s)?this.setAttribute("preload",s):this.removeAttribute("preload"))}get debug(){return this.getAttribute(w.DEBUG)!=null}set debug(s){s!==this.debug&&(s?this.setAttribute(w.DEBUG,""):this.removeAttribute(w.DEBUG))}get disableTracking(){return this.hasAttribute(w.DISABLE_TRACKING)}set disableTracking(s){s!==this.disableTracking&&this.toggleAttribute(w.DISABLE_TRACKING,!!s)}get disableCookies(){return this.hasAttribute(w.DISABLE_COOKIES)}set disableCookies(s){s!==this.disableCookies&&(s?this.setAttribute(w.DISABLE_COOKIES,""):this.removeAttribute(w.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(w.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(s){s!==this.disablePseudoEnded&&(s?this.setAttribute(w.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(w.DISABLE_PSEUDO_ENDED))}get maxReconnectRetries(){let s=this.getAttribute(w.MAX_RECONNECT_RETRIES);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set maxReconnectRetries(s){s!==this.maxReconnectRetries&&(s==null?this.removeAttribute(w.MAX_RECONNECT_RETRIES):this.setAttribute(w.MAX_RECONNECT_RETRIES,`${s}`))}get startTime(){let s=this.getAttribute(w.START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set startTime(s){s!==this.startTime&&(s==null?this.removeAttribute(w.START_TIME):this.setAttribute(w.START_TIME,`${s}`))}get initialBandwidthEstimateKbps(){let s=this.getAttribute(w.INITIAL_BANDWIDTH_ESTIMATE_KBPS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set initialBandwidthEstimateKbps(s){s!==this.initialBandwidthEstimateKbps&&(s==null?this.removeAttribute(w.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(w.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${s}`))}get initialEstimateSegments(){let s=this.getAttribute(w.INITIAL_ESTIMATE_SEGMENTS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set initialEstimateSegments(s){s!==this.initialEstimateSegments&&(s==null?this.removeAttribute(w.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(w.INITIAL_ESTIMATE_SEGMENTS,`${s}`))}get minPreloadSegments(){let s=this.getAttribute(w.MIN_PRELOAD_SEGMENTS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set minPreloadSegments(s){s!==this.minPreloadSegments&&(s==null?this.removeAttribute(w.MIN_PRELOAD_SEGMENTS):this.setAttribute(w.MIN_PRELOAD_SEGMENTS,`${s}`))}get playbackId(){var s;return this.hasAttribute(w.PLAYBACK_ID)?this.getAttribute(w.PLAYBACK_ID):(s=yn(this.src))!=null?s:void 0}set playbackId(s){s!==this.playbackId&&(s?this.setAttribute(w.PLAYBACK_ID,s):this.removeAttribute(w.PLAYBACK_ID))}get maxResolution(){var s;return(s=this.getAttribute(w.MAX_RESOLUTION))!=null?s:void 0}set maxResolution(s){s!==this.maxResolution&&(s?this.setAttribute(w.MAX_RESOLUTION,s):this.removeAttribute(w.MAX_RESOLUTION))}get minResolution(){var s;return(s=this.getAttribute(w.MIN_RESOLUTION))!=null?s:void 0}set minResolution(s){s!==this.minResolution&&(s?this.setAttribute(w.MIN_RESOLUTION,s):this.removeAttribute(w.MIN_RESOLUTION))}get maxAutoResolution(){var s;return(s=this.getAttribute(w.MAX_AUTO_RESOLUTION))!=null?s:void 0}set maxAutoResolution(s){s==null?this.removeAttribute(w.MAX_AUTO_RESOLUTION):this.setAttribute(w.MAX_AUTO_RESOLUTION,s)}get renditionOrder(){var s;return(s=this.getAttribute(w.RENDITION_ORDER))!=null?s:void 0}set renditionOrder(s){s!==this.renditionOrder&&(s?this.setAttribute(w.RENDITION_ORDER,s):this.removeAttribute(w.RENDITION_ORDER))}get programStartTime(){let s=this.getAttribute(w.PROGRAM_START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set programStartTime(s){s==null?this.removeAttribute(w.PROGRAM_START_TIME):this.setAttribute(w.PROGRAM_START_TIME,`${s}`)}get programEndTime(){let s=this.getAttribute(w.PROGRAM_END_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set programEndTime(s){s==null?this.removeAttribute(w.PROGRAM_END_TIME):this.setAttribute(w.PROGRAM_END_TIME,`${s}`)}get assetStartTime(){let s=this.getAttribute(w.ASSET_START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set assetStartTime(s){s==null?this.removeAttribute(w.ASSET_START_TIME):this.setAttribute(w.ASSET_START_TIME,`${s}`)}get assetEndTime(){let s=this.getAttribute(w.ASSET_END_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set assetEndTime(s){s==null?this.removeAttribute(w.ASSET_END_TIME):this.setAttribute(w.ASSET_END_TIME,`${s}`)}get customDomain(){var s;return(s=this.getAttribute(w.CUSTOM_DOMAIN))!=null?s:void 0}set customDomain(s){s!==this.customDomain&&(s?this.setAttribute(w.CUSTOM_DOMAIN,s):this.removeAttribute(w.CUSTOM_DOMAIN))}get capRenditionToPlayerSize(){var s;return((s=this._hlsConfig)==null?void 0:s.capLevelToPlayerSize)!=null?this._hlsConfig.capLevelToPlayerSize:De(this,In)}set capRenditionToPlayerSize(s){yt(this,In,s)}get drmToken(){var s;return(s=this.getAttribute(w.DRM_TOKEN))!=null?s:void 0}set drmToken(s){s!==this.drmToken&&(s?this.setAttribute(w.DRM_TOKEN,s):this.removeAttribute(w.DRM_TOKEN))}get playbackToken(){var s,e,t,i;if(this.hasAttribute(w.PLAYBACK_TOKEN))return(s=this.getAttribute(w.PLAYBACK_TOKEN))!=null?s:void 0;if(this.hasAttribute(w.PLAYBACK_ID)){let[,r]=mn((e=this.playbackId)!=null?e:"");return(t=new URLSearchParams(r).get("token"))!=null?t:void 0}if(this.src)return(i=new URLSearchParams(this.src).get("token"))!=null?i:void 0}set playbackToken(s){s!==this.playbackToken&&(s?this.setAttribute(w.PLAYBACK_TOKEN,s):this.removeAttribute(w.PLAYBACK_TOKEN))}get tokens(){let s=this.getAttribute(w.PLAYBACK_TOKEN),e=this.getAttribute(w.DRM_TOKEN);return{...De(this,_n),...s!=null?{playback:s}:{},...e!=null?{drm:e}:{}}}set tokens(s){yt(this,_n,s!=null?s:{})}get ended(){return Pl(this.nativeEl,this._hls)}get envKey(){var s;return(s=this.getAttribute(w.ENV_KEY))!=null?s:void 0}set envKey(s){s!==this.envKey&&(s?this.setAttribute(w.ENV_KEY,s):this.removeAttribute(w.ENV_KEY))}get beaconCollectionDomain(){var s;return(s=this.getAttribute(w.BEACON_COLLECTION_DOMAIN))!=null?s:void 0}set beaconCollectionDomain(s){s!==this.beaconCollectionDomain&&(s?this.setAttribute(w.BEACON_COLLECTION_DOMAIN,s):this.removeAttribute(w.BEACON_COLLECTION_DOMAIN))}get streamType(){var s;return(s=this.getAttribute(w.STREAM_TYPE))!=null?s:fn(this.nativeEl)}set streamType(s){s!==this.streamType&&(s?this.setAttribute(w.STREAM_TYPE,s):this.removeAttribute(w.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(w.TARGET_LIVE_WINDOW)?+this.getAttribute(w.TARGET_LIVE_WINDOW):Nh(this.nativeEl)}set targetLiveWindow(s){s!=this.targetLiveWindow&&(s==null?this.removeAttribute(w.TARGET_LIVE_WINDOW):this.setAttribute(w.TARGET_LIVE_WINDOW,`${+s}`))}get liveEdgeStart(){var s,e;if(this.hasAttribute(w.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:t}=this,i=(s=this.nativeEl.seekable.end(0))!=null?s:0,r=(e=this.nativeEl.seekable.start(0))!=null?e:0;return Math.max(r,i-t)}return Fh(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(w.LIVE_EDGE_OFFSET))return+this.getAttribute(w.LIVE_EDGE_OFFSET)}set liveEdgeOffset(s){s!=this.liveEdgeOffset&&(s==null?this.removeAttribute(w.LIVE_EDGE_OFFSET):this.setAttribute(w.LIVE_EDGE_OFFSET,`${+s}`))}get seekable(){return vn(this.nativeEl)}async addCuePoints(s){return this.nativeEl.currentSrc||console.warn("addCuePoints() was called before the media element has loaded. Wait for the loadstart event before calling addCuePoints()."),bl(this.nativeEl,s)}get activeCuePoint(){return Al(this.nativeEl)}get cuePoints(){return Rh(this.nativeEl)}async addChapters(s){return this.nativeEl.currentSrc||console.warn("addChapters() was called before the media element has loaded. Wait for the loadstart event before calling addChapters()."),Rl(this.nativeEl,s)}get activeChapter(){return Il(this.nativeEl)}get chapters(){return Lh(this.nativeEl)}getStartDate(){return Dh(this.nativeEl,this._hls)}get currentPdt(){return kh(this.nativeEl,this._hls)}get preferPlayback(){let s=this.getAttribute(w.PREFER_PLAYBACK);if(s===xi.MSE||s===xi.NATIVE)return s}set preferPlayback(s){s!==this.preferPlayback&&(s===xi.MSE||s===xi.NATIVE?this.setAttribute(w.PREFER_PLAYBACK,s):this.removeAttribute(w.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(s=>s.startsWith("metadata-")&&![w.METADATA_URL].includes(s)).reduce((s,e)=>{let t=this.getAttribute(e);return t!=null&&(s[e.replace(/^metadata-/,"").replace(/-/g,"_")]=t),s},{}),...De(this,Ws)}}set metadata(s){yt(this,Ws,s!=null?s:{}),this.mux&&this.mux.emit("hb",De(this,Ws))}get _hlsConfig(){return De(this,Sn)}set _hlsConfig(s){yt(this,Sn,s)}get logo(){var s;return(s=this.getAttribute(w.LOGO))!=null?s:De(this,Ys)}set logo(s){s?this.setAttribute(w.LOGO,s):this.removeAttribute(w.LOGO)}load(){wl(this,this.nativeEl,De(this,st,zt))}unload(){Cl(this.nativeEl,De(this,st,zt),this)}attributeChangedCallback(s,e,t){var i,r;switch(Hs.observedAttributes.includes(s)&&!["src","autoplay","preload"].includes(s)&&super.attributeChangedCallback(s,e,t),s){case w.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=t!=null?t:void 0;break;case w.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=t!=null?t:void 0;break;case"src":{let n=!!e,a=!!t;!n&&a?En(this,st,js).call(this):n&&!a?this.unload():n&&a&&(this.unload(),En(this,st,js).call(this));break}case"autoplay":if(t===e)break;(i=De(this,st,zt))==null||i.setAutoplay(this.autoplay);break;case"preload":if(t===e)break;(r=De(this,st,zt))==null||r.setPreload(t);break;case w.PLAYBACK_ID:case w.CUSTOM_DOMAIN:case w.MAX_RESOLUTION:case w.MIN_RESOLUTION:case w.RENDITION_ORDER:case w.PROGRAM_START_TIME:case w.PROGRAM_END_TIME:case w.ASSET_START_TIME:case w.ASSET_END_TIME:case w.PLAYBACK_TOKEN:this.hasAttribute(w.PLAYBACK_ID)&&(this.src=Oh(this));break;case w.DEBUG:{let n=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=n);break}case w.METADATA_URL:t&&fetch(t).then(n=>n.json()).then(n=>this.metadata=n).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${t}!`));break;case w.STREAM_TYPE:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case w.TARGET_LIVE_WINDOW:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case w.LOGO:(t==null||t!==e)&&this.updateLogo();break;case w.DISABLE_TRACKING:{if(t==null||t!==e){let n=this.currentTime,a=this.paused;this.unload(),En(this,st,js).call(this).then(()=>{this.currentTime=n,a||this.play()})}break}case w.DISABLE_COOKIES:{(t==null||t!==e)&&Gh(this,this.nativeEl,De(this,st,zt));break}case w.CAP_RENDITION_TO_PLAYER_SIZE:(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0)}}updateLogo(){if(!this.shadowRoot)return;let s=this.shadowRoot.querySelector('slot[name="logo"]');if(!s)return;let e=this.constructor.getLogoHTML(De(this,Ys)||this.logo);s.innerHTML=e}connectedCallback(){var s,e;(s=super.connectedCallback)==null||s.call(this),(e=this.nativeEl)==null||e.addEventListener("muxmetadata",De(this,Rn)),this.nativeEl&&this.src&&!De(this,st,zt)&&En(this,st,js).call(this)}disconnectedCallback(){var s,e;(s=this.nativeEl)==null||s.removeEventListener("muxmetadata",De(this,Rn)),this.unload(),(e=super.disconnectedCallback)==null||e.call(this)}handleEvent(s){s.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(s.type,{composed:!0,detail:s.detail}))}};qs=new WeakMap,Tn=new WeakMap,Ws=new WeakMap,_n=new WeakMap,Sn=new WeakMap,bn=new WeakMap,An=new WeakMap,xn=new WeakMap,Ys=new WeakMap,Rn=new WeakMap,st=new WeakSet,zt=function(){return Uh(this.nativeEl)},In=new WeakMap,js=async function(){De(this,qs)||(await yt(this,qs,Promise.resolve()),yt(this,qs,null),this.load())};var It=new WeakMap,Zi=class extends Error{},Ln=class extends Error{};var MT=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],uf=globalThis.WeakRef?class extends Set{add(s){super.add(new WeakRef(s))}forEach(s){super.forEach(e=>{let t=e.deref();t&&s(t)})}}:Set;function df(s){var e,t,i;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(i=globalThis.cast)!=null&&i.framework?s():customElements.whenDefined("google-cast-button").then(s):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(s)}}function cf(){return globalThis.chrome}function hf(){var t;let s="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${s}"]`))return;let e=document.createElement("script");e.src=s,document.head.append(e)}function Ft(){var s,e;return(e=(s=globalThis.cast)==null?void 0:s.framework)==null?void 0:e.CastContext.getInstance()}function zs(){var s;return(s=Ft())==null?void 0:s.getCurrentSession()}function Dn(){var s;return(s=zs())==null?void 0:s.getSessionObj().media[0]}function ff(s){return new Promise((e,t)=>{Dn().editTracksInfo(s,e,t)})}function mf(s){return new Promise((e,t)=>{Dn().getStatus(s,e,t)})}function Ul(s){return Ft().setOptions({...Bl(),...s})}function Bl(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function NT(s){if(!s)return;let e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=s.match(e);return t?t[1]:null}function FT(s){let e=s.split(`
|
|
139
|
-
`),t=[];for(let i=0;i<e.length;i++)if(e[i].trim().startsWith("#EXT-X-STREAM-INF")){let n=e[i+1]?e[i+1].trim():"";n&&!n.startsWith("#")&&t.push(n)}return t}function
|
|
140
|
-
`).find(i=>!i.trim().startsWith("#")&&i.trim()!=="")}async function gf(s){if(!s)return!1;if(/\.m3u8?(\?.*)?$/i.test(s))return!0;if(s.startsWith("blob:"))return!1;try{let t=(await fetch(s,{method:"HEAD"})).headers.get("Content-Type");return MT.some(i=>t===i)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function pf(s){if(!(!s||s.startsWith("blob:")))try{let e=await(await fetch(s)).text(),t=e,i=FT(e);if(i.length>0){let a=new URL(i[0],s).toString();t=await(await fetch(a)).text()}let r=UT(t);return NT(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}var kn=new uf,Ut=new WeakSet,Ne;df(()=>{var s,e,t,i;if(!((e=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(i=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:i.isAvailable);return}Ne||(Ne=cast.framework,Ft().addEventListener(Ne.CastContextEventType.CAST_STATE_CHANGED,r=>{kn.forEach(n=>{var a,o;return(o=(a=It.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),Ft().addEventListener(Ne.CastContextEventType.SESSION_STATE_CHANGED,r=>{kn.forEach(n=>{var a,o;return(o=(a=It.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),kn.forEach(r=>{var n,a;return(a=(n=It.get(r)).init)==null?void 0:a.call(n)}))});var yf=0,de,es,je,vt,Li,Di,Xt,wn,Xs,be,Ii,vf,Ef,$l,Tf,Gl,_f,Kl,Pn=class extends EventTarget{constructor(t){super();X(this,be);X(this,de);X(this,es);X(this,je);X(this,vt);X(this,Li,"disconnected");X(this,Di,!1);X(this,Xt,new Set);X(this,wn,new WeakMap);X(this,Xs,()=>me(this,be,Kl).call(this));j(this,de,t),kn.add(this),It.set(this,{init:()=>me(this,be,Gl).call(this),onCastStateChanged:()=>me(this,be,$l).call(this),onSessionStateChanged:()=>me(this,be,Tf).call(this),getCastPlayer:()=>D(this,be,Ii)}),me(this,be,Gl).call(this)}destroy(){var t,i,r;(i=(t=D(this,de))==null?void 0:t.textTracks)==null||i.removeEventListener("change",D(this,Xs)),D(this,vt)&&((r=D(this,je))!=null&&r.controller)&&Object.entries(D(this,vt)).forEach(([n,a])=>{D(this,je).controller.removeEventListener(n,a)}),D(this,de)&&Ut.delete(D(this,de)),j(this,es,!1)}get state(){return D(this,Li)}async watchAvailability(t){if(D(this,de).disableRemotePlayback)throw new Zi("disableRemotePlayback attribute is present.");return D(this,wn).set(t,++yf),D(this,Xt).add(t),queueMicrotask(()=>t(me(this,be,Ef).call(this))),yf}async cancelWatchAvailability(t){if(D(this,de).disableRemotePlayback)throw new Zi("disableRemotePlayback attribute is present.");t?D(this,Xt).delete(t):D(this,Xt).clear()}async prompt(){var i,r,n,a;if(D(this,de).disableRemotePlayback)throw new Zi("disableRemotePlayback attribute is present.");if(!((r=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&r.isAvailable))throw new Ln("The RemotePlayback API is disabled on this platform.");let t=Ut.has(D(this,de));Ut.add(D(this,de)),Ul(D(this,de).castOptions),Object.entries(D(this,vt)).forEach(([o,l])=>{D(this,je).controller.addEventListener(o,l)});try{await Ft().requestSession()}catch(o){if(t||Ut.delete(D(this,de)),o==="cancel")return;throw new Error(o)}(a=(n=It.get(D(this,de)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};de=new WeakMap,es=new WeakMap,je=new WeakMap,vt=new WeakMap,Li=new WeakMap,Di=new WeakMap,Xt=new WeakMap,wn=new WeakMap,Xs=new WeakMap,be=new WeakSet,Ii=function(){if(Ut.has(D(this,de)))return D(this,je)},vf=function(){Ut.has(D(this,de))&&(Object.entries(D(this,vt)).forEach(([t,i])=>{D(this,je).controller.removeEventListener(t,i)}),Ut.delete(D(this,de)),D(this,de).muted=D(this,je).isMuted,D(this,de).currentTime=D(this,je).savedPlayerState.currentTime,D(this,je).savedPlayerState.isPaused===!1&&D(this,de).play())},Ef=function(){var i;let t=(i=Ft())==null?void 0:i.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},$l=function(){let t=Ft().getCastState();if(Ut.has(D(this,de))&&t==="CONNECTING"&&(j(this,Li,"connecting"),this.dispatchEvent(new Event("connecting"))),!D(this,Di)&&(t!=null&&t.includes("CONNECT"))){j(this,Di,!0);for(let i of D(this,Xt))i(!0)}else if(D(this,Di)&&(!t||t==="NO_DEVICES_AVAILABLE")){j(this,Di,!1);for(let i of D(this,Xt))i(!1)}},Tf=async function(){var i;let{SESSION_RESUMED:t}=Ne.SessionState;if(Ft().getSessionState()===t&&D(this,de).castSrc===((i=Dn())==null?void 0:i.media.contentId)){Ut.add(D(this,de)),Object.entries(D(this,vt)).forEach(([r,n])=>{D(this,je).controller.addEventListener(r,n)});try{await mf(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}D(this,vt)[Ne.RemotePlayerEventType.IS_PAUSED_CHANGED](),D(this,vt)[Ne.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},Gl=function(){!Ne||D(this,es)||(j(this,es,!0),Ul(D(this,de).castOptions),D(this,de).textTracks.addEventListener("change",D(this,Xs)),me(this,be,$l).call(this),j(this,je,new Ne.RemotePlayer),new Ne.RemotePlayerController(D(this,je)),j(this,vt,{[Ne.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(j(this,Li,"connected"),this.dispatchEvent(new Event("connect"))):(me(this,be,vf).call(this),j(this,Li,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[Ne.RemotePlayerEventType.DURATION_CHANGED]:()=>{D(this,de).dispatchEvent(new Event("durationchange"))},[Ne.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{D(this,de).dispatchEvent(new Event("volumechange"))},[Ne.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{D(this,de).dispatchEvent(new Event("volumechange"))},[Ne.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=D(this,be,Ii))!=null&&t.isMediaLoaded&&D(this,de).dispatchEvent(new Event("timeupdate"))},[Ne.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{D(this,de).dispatchEvent(new Event("resize"))},[Ne.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{D(this,de).dispatchEvent(new Event(this.paused?"pause":"play"))},[Ne.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,i;((t=D(this,be,Ii))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&D(this,de).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(i=D(this,be,Ii))==null?void 0:i.playerState]))},[Ne.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=D(this,be,Ii))!=null&&t.isMediaLoaded&&(await Promise.resolve(),me(this,be,_f).call(this))}}))},_f=function(){me(this,be,Kl).call(this)},Kl=async function(){var h,f,m,p,g;if(!D(this,be,Ii))return;let i=((f=(h=D(this,je).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...D(this,de).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=i.map(({language:v,name:T,trackId:E})=>{var b;let{mode:_}=(b=r.find(x=>x.language===v&&x.label===T))!=null?b:{};return _?{mode:_,trackId:E}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),u=(g=(p=(m=zs())==null?void 0:m.getSessionObj().media[0])==null?void 0:p.activeTrackIds)!=null?g:[],d=u;if(u.length&&(d=d.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(d=[...d,l.trackId]),d=[...new Set(d)],!((v,T)=>v.length===T.length&&v.every(E=>T.includes(E)))(u,d))try{let v=new chrome.cast.media.EditTracksInfoRequest(d);await ff(v)}catch(v){console.error(v)}};var Sf=s=>{var e,t,i,r,n,a,o,ce,bf;return t=class extends s{constructor(){super(...arguments);X(this,o);X(this,i,{paused:!1});X(this,r,Bl());X(this,n);X(this,a)}get remote(){return D(this,a)?D(this,a):cf()?this.isConnected?(this.disableRemotePlayback||hf(),It.set(this,{loadOnPrompt:()=>me(this,o,bf).call(this)}),j(this,a,new Pn(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=D(this,a))==null||h.destroy(),j(this,a,null),It.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,m){if(super.attributeChangedCallback(h,f,m),h==="cast-receiver"&&m){D(this,r).receiverApplicationId=m;return}if(D(this,o,ce))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var T,E;if(!D(this,o,ce))return super.load();let h=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);h.customData=this.castCustomData;let f=[...this.querySelectorAll("track")].filter(({kind:_,src:b})=>b&&(_==="subtitles"||_==="captions")),m=[],p=0;if(f.length&&(h.tracks=f.map(_=>{let b=++p;m.length===0&&_.track.mode==="showing"&&m.push(b);let x=new chrome.cast.media.Track(b,chrome.cast.media.TrackType.TEXT);return x.trackContentId=_.src,x.trackContentType="text/vtt",x.subtype=_.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,x.name=_.label,x.language=_.srclang,x})),this.castStreamType==="live"?h.streamType=chrome.cast.media.StreamType.LIVE:h.streamType=chrome.cast.media.StreamType.BUFFERED,h.metadata=new chrome.cast.media.GenericMediaMetadata,h.metadata.title=this.title,h.metadata.images=[{url:this.poster}],await gf(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let _=await pf(this.castSrc);(_==null?void 0:_.includes("m4s"))||(_==null?void 0:_.includes("mp4"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):_!=null&&_.includes("ts")&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}let v=new chrome.cast.media.LoadRequest(h);v.currentTime=(T=super.currentTime)!=null?T:0,v.autoplay=!D(this,i).paused,v.activeTrackIds=m,await((E=zs())==null?void 0:E.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(D(this,o,ce)){D(this,o,ce).isPaused&&((h=D(this,o,ce).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(D(this,o,ce)){D(this,o,ce).isPaused||(h=D(this,o,ce).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return D(this,r)}get castReceiver(){var h;return(h=this.getAttribute("cast-receiver"))!=null?h:void 0}set castReceiver(h){this.castReceiver!=h&&this.setAttribute("cast-receiver",`${h}`)}get castSrc(){var m,p,g,v,T;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(T=(v=(g=(p=this.getAttribute("cast-src"))!=null?p:(m=this.querySelector("source"))==null?void 0:m.src)!=null?g:f)!=null?v:this.getAttribute("src"))!=null?T:void 0}set castSrc(h){this.castSrc!=h&&this.setAttribute("cast-src",`${h}`)}get castContentType(){var h;return(h=this.getAttribute("cast-content-type"))!=null?h:void 0}set castContentType(h){this.setAttribute("cast-content-type",`${h}`)}get castStreamType(){var h,f;return(f=(h=this.getAttribute("cast-stream-type"))!=null?h:this.streamType)!=null?f:void 0}set castStreamType(h){this.setAttribute("cast-stream-type",`${h}`)}get castCustomData(){return D(this,n)}set castCustomData(h){let f=typeof h;if(!["object","undefined"].includes(f)){console.error(`castCustomData must be nullish or an object but value was of type ${f}`);return}j(this,n,h)}get readyState(){if(D(this,o,ce))switch(D(this,o,ce).playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return D(this,o,ce)?D(this,o,ce).isPaused:super.paused}get muted(){var h;return D(this,o,ce)?(h=D(this,o,ce))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(D(this,o,ce)){(h&&!D(this,o,ce).isMuted||!h&&D(this,o,ce).isMuted)&&((f=D(this,o,ce).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return D(this,o,ce)?(f=(h=D(this,o,ce))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(D(this,o,ce)){D(this,o,ce).volumeLevel=+h,(f=D(this,o,ce).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,m;return D(this,o,ce)&&((h=D(this,o,ce))!=null&&h.isMediaLoaded)?(m=(f=D(this,o,ce))==null?void 0:f.duration)!=null?m:NaN:super.duration}get currentTime(){var h,f,m;return D(this,o,ce)&&((h=D(this,o,ce))!=null&&h.isMediaLoaded)?(m=(f=D(this,o,ce))==null?void 0:f.currentTime)!=null?m:0:super.currentTime}set currentTime(h){var f;if(D(this,o,ce)){D(this,o,ce).currentTime=h,(f=D(this,o,ce).controller)==null||f.seek();return}super.currentTime=h}},i=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,ce=function(){var h,f;return(f=(h=It.get(this.remote))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},bf=async function(){D(this,i).paused=sr(t.prototype,this,"paused"),sr(t.prototype,this,"pause").call(this),this.muted=sr(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},ne(t,"observedAttributes",[...(e=s.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var Bt=class extends Event{constructor(t,i){super(t);ne(this,"track");this.track=i.track}};var Vl=new WeakMap;function H(s){var e;return(e=Vl.get(s))!=null?e:BT(s,{})}function BT(s,e){let t=Vl.get(s);return t||Vl.set(s,t={}),Object.assign(t,e)}function Cn(s,e){let t=s.videoTracks;H(e).media=new WeakRef(s),H(e).renditionSet||(H(e).renditionSet=new Set);let i=H(t).trackSet;i.add(e);let r=i.size-1;r in Pi.prototype||Object.defineProperty(Pi.prototype,r,{get(){return[...H(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Bt("addtrack",{track:e}))})}function On(s){var i,r;let e=(r=(i=H(s).media)==null?void 0:i.deref())==null?void 0:r.videoTracks;if(!e)return;H(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new Bt("removetrack",{track:s}))})}function Af(s){var i,r,n;let e=(n=(r=(i=H(s).media)==null?void 0:i.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==s&&(a.selected=!1,t=!0);if(t){if(H(e).changeRequested)return;H(e).changeRequested=!0,queueMicrotask(()=>{delete H(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var Qt,Jt,Zt,ki,Qs,Pi=class extends EventTarget{constructor(){super();X(this,ki);X(this,Qt);X(this,Jt);X(this,Zt);H(this).trackSet=new Set}[Symbol.iterator](){return D(this,ki,Qs).values()}get length(){return D(this,ki,Qs).size}getTrackById(t){var i;return(i=[...D(this,ki,Qs)].find(r=>r.id===t))!=null?i:null}get selectedIndex(){return[...D(this,ki,Qs)].findIndex(t=>t.selected)}get onaddtrack(){return D(this,Qt)}set onaddtrack(t){D(this,Qt)&&(this.removeEventListener("addtrack",D(this,Qt)),j(this,Qt,void 0)),typeof t=="function"&&(j(this,Qt,t),this.addEventListener("addtrack",t))}get onremovetrack(){return D(this,Jt)}set onremovetrack(t){D(this,Jt)&&(this.removeEventListener("removetrack",D(this,Jt)),j(this,Jt,void 0)),typeof t=="function"&&(j(this,Jt,t),this.addEventListener("removetrack",t))}get onchange(){return D(this,Zt)}set onchange(t){D(this,Zt)&&(this.removeEventListener("change",D(this,Zt)),j(this,Zt,void 0)),typeof t=="function"&&(j(this,Zt,t),this.addEventListener("change",t))}};Qt=new WeakMap,Jt=new WeakMap,Zt=new WeakMap,ki=new WeakSet,Qs=function(){return H(this).trackSet};var $t=class extends Event{constructor(t,i){super(t);ne(this,"rendition");this.rendition=i.rendition}};function xf(s,e){var n,a;let t=(a=(n=H(s).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;H(e).media=H(s).media,H(e).track=s;let i=H(s).renditionSet;i.add(e);let r=i.size-1;r in wi.prototype||Object.defineProperty(wi.prototype,r,{get(){return ts(this)[r]}}),queueMicrotask(()=>{!t||!s.selected||t.dispatchEvent(new $t("addrendition",{rendition:e}))})}function Rf(s){var r,n;let e=(n=(r=H(s).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=H(s).track;H(t).renditionSet.delete(s),queueMicrotask(()=>{let a=H(s).track;!e||!a.selected||e.dispatchEvent(new $t("removerendition",{rendition:s}))})}function If(s){var t,i;let e=(i=(t=H(s).media)==null?void 0:t.deref())==null?void 0:i.videoRenditions;!e||H(e).changeRequested||(H(e).changeRequested=!0,queueMicrotask(()=>{delete H(e).changeRequested,H(s).track.selected&&e.dispatchEvent(new Event("change"))}))}function ts(s){var t;let e=(t=H(s).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(i=>i.selected).flatMap(i=>[...H(i).renditionSet]):[]}var ei,ti,ii,wi=class extends EventTarget{constructor(){super(...arguments);X(this,ei);X(this,ti);X(this,ii)}[Symbol.iterator](){return ts(this).values()}get length(){return ts(this).length}getRenditionById(t){var i;return(i=ts(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return ts(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of ts(this).entries())r.selected=i===t}get onaddrendition(){return D(this,ei)}set onaddrendition(t){D(this,ei)&&(this.removeEventListener("addrendition",D(this,ei)),j(this,ei,void 0)),typeof t=="function"&&(j(this,ei,t),this.addEventListener("addrendition",t))}get onremoverendition(){return D(this,ti)}set onremoverendition(t){D(this,ti)&&(this.removeEventListener("removerendition",D(this,ti)),j(this,ti,void 0)),typeof t=="function"&&(j(this,ti,t),this.addEventListener("removerendition",t))}get onchange(){return D(this,ii)}set onchange(t){D(this,ii)&&(this.removeEventListener("change",D(this,ii)),j(this,ii,void 0)),typeof t=="function"&&(j(this,ii,t),this.addEventListener("change",t))}};ei=new WeakMap,ti=new WeakMap,ii=new WeakMap;var is,Js=class{constructor(){ne(this,"src");ne(this,"id");ne(this,"width");ne(this,"height");ne(this,"bitrate");ne(this,"frameRate");ne(this,"codec");X(this,is,!1)}get selected(){return D(this,is)}set selected(e){D(this,is)!==e&&(j(this,is,e),If(this))}};is=new WeakMap;var ss,rs=class{constructor(){ne(this,"id");ne(this,"kind");ne(this,"label","");ne(this,"language","");ne(this,"sourceBuffer");X(this,ss,!1)}addRendition(e,t,i,r,n,a){let o=new Js;return o.src=e,o.width=t,o.height=i,o.frameRate=a,o.bitrate=n,o.codec=r,xf(this,o),o}removeRendition(e){Rf(e)}get selected(){return D(this,ss)}set selected(e){D(this,ss)!==e&&(j(this,ss,e),e===!0&&Af(this))}};ss=new WeakMap;function Lf(s,e){var n,a;let t=(a=(n=H(s).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;H(e).media=H(s).media,H(e).track=s;let i=H(s).renditionSet;i.add(e);let r=i.size-1;r in Ci.prototype||Object.defineProperty(Ci.prototype,r,{get(){return ns(this)[r]}}),queueMicrotask(()=>{!t||!s.enabled||t.dispatchEvent(new $t("addrendition",{rendition:e}))})}function Df(s){var r,n;let e=(n=(r=H(s).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=H(s).track;H(t).renditionSet.delete(s),queueMicrotask(()=>{let a=H(s).track;!e||!a.enabled||e.dispatchEvent(new $t("removerendition",{rendition:s}))})}function kf(s){var t,i;let e=(i=(t=H(s).media)==null?void 0:t.deref())==null?void 0:i.audioRenditions;!e||H(e).changeRequested||(H(e).changeRequested=!0,queueMicrotask(()=>{delete H(e).changeRequested,H(s).track.enabled&&e.dispatchEvent(new Event("change"))}))}function ns(s){var t;let e=(t=H(s).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(i=>i.enabled).flatMap(i=>[...H(i).renditionSet]):[]}var si,ri,ni,Ci=class extends EventTarget{constructor(){super(...arguments);X(this,si);X(this,ri);X(this,ni)}[Symbol.iterator](){return ns(this).values()}get length(){return ns(this).length}getRenditionById(t){var i;return(i=ns(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return ns(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of ns(this).entries())r.selected=i===t}get onaddrendition(){return D(this,si)}set onaddrendition(t){D(this,si)&&(this.removeEventListener("addrendition",D(this,si)),j(this,si,void 0)),typeof t=="function"&&(j(this,si,t),this.addEventListener("addrendition",t))}get onremoverendition(){return D(this,ri)}set onremoverendition(t){D(this,ri)&&(this.removeEventListener("removerendition",D(this,ri)),j(this,ri,void 0)),typeof t=="function"&&(j(this,ri,t),this.addEventListener("removerendition",t))}get onchange(){return D(this,ni)}set onchange(t){D(this,ni)&&(this.removeEventListener("change",D(this,ni)),j(this,ni,void 0)),typeof t=="function"&&(j(this,ni,t),this.addEventListener("change",t))}};si=new WeakMap,ri=new WeakMap,ni=new WeakMap;var as,Zs=class{constructor(){ne(this,"src");ne(this,"id");ne(this,"bitrate");ne(this,"codec");X(this,as,!1)}get selected(){return D(this,as)}set selected(e){D(this,as)!==e&&(j(this,as,e),kf(this))}};as=new WeakMap;function Nn(s,e){let t=s.audioTracks;H(e).media=new WeakRef(s),H(e).renditionSet||(H(e).renditionSet=new Set);let i=H(t).trackSet;i.add(e);let r=i.size-1;r in Oi.prototype||Object.defineProperty(Oi.prototype,r,{get(){return[...H(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Bt("addtrack",{track:e}))})}function Fn(s){var i,r;let e=(r=(i=H(s).media)==null?void 0:i.deref())==null?void 0:r.audioTracks;if(!e)return;H(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new Bt("removetrack",{track:s}))})}function Pf(s){var t,i;let e=(i=(t=H(s).media)==null?void 0:t.deref())==null?void 0:i.audioTracks;!e||H(e).changeRequested||(H(e).changeRequested=!0,queueMicrotask(()=>{delete H(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var ai,oi,li,os,Mn,Oi=class extends EventTarget{constructor(){super();X(this,os);X(this,ai);X(this,oi);X(this,li);H(this).trackSet=new Set}[Symbol.iterator](){return D(this,os,Mn).values()}get length(){return D(this,os,Mn).size}getTrackById(t){var i;return(i=[...D(this,os,Mn)].find(r=>r.id===t))!=null?i:null}get onaddtrack(){return D(this,ai)}set onaddtrack(t){D(this,ai)&&(this.removeEventListener("addtrack",D(this,ai)),j(this,ai,void 0)),typeof t=="function"&&(j(this,ai,t),this.addEventListener("addtrack",t))}get onremovetrack(){return D(this,oi)}set onremovetrack(t){D(this,oi)&&(this.removeEventListener("removetrack",D(this,oi)),j(this,oi,void 0)),typeof t=="function"&&(j(this,oi,t),this.addEventListener("removetrack",t))}get onchange(){return D(this,li)}set onchange(t){D(this,li)&&(this.removeEventListener("change",D(this,li)),j(this,li,void 0)),typeof t=="function"&&(j(this,li,t),this.addEventListener("change",t))}};ai=new WeakMap,oi=new WeakMap,li=new WeakMap,os=new WeakSet,Mn=function(){return H(this).trackSet};var ls,us=class{constructor(){ne(this,"id");ne(this,"kind");ne(this,"label","");ne(this,"language","");ne(this,"sourceBuffer");X(this,ls,!1)}addRendition(e,t,i){let r=new Zs;return r.src=e,r.codec=t,r.bitrate=i,Lf(this,r),r}removeRendition(e){Df(e)}get enabled(){return D(this,ls)}set enabled(e){D(this,ls)!==e&&(j(this,ls,e),Pf(this))}};ls=new WeakMap;var wf=Un(globalThis.HTMLMediaElement,"video"),Cf=Un(globalThis.HTMLMediaElement,"audio");function Of(s){if(!(s!=null&&s.prototype))return s;let e=Un(s,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"videoTracks",{get(){return $T(this)}});let t=Un(s,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"audioTracks",{get(){return GT(this)}}),"addVideoTrack"in s.prototype||(s.prototype.addVideoTrack=function(n,a="",o=""){let l=new rs;return l.kind=n,l.label=a,l.language=o,Cn(this,l),l}),"removeVideoTrack"in s.prototype||(s.prototype.removeVideoTrack=On),"addAudioTrack"in s.prototype||(s.prototype.addAudioTrack=function(n,a="",o=""){let l=new us;return l.kind=n,l.label=a,l.language=o,Nn(this,l),l}),"removeAudioTrack"in s.prototype||(s.prototype.removeAudioTrack=Fn),"videoRenditions"in s.prototype||Object.defineProperty(s.prototype,"videoRenditions",{get(){return i(this)}});let i=n=>{let a=H(n).videoRenditions;return a||(a=new wi,H(a).media=new WeakRef(n),H(n).videoRenditions=a),a};"audioRenditions"in s.prototype||Object.defineProperty(s.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=H(n).audioRenditions;return a||(a=new Ci,H(a).media=new WeakRef(n),H(n).audioRenditions=a),a};return s}function Un(s,e){var t;if(s!=null&&s.prototype)return(t=Object.getOwnPropertyDescriptor(s.prototype,`${e}Tracks`))==null?void 0:t.get}function $T(s){var t;let e=H(s).videoTracks;if(!e&&(e=new Pi,H(s).videoTracks=e,wf)){let i=wf.call((t=s.nativeEl)!=null?t:s);for(let o of i)Cn(s,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof rs)){for(let l of i)On(l);return}Cn(s,o.track)},a=o=>{On(o.track)};i.addEventListener("change",r),i.addEventListener("addtrack",n),i.addEventListener("removetrack",a)}return e}function GT(s){var t;let e=H(s).audioTracks;if(!e&&(e=new Oi,H(s).audioTracks=e,Cf)){let i=Cf.call((t=s.nativeEl)!=null?t:s);for(let o of i)Nn(s,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof us)){for(let l of i)Fn(l);return}Nn(s,o.track)},a=o=>{Fn(o.track)};i.addEventListener("change",r),i.addEventListener("addtrack",n),i.addEventListener("removetrack",a)}return e}var tr,er=class extends Sf(Of(lf)){constructor(){super(...arguments);X(this,tr)}get autoplay(){let t=this.getAttribute("autoplay");return t===null?!1:t===""?!0:t}set autoplay(t){let i=this.autoplay;t!==i&&(t?this.setAttribute("autoplay",typeof t=="string"?t:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var t;return(t=D(this,tr))!=null?t:this.muxCastCustomData}set castCustomData(t){j(this,tr,t)}};tr=new WeakMap;rr.customElements.get("mux-video")||(rr.customElements.define("mux-video",er),rr.MuxVideoElement=er);var DS=er;})();
|
|
140
|
+
`}get preferCmcd(){var s;return(s=this.getAttribute(M.PREFER_CMCD))!=null?s:void 0}set preferCmcd(s){s!==this.preferCmcd&&(s?yu.includes(s)?this.setAttribute(M.PREFER_CMCD,s):console.warn(`Invalid value for preferCmcd. Must be one of ${yu.join()}`):this.removeAttribute(M.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(M.PLAYER_INIT_TIME)?+this.getAttribute(M.PLAYER_INIT_TIME):$e(this,ia)}set playerInitTime(s){s!=this.playerInitTime&&(s==null?this.removeAttribute(M.PLAYER_INIT_TIME):this.setAttribute(M.PLAYER_INIT_TIME,`${+s}`))}get playerSoftwareName(){var s;return(s=$e(this,aa))!=null?s:wg}set playerSoftwareName(s){Mt(this,aa,s)}get playerSoftwareVersion(){var s;return(s=$e(this,na))!=null?s:Cg}set playerSoftwareVersion(s){Mt(this,na,s)}get _hls(){var s;return(s=$e(this,vt,Ei))==null?void 0:s.engine}get mux(){var s;return(s=this.nativeEl)==null?void 0:s.mux}get error(){var s;return(s=Iu(this.nativeEl))!=null?s:null}get errorTranslator(){return $e(this,oa)}set errorTranslator(s){Mt(this,oa,s)}get src(){return this.getAttribute("src")}set src(s){s!==this.src&&(s==null?this.removeAttribute("src"):this.setAttribute("src",s))}get type(){var s;return(s=this.getAttribute(M.TYPE))!=null?s:void 0}set type(s){s!==this.type&&(s?this.setAttribute(M.TYPE,s):this.removeAttribute(M.TYPE))}get preload(){let s=this.getAttribute("preload");return s===""?"auto":["none","metadata","auto"].includes(s)?s:super.preload}set preload(s){s!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(s)?this.setAttribute("preload",s):this.removeAttribute("preload"))}get debug(){return this.getAttribute(M.DEBUG)!=null}set debug(s){s!==this.debug&&(s?this.setAttribute(M.DEBUG,""):this.removeAttribute(M.DEBUG))}get disableTracking(){return this.hasAttribute(M.DISABLE_TRACKING)}set disableTracking(s){s!==this.disableTracking&&this.toggleAttribute(M.DISABLE_TRACKING,!!s)}get disableCookies(){return this.hasAttribute(M.DISABLE_COOKIES)}set disableCookies(s){s!==this.disableCookies&&(s?this.setAttribute(M.DISABLE_COOKIES,""):this.removeAttribute(M.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(M.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(s){s!==this.disablePseudoEnded&&(s?this.setAttribute(M.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(M.DISABLE_PSEUDO_ENDED))}get maxReconnectRetries(){let s=this.getAttribute(M.MAX_RECONNECT_RETRIES);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set maxReconnectRetries(s){s!==this.maxReconnectRetries&&(s==null?this.removeAttribute(M.MAX_RECONNECT_RETRIES):this.setAttribute(M.MAX_RECONNECT_RETRIES,`${s}`))}get startTime(){let s=this.getAttribute(M.START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set startTime(s){s!==this.startTime&&(s==null?this.removeAttribute(M.START_TIME):this.setAttribute(M.START_TIME,`${s}`))}get initialBandwidthEstimateKbps(){let s=this.getAttribute(M.INITIAL_BANDWIDTH_ESTIMATE_KBPS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set initialBandwidthEstimateKbps(s){s!==this.initialBandwidthEstimateKbps&&(s==null?this.removeAttribute(M.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(M.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${s}`))}get initialEstimateSegments(){let s=this.getAttribute(M.INITIAL_ESTIMATE_SEGMENTS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set initialEstimateSegments(s){s!==this.initialEstimateSegments&&(s==null?this.removeAttribute(M.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(M.INITIAL_ESTIMATE_SEGMENTS,`${s}`))}get minPreloadSegments(){let s=this.getAttribute(M.MIN_PRELOAD_SEGMENTS);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set minPreloadSegments(s){s!==this.minPreloadSegments&&(s==null?this.removeAttribute(M.MIN_PRELOAD_SEGMENTS):this.setAttribute(M.MIN_PRELOAD_SEGMENTS,`${s}`))}get playbackId(){var s;return this.hasAttribute(M.PLAYBACK_ID)?this.getAttribute(M.PLAYBACK_ID):(s=Zn(this.src))!=null?s:void 0}set playbackId(s){s!==this.playbackId&&(s?this.setAttribute(M.PLAYBACK_ID,s):this.removeAttribute(M.PLAYBACK_ID))}get maxResolution(){var s;return(s=this.getAttribute(M.MAX_RESOLUTION))!=null?s:void 0}set maxResolution(s){s!==this.maxResolution&&(s?this.setAttribute(M.MAX_RESOLUTION,s):this.removeAttribute(M.MAX_RESOLUTION))}get minResolution(){var s;return(s=this.getAttribute(M.MIN_RESOLUTION))!=null?s:void 0}set minResolution(s){s!==this.minResolution&&(s?this.setAttribute(M.MIN_RESOLUTION,s):this.removeAttribute(M.MIN_RESOLUTION))}get maxAutoResolution(){var s;return(s=this.getAttribute(M.MAX_AUTO_RESOLUTION))!=null?s:void 0}set maxAutoResolution(s){s==null?this.removeAttribute(M.MAX_AUTO_RESOLUTION):this.setAttribute(M.MAX_AUTO_RESOLUTION,s)}get renditionOrder(){var s;return(s=this.getAttribute(M.RENDITION_ORDER))!=null?s:void 0}set renditionOrder(s){s!==this.renditionOrder&&(s?this.setAttribute(M.RENDITION_ORDER,s):this.removeAttribute(M.RENDITION_ORDER))}get programStartTime(){let s=this.getAttribute(M.PROGRAM_START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set programStartTime(s){s==null?this.removeAttribute(M.PROGRAM_START_TIME):this.setAttribute(M.PROGRAM_START_TIME,`${s}`)}get programEndTime(){let s=this.getAttribute(M.PROGRAM_END_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set programEndTime(s){s==null?this.removeAttribute(M.PROGRAM_END_TIME):this.setAttribute(M.PROGRAM_END_TIME,`${s}`)}get assetStartTime(){let s=this.getAttribute(M.ASSET_START_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set assetStartTime(s){s==null?this.removeAttribute(M.ASSET_START_TIME):this.setAttribute(M.ASSET_START_TIME,`${s}`)}get assetEndTime(){let s=this.getAttribute(M.ASSET_END_TIME);if(s==null)return;let e=+s;return Number.isNaN(e)?void 0:e}set assetEndTime(s){s==null?this.removeAttribute(M.ASSET_END_TIME):this.setAttribute(M.ASSET_END_TIME,`${s}`)}get customDomain(){var s;return(s=this.getAttribute(M.CUSTOM_DOMAIN))!=null?s:void 0}set customDomain(s){s!==this.customDomain&&(s?this.setAttribute(M.CUSTOM_DOMAIN,s):this.removeAttribute(M.CUSTOM_DOMAIN))}get capRenditionToPlayerSize(){var s;return((s=this._hlsConfig)==null?void 0:s.capLevelToPlayerSize)!=null?this._hlsConfig.capLevelToPlayerSize:$e(this,ua)}set capRenditionToPlayerSize(s){Mt(this,ua,s)}get drmToken(){var s;return(s=this.getAttribute(M.DRM_TOKEN))!=null?s:void 0}set drmToken(s){s!==this.drmToken&&(s?this.setAttribute(M.DRM_TOKEN,s):this.removeAttribute(M.DRM_TOKEN))}get playbackToken(){var s,e,t,i;if(this.hasAttribute(M.PLAYBACK_TOKEN))return(s=this.getAttribute(M.PLAYBACK_TOKEN))!=null?s:void 0;if(this.hasAttribute(M.PLAYBACK_ID)){let[,r]=Xn((e=this.playbackId)!=null?e:"");return(t=new URLSearchParams(r).get("token"))!=null?t:void 0}if(this.src)return(i=new URLSearchParams(this.src).get("token"))!=null?i:void 0}set playbackToken(s){s!==this.playbackToken&&(s?this.setAttribute(M.PLAYBACK_TOKEN,s):this.removeAttribute(M.PLAYBACK_TOKEN))}get tokens(){let s=this.getAttribute(M.PLAYBACK_TOKEN),e=this.getAttribute(M.DRM_TOKEN);return{...$e(this,sa),...s!=null?{playback:s}:{},...e!=null?{drm:e}:{}}}set tokens(s){Mt(this,sa,s!=null?s:{})}get ended(){return Du(this.nativeEl,this._hls)}get envKey(){var s;return(s=this.getAttribute(M.ENV_KEY))!=null?s:void 0}set envKey(s){s!==this.envKey&&(s?this.setAttribute(M.ENV_KEY,s):this.removeAttribute(M.ENV_KEY))}get beaconCollectionDomain(){var s;return(s=this.getAttribute(M.BEACON_COLLECTION_DOMAIN))!=null?s:void 0}set beaconCollectionDomain(s){s!==this.beaconCollectionDomain&&(s?this.setAttribute(M.BEACON_COLLECTION_DOMAIN,s):this.removeAttribute(M.BEACON_COLLECTION_DOMAIN))}get streamType(){var s;return(s=this.getAttribute(M.STREAM_TYPE))!=null?s:zn(this.nativeEl)}set streamType(s){s!==this.streamType&&(s?this.setAttribute(M.STREAM_TYPE,s):this.removeAttribute(M.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(M.TARGET_LIVE_WINDOW)?+this.getAttribute(M.TARGET_LIVE_WINDOW):dg(this.nativeEl)}set targetLiveWindow(s){s!=this.targetLiveWindow&&(s==null?this.removeAttribute(M.TARGET_LIVE_WINDOW):this.setAttribute(M.TARGET_LIVE_WINDOW,`${+s}`))}get liveEdgeStart(){var s,e;if(this.hasAttribute(M.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:t}=this,i=(s=this.nativeEl.seekable.end(0))!=null?s:0,r=(e=this.nativeEl.seekable.start(0))!=null?e:0;return Math.max(r,i-t)}return cg(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(M.LIVE_EDGE_OFFSET))return+this.getAttribute(M.LIVE_EDGE_OFFSET)}set liveEdgeOffset(s){s!=this.liveEdgeOffset&&(s==null?this.removeAttribute(M.LIVE_EDGE_OFFSET):this.setAttribute(M.LIVE_EDGE_OFFSET,`${+s}`))}get seekable(){return ea(this.nativeEl)}async addCuePoints(s){return this.nativeEl.currentSrc||console.warn("addCuePoints() was called before the media element has loaded. Wait for the loadstart event before calling addCuePoints()."),_u(this.nativeEl,s)}get activeCuePoint(){return Su(this.nativeEl)}get cuePoints(){return eg(this.nativeEl)}async addChapters(s){return this.nativeEl.currentSrc||console.warn("addChapters() was called before the media element has loaded. Wait for the loadstart event before calling addChapters()."),Au(this.nativeEl,s)}get activeChapter(){return Ru(this.nativeEl)}get chapters(){return ig(this.nativeEl)}getStartDate(){return sg(this.nativeEl,this._hls)}get currentPdt(){return rg(this.nativeEl,this._hls)}get preferPlayback(){let s=this.getAttribute(M.PREFER_PLAYBACK);if(s===Yi.MSE||s===Yi.NATIVE)return s}set preferPlayback(s){s!==this.preferPlayback&&(s===Yi.MSE||s===Yi.NATIVE?this.setAttribute(M.PREFER_PLAYBACK,s):this.removeAttribute(M.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(s=>s.startsWith("metadata-")&&![M.METADATA_URL].includes(s)).reduce((s,e)=>{let t=this.getAttribute(e);return t!=null&&(s[e.replace(/^metadata-/,"").replace(/-/g,"_")]=t),s},{}),...$e(this,Tr)}}set metadata(s){Mt(this,Tr,s!=null?s:{}),this.mux&&this.mux.emit("hb",$e(this,Tr))}get _hlsConfig(){return $e(this,ra)}set _hlsConfig(s){Mt(this,ra,s)}get logo(){var s;return(s=this.getAttribute(M.LOGO))!=null?s:$e(this,_r)}set logo(s){s?this.setAttribute(M.LOGO,s):this.removeAttribute(M.LOGO)}load(){ku(this,this.nativeEl,$e(this,vt,Ei))}unload(){Pu(this.nativeEl,$e(this,vt,Ei),this)}attributeChangedCallback(s,e,t){var i,r;switch(yr.observedAttributes.includes(s)&&!["src","autoplay","preload"].includes(s)&&super.attributeChangedCallback(s,e,t),s){case M.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=t!=null?t:void 0;break;case M.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=t!=null?t:void 0;break;case"src":{let n=!!e,a=!!t;!n&&a?ta(this,vt,Sr).call(this):n&&!a?this.unload():n&&a&&(this.unload(),ta(this,vt,Sr).call(this));break}case"autoplay":if(t===e)break;(i=$e(this,vt,Ei))==null||i.setAutoplay(this.autoplay);break;case"preload":if(t===e)break;(r=$e(this,vt,Ei))==null||r.setPreload(t);break;case M.PLAYBACK_ID:case M.CUSTOM_DOMAIN:case M.MAX_RESOLUTION:case M.MIN_RESOLUTION:case M.RENDITION_ORDER:case M.PROGRAM_START_TIME:case M.PROGRAM_END_TIME:case M.ASSET_START_TIME:case M.ASSET_END_TIME:case M.PLAYBACK_TOKEN:this.hasAttribute(M.PLAYBACK_ID)&&(this.src=lg(this));break;case M.DEBUG:{let n=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=n);break}case M.METADATA_URL:t&&fetch(t).then(n=>n.json()).then(n=>this.metadata=n).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${t}!`));break;case M.STREAM_TYPE:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case M.TARGET_LIVE_WINDOW:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case M.LOGO:(t==null||t!==e)&&this.updateLogo();break;case M.DISABLE_TRACKING:{if(t==null||t!==e){let n=this.currentTime,a=this.paused;this.unload(),ta(this,vt,Sr).call(this).then(()=>{this.currentTime=n,a||this.play()})}break}case M.DISABLE_COOKIES:{(t==null||t!==e)&&mg(this,this.nativeEl,$e(this,vt,Ei));break}case M.CAP_RENDITION_TO_PLAYER_SIZE:(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0)}}updateLogo(){if(!this.shadowRoot)return;let s=this.shadowRoot.querySelector('slot[name="logo"]');if(!s)return;let e=this.constructor.getLogoHTML($e(this,_r)||this.logo);s.innerHTML=e}connectedCallback(){var s,e;(s=super.connectedCallback)==null||s.call(this),(e=this.nativeEl)==null||e.addEventListener("muxmetadata",$e(this,la)),this.nativeEl&&this.src&&!$e(this,vt,Ei)&&ta(this,vt,Sr).call(this)}disconnectedCallback(){var s,e;(s=this.nativeEl)==null||s.removeEventListener("muxmetadata",$e(this,la)),this.unload(),(e=super.disconnectedCallback)==null||e.call(this)}handleEvent(s){s.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(s.type,{composed:!0,detail:s.detail}))}};Er=new WeakMap,ia=new WeakMap,Tr=new WeakMap,sa=new WeakMap,ra=new WeakMap,na=new WeakMap,aa=new WeakMap,oa=new WeakMap,_r=new WeakMap,la=new WeakMap,vt=new WeakSet,Ei=function(){return hg(this.nativeEl)},ua=new WeakMap,Sr=async function(){$e(this,Er)||(await Mt(this,Er,Promise.resolve()),Mt(this,Er,null),this.load())};var Wt=new WeakMap,ys=class extends Error{},da=class extends Error{};var jS=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],Ng=globalThis.WeakRef?class extends Set{add(s){super.add(new WeakRef(s))}forEach(s){super.forEach(e=>{let t=e.deref();t&&s(t)})}}:Set;function Fg(s){var e,t,i;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(i=globalThis.cast)!=null&&i.framework?s():customElements.whenDefined("google-cast-button").then(s):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(s)}}function Bg(){return globalThis.chrome}function Ug(){var t;let s="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${s}"]`))return;let e=document.createElement("script");e.src=s,document.head.append(e)}function si(){var s,e;return(e=(s=globalThis.cast)==null?void 0:s.framework)==null?void 0:e.CastContext.getInstance()}function br(){var s;return(s=si())==null?void 0:s.getCurrentSession()}function ca(){var s;return(s=br())==null?void 0:s.getSessionObj().media[0]}function $g(s){return new Promise((e,t)=>{ca().editTracksInfo(s,e,t)})}function Gg(s){return new Promise((e,t)=>{ca().getStatus(s,e,t)})}function Nu(s){return si().setOptions({...Fu(),...s})}function Fu(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function zS(s){if(!s)return;let e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=s.match(e);return t?t[1]:null}function XS(s){let e=s.split(`
|
|
141
|
+
`),t=[];for(let i=0;i<e.length;i++)if(e[i].trim().startsWith("#EXT-X-STREAM-INF")){let n=e[i+1]?e[i+1].trim():"";n&&!n.startsWith("#")&&t.push(n)}return t}function QS(s){return s.split(`
|
|
142
|
+
`).find(i=>!i.trim().startsWith("#")&&i.trim()!=="")}async function Kg(s){if(!s)return!1;if(/\.m3u8?(\?.*)?$/i.test(s))return!0;if(s.startsWith("blob:"))return!1;try{let t=(await fetch(s,{method:"HEAD"})).headers.get("Content-Type");return jS.some(i=>t===i)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function Vg(s){if(!(!s||s.startsWith("blob:")))try{let e=await(await fetch(s)).text(),t=e,i=XS(e);if(i.length>0){let a=new URL(i[0],s).toString();t=await(await fetch(a)).text()}let r=QS(t);return zS(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}var ha=new Ng,ri=new WeakSet,je;Fg(()=>{var s,e,t,i;if(!((e=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(i=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:i.isAvailable);return}je||(je=cast.framework,si().addEventListener(je.CastContextEventType.CAST_STATE_CHANGED,r=>{ha.forEach(n=>{var a,o;return(o=(a=Wt.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),si().addEventListener(je.CastContextEventType.SESSION_STATE_CHANGED,r=>{ha.forEach(n=>{var a,o;return(o=(a=Wt.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),ha.forEach(r=>{var n,a;return(a=(n=Wt.get(r)).init)==null?void 0:a.call(n)}))});var Hg=0,Ee,Es,ot,Nt,Xi,Qi,Ti,ga,Ar,Ce,zi,qg,Wg,Bu,Yg,Uu,jg,$u,fa=class extends EventTarget{constructor(t){super();te(this,Ce);te(this,Ee);te(this,Es);te(this,ot);te(this,Nt);te(this,Xi,"disconnected");te(this,Qi,!1);te(this,Ti,new Set);te(this,ga,new WeakMap);te(this,Ar,()=>Ae(this,Ce,$u).call(this));Z(this,Ee,t),ha.add(this),Wt.set(this,{init:()=>Ae(this,Ce,Uu).call(this),onCastStateChanged:()=>Ae(this,Ce,Bu).call(this),onSessionStateChanged:()=>Ae(this,Ce,Yg).call(this),getCastPlayer:()=>D(this,Ce,zi)}),Ae(this,Ce,Uu).call(this)}destroy(){var t,i,r;(i=(t=D(this,Ee))==null?void 0:t.textTracks)==null||i.removeEventListener("change",D(this,Ar)),D(this,Nt)&&((r=D(this,ot))!=null&&r.controller)&&Object.entries(D(this,Nt)).forEach(([n,a])=>{D(this,ot).controller.removeEventListener(n,a)}),D(this,Ee)&&ri.delete(D(this,Ee)),Z(this,Es,!1)}get state(){return D(this,Xi)}async watchAvailability(t){if(D(this,Ee).disableRemotePlayback)throw new ys("disableRemotePlayback attribute is present.");return D(this,ga).set(t,++Hg),D(this,Ti).add(t),queueMicrotask(()=>t(Ae(this,Ce,Wg).call(this))),Hg}async cancelWatchAvailability(t){if(D(this,Ee).disableRemotePlayback)throw new ys("disableRemotePlayback attribute is present.");t?D(this,Ti).delete(t):D(this,Ti).clear()}async prompt(){var i,r,n,a;if(D(this,Ee).disableRemotePlayback)throw new ys("disableRemotePlayback attribute is present.");if(!((r=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&r.isAvailable))throw new da("The RemotePlayback API is disabled on this platform.");let t=ri.has(D(this,Ee));ri.add(D(this,Ee)),Nu(D(this,Ee).castOptions),Object.entries(D(this,Nt)).forEach(([o,l])=>{D(this,ot).controller.addEventListener(o,l)});try{await si().requestSession()}catch(o){if(t||ri.delete(D(this,Ee)),o==="cancel")return;throw new Error(o)}(a=(n=Wt.get(D(this,Ee)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};Ee=new WeakMap,Es=new WeakMap,ot=new WeakMap,Nt=new WeakMap,Xi=new WeakMap,Qi=new WeakMap,Ti=new WeakMap,ga=new WeakMap,Ar=new WeakMap,Ce=new WeakSet,zi=function(){if(ri.has(D(this,Ee)))return D(this,ot)},qg=function(){ri.has(D(this,Ee))&&(Object.entries(D(this,Nt)).forEach(([t,i])=>{D(this,ot).controller.removeEventListener(t,i)}),ri.delete(D(this,Ee)),D(this,Ee).muted=D(this,ot).isMuted,D(this,Ee).currentTime=D(this,ot).savedPlayerState.currentTime,D(this,ot).savedPlayerState.isPaused===!1&&D(this,Ee).play())},Wg=function(){var i;let t=(i=si())==null?void 0:i.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},Bu=function(){let t=si().getCastState();if(ri.has(D(this,Ee))&&t==="CONNECTING"&&(Z(this,Xi,"connecting"),this.dispatchEvent(new Event("connecting"))),!D(this,Qi)&&(t!=null&&t.includes("CONNECT"))){Z(this,Qi,!0);for(let i of D(this,Ti))i(!0)}else if(D(this,Qi)&&(!t||t==="NO_DEVICES_AVAILABLE")){Z(this,Qi,!1);for(let i of D(this,Ti))i(!1)}},Yg=async function(){var i;let{SESSION_RESUMED:t}=je.SessionState;if(si().getSessionState()===t&&D(this,Ee).castSrc===((i=ca())==null?void 0:i.media.contentId)){ri.add(D(this,Ee)),Object.entries(D(this,Nt)).forEach(([r,n])=>{D(this,ot).controller.addEventListener(r,n)});try{await Gg(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}D(this,Nt)[je.RemotePlayerEventType.IS_PAUSED_CHANGED](),D(this,Nt)[je.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},Uu=function(){!je||D(this,Es)||(Z(this,Es,!0),Nu(D(this,Ee).castOptions),D(this,Ee).textTracks.addEventListener("change",D(this,Ar)),Ae(this,Ce,Bu).call(this),Z(this,ot,new je.RemotePlayer),new je.RemotePlayerController(D(this,ot)),Z(this,Nt,{[je.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(Z(this,Xi,"connected"),this.dispatchEvent(new Event("connect"))):(Ae(this,Ce,qg).call(this),Z(this,Xi,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[je.RemotePlayerEventType.DURATION_CHANGED]:()=>{D(this,Ee).dispatchEvent(new Event("durationchange"))},[je.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{D(this,Ee).dispatchEvent(new Event("volumechange"))},[je.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{D(this,Ee).dispatchEvent(new Event("volumechange"))},[je.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=D(this,Ce,zi))!=null&&t.isMediaLoaded&&D(this,Ee).dispatchEvent(new Event("timeupdate"))},[je.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{D(this,Ee).dispatchEvent(new Event("resize"))},[je.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{D(this,Ee).dispatchEvent(new Event(this.paused?"pause":"play"))},[je.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,i;((t=D(this,Ce,zi))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&D(this,Ee).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(i=D(this,Ce,zi))==null?void 0:i.playerState]))},[je.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=D(this,Ce,zi))!=null&&t.isMediaLoaded&&(await Promise.resolve(),Ae(this,Ce,jg).call(this))}}))},jg=function(){Ae(this,Ce,$u).call(this)},$u=async function(){var h,f,g,m,p;if(!D(this,Ce,zi))return;let i=((f=(h=D(this,ot).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:y})=>y===chrome.cast.media.TrackType.TEXT),r=[...D(this,Ee).textTracks].filter(({kind:y})=>y==="subtitles"||y==="captions"),n=i.map(({language:y,name:T,trackId:v})=>{var S;let{mode:_}=(S=r.find(A=>A.language===y&&A.label===T))!=null?S:{};return _?{mode:_,trackId:v}:!1}).filter(Boolean),o=n.filter(({mode:y})=>y!=="showing").map(({trackId:y})=>y),l=n.find(({mode:y})=>y==="showing"),u=(p=(m=(g=br())==null?void 0:g.getSessionObj().media[0])==null?void 0:m.activeTrackIds)!=null?p:[],d=u;if(u.length&&(d=d.filter(y=>!o.includes(y))),l!=null&&l.trackId&&(d=[...d,l.trackId]),d=[...new Set(d)],!((y,T)=>y.length===T.length&&y.every(v=>T.includes(v)))(u,d))try{let y=new chrome.cast.media.EditTracksInfoRequest(d);await $g(y)}catch(y){console.error(y)}};var zg=s=>{var e,t,i,r,n,a,o,_e,Xg;return t=class extends s{constructor(){super(...arguments);te(this,o);te(this,i,{paused:!1});te(this,r,Fu());te(this,n);te(this,a)}get remote(){return D(this,a)?D(this,a):Bg()?this.isConnected?(this.disableRemotePlayback||Ug(),Wt.set(this,{loadOnPrompt:()=>Ae(this,o,Xg).call(this)}),Z(this,a,new fa(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=D(this,a))==null||h.destroy(),Z(this,a,null),Wt.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,g){if(super.attributeChangedCallback(h,f,g),h==="cast-receiver"&&g){D(this,r).receiverApplicationId=g;return}if(D(this,o,_e))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var T,v;if(!D(this,o,_e))return super.load();let h=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);h.customData=this.castCustomData;let f=[...this.querySelectorAll("track")].filter(({kind:_,src:S})=>S&&(_==="subtitles"||_==="captions")),g=[],m=0;if(f.length&&(h.tracks=f.map(_=>{let S=++m;g.length===0&&_.track.mode==="showing"&&g.push(S);let A=new chrome.cast.media.Track(S,chrome.cast.media.TrackType.TEXT);return A.trackContentId=_.src,A.trackContentType="text/vtt",A.subtype=_.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,A.name=_.label,A.language=_.srclang,A})),this.castStreamType==="live"?h.streamType=chrome.cast.media.StreamType.LIVE:h.streamType=chrome.cast.media.StreamType.BUFFERED,h.metadata=new chrome.cast.media.GenericMediaMetadata,h.metadata.title=this.title,h.metadata.images=[{url:this.poster}],await Kg(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let _=await Vg(this.castSrc);(_==null?void 0:_.includes("m4s"))||(_==null?void 0:_.includes("mp4"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):_!=null&&_.includes("ts")&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}let y=new chrome.cast.media.LoadRequest(h);y.currentTime=(T=super.currentTime)!=null?T:0,y.autoplay=!D(this,i).paused,y.activeTrackIds=g,await((v=br())==null?void 0:v.loadMedia(y)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(D(this,o,_e)){D(this,o,_e).isPaused&&((h=D(this,o,_e).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(D(this,o,_e)){D(this,o,_e).isPaused||(h=D(this,o,_e).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return D(this,r)}get castReceiver(){var h;return(h=this.getAttribute("cast-receiver"))!=null?h:void 0}set castReceiver(h){this.castReceiver!=h&&this.setAttribute("cast-receiver",`${h}`)}get castSrc(){var g,m,p,y,T;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(T=(y=(p=(m=this.getAttribute("cast-src"))!=null?m:(g=this.querySelector("source"))==null?void 0:g.src)!=null?p:f)!=null?y:this.getAttribute("src"))!=null?T:void 0}set castSrc(h){this.castSrc!=h&&this.setAttribute("cast-src",`${h}`)}get castContentType(){var h;return(h=this.getAttribute("cast-content-type"))!=null?h:void 0}set castContentType(h){this.setAttribute("cast-content-type",`${h}`)}get castStreamType(){var h,f;return(f=(h=this.getAttribute("cast-stream-type"))!=null?h:this.streamType)!=null?f:void 0}set castStreamType(h){this.setAttribute("cast-stream-type",`${h}`)}get castCustomData(){return D(this,n)}set castCustomData(h){let f=typeof h;if(!["object","undefined"].includes(f)){console.error(`castCustomData must be nullish or an object but value was of type ${f}`);return}Z(this,n,h)}get readyState(){if(D(this,o,_e))switch(D(this,o,_e).playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return D(this,o,_e)?D(this,o,_e).isPaused:super.paused}get muted(){var h;return D(this,o,_e)?(h=D(this,o,_e))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(D(this,o,_e)){(h&&!D(this,o,_e).isMuted||!h&&D(this,o,_e).isMuted)&&((f=D(this,o,_e).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return D(this,o,_e)?(f=(h=D(this,o,_e))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(D(this,o,_e)){D(this,o,_e).volumeLevel=+h,(f=D(this,o,_e).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,g;return D(this,o,_e)&&((h=D(this,o,_e))!=null&&h.isMediaLoaded)?(g=(f=D(this,o,_e))==null?void 0:f.duration)!=null?g:NaN:super.duration}get currentTime(){var h,f,g;return D(this,o,_e)&&((h=D(this,o,_e))!=null&&h.isMediaLoaded)?(g=(f=D(this,o,_e))==null?void 0:f.currentTime)!=null?g:0:super.currentTime}set currentTime(h){var f;if(D(this,o,_e)){D(this,o,_e).currentTime=h,(f=D(this,o,_e).controller)==null||f.seek();return}super.currentTime=h}},i=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,_e=function(){var h,f;return(f=(h=Wt.get(this.remote))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},Xg=async function(){D(this,i).paused=kr(t.prototype,this,"paused"),kr(t.prototype,this,"pause").call(this),this.muted=kr(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},fe(t,"observedAttributes",[...(e=s.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var ni=class extends Event{constructor(t,i){super(t);fe(this,"track");this.track=i.track}};var Gu=new WeakMap;function q(s){var e;return(e=Gu.get(s))!=null?e:JS(s,{})}function JS(s,e){let t=Gu.get(s);return t||Gu.set(s,t={}),Object.assign(t,e)}function ma(s,e){let t=s.videoTracks;q(e).media=new WeakRef(s),q(e).renditionSet||(q(e).renditionSet=new Set);let i=q(t).trackSet;i.add(e);let r=i.size-1;r in Zi.prototype||Object.defineProperty(Zi.prototype,r,{get(){return[...q(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new ni("addtrack",{track:e}))})}function pa(s){var i,r;let e=(r=(i=q(s).media)==null?void 0:i.deref())==null?void 0:r.videoTracks;if(!e)return;q(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new ni("removetrack",{track:s}))})}function Qg(s){var i,r,n;let e=(n=(r=(i=q(s).media)==null?void 0:i.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==s&&(a.selected=!1,t=!0);if(t){if(q(e).changeRequested)return;q(e).changeRequested=!0,queueMicrotask(()=>{delete q(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var _i,Si,bi,Ji,Rr,Zi=class extends EventTarget{constructor(){super();te(this,Ji);te(this,_i);te(this,Si);te(this,bi);q(this).trackSet=new Set}[Symbol.iterator](){return D(this,Ji,Rr).values()}get length(){return D(this,Ji,Rr).size}getTrackById(t){var i;return(i=[...D(this,Ji,Rr)].find(r=>r.id===t))!=null?i:null}get selectedIndex(){return[...D(this,Ji,Rr)].findIndex(t=>t.selected)}get onaddtrack(){return D(this,_i)}set onaddtrack(t){D(this,_i)&&(this.removeEventListener("addtrack",D(this,_i)),Z(this,_i,void 0)),typeof t=="function"&&(Z(this,_i,t),this.addEventListener("addtrack",t))}get onremovetrack(){return D(this,Si)}set onremovetrack(t){D(this,Si)&&(this.removeEventListener("removetrack",D(this,Si)),Z(this,Si,void 0)),typeof t=="function"&&(Z(this,Si,t),this.addEventListener("removetrack",t))}get onchange(){return D(this,bi)}set onchange(t){D(this,bi)&&(this.removeEventListener("change",D(this,bi)),Z(this,bi,void 0)),typeof t=="function"&&(Z(this,bi,t),this.addEventListener("change",t))}};_i=new WeakMap,Si=new WeakMap,bi=new WeakMap,Ji=new WeakSet,Rr=function(){return q(this).trackSet};var ai=class extends Event{constructor(t,i){super(t);fe(this,"rendition");this.rendition=i.rendition}};function Jg(s,e){var n,a;let t=(a=(n=q(s).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;q(e).media=q(s).media,q(e).track=s;let i=q(s).renditionSet;i.add(e);let r=i.size-1;r in es.prototype||Object.defineProperty(es.prototype,r,{get(){return Ts(this)[r]}}),queueMicrotask(()=>{!t||!s.selected||t.dispatchEvent(new ai("addrendition",{rendition:e}))})}function Zg(s){var r,n;let e=(n=(r=q(s).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=q(s).track;q(t).renditionSet.delete(s),queueMicrotask(()=>{let a=q(s).track;!e||!a.selected||e.dispatchEvent(new ai("removerendition",{rendition:s}))})}function em(s){var t,i;let e=(i=(t=q(s).media)==null?void 0:t.deref())==null?void 0:i.videoRenditions;!e||q(e).changeRequested||(q(e).changeRequested=!0,queueMicrotask(()=>{delete q(e).changeRequested,q(s).track.selected&&e.dispatchEvent(new Event("change"))}))}function Ts(s){var t;let e=(t=q(s).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(i=>i.selected).flatMap(i=>[...q(i).renditionSet]):[]}var Ai,Ri,xi,es=class extends EventTarget{constructor(){super(...arguments);te(this,Ai);te(this,Ri);te(this,xi)}[Symbol.iterator](){return Ts(this).values()}get length(){return Ts(this).length}getRenditionById(t){var i;return(i=Ts(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return Ts(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of Ts(this).entries())r.selected=i===t}get onaddrendition(){return D(this,Ai)}set onaddrendition(t){D(this,Ai)&&(this.removeEventListener("addrendition",D(this,Ai)),Z(this,Ai,void 0)),typeof t=="function"&&(Z(this,Ai,t),this.addEventListener("addrendition",t))}get onremoverendition(){return D(this,Ri)}set onremoverendition(t){D(this,Ri)&&(this.removeEventListener("removerendition",D(this,Ri)),Z(this,Ri,void 0)),typeof t=="function"&&(Z(this,Ri,t),this.addEventListener("removerendition",t))}get onchange(){return D(this,xi)}set onchange(t){D(this,xi)&&(this.removeEventListener("change",D(this,xi)),Z(this,xi,void 0)),typeof t=="function"&&(Z(this,xi,t),this.addEventListener("change",t))}};Ai=new WeakMap,Ri=new WeakMap,xi=new WeakMap;var _s,xr=class{constructor(){fe(this,"src");fe(this,"id");fe(this,"width");fe(this,"height");fe(this,"bitrate");fe(this,"frameRate");fe(this,"codec");te(this,_s,!1)}get selected(){return D(this,_s)}set selected(e){D(this,_s)!==e&&(Z(this,_s,e),em(this))}};_s=new WeakMap;var Ss,bs=class{constructor(){fe(this,"id");fe(this,"kind");fe(this,"label","");fe(this,"language","");fe(this,"sourceBuffer");te(this,Ss,!1)}addRendition(e,t,i,r,n,a){let o=new xr;return o.src=e,o.width=t,o.height=i,o.frameRate=a,o.bitrate=n,o.codec=r,Jg(this,o),o}removeRendition(e){Zg(e)}get selected(){return D(this,Ss)}set selected(e){D(this,Ss)!==e&&(Z(this,Ss,e),e===!0&&Qg(this))}};Ss=new WeakMap;function tm(s,e){var n,a;let t=(a=(n=q(s).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;q(e).media=q(s).media,q(e).track=s;let i=q(s).renditionSet;i.add(e);let r=i.size-1;r in ts.prototype||Object.defineProperty(ts.prototype,r,{get(){return As(this)[r]}}),queueMicrotask(()=>{!t||!s.enabled||t.dispatchEvent(new ai("addrendition",{rendition:e}))})}function im(s){var r,n;let e=(n=(r=q(s).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=q(s).track;q(t).renditionSet.delete(s),queueMicrotask(()=>{let a=q(s).track;!e||!a.enabled||e.dispatchEvent(new ai("removerendition",{rendition:s}))})}function sm(s){var t,i;let e=(i=(t=q(s).media)==null?void 0:t.deref())==null?void 0:i.audioRenditions;!e||q(e).changeRequested||(q(e).changeRequested=!0,queueMicrotask(()=>{delete q(e).changeRequested,q(s).track.enabled&&e.dispatchEvent(new Event("change"))}))}function As(s){var t;let e=(t=q(s).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(i=>i.enabled).flatMap(i=>[...q(i).renditionSet]):[]}var Ii,Li,Di,ts=class extends EventTarget{constructor(){super(...arguments);te(this,Ii);te(this,Li);te(this,Di)}[Symbol.iterator](){return As(this).values()}get length(){return As(this).length}getRenditionById(t){var i;return(i=As(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return As(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of As(this).entries())r.selected=i===t}get onaddrendition(){return D(this,Ii)}set onaddrendition(t){D(this,Ii)&&(this.removeEventListener("addrendition",D(this,Ii)),Z(this,Ii,void 0)),typeof t=="function"&&(Z(this,Ii,t),this.addEventListener("addrendition",t))}get onremoverendition(){return D(this,Li)}set onremoverendition(t){D(this,Li)&&(this.removeEventListener("removerendition",D(this,Li)),Z(this,Li,void 0)),typeof t=="function"&&(Z(this,Li,t),this.addEventListener("removerendition",t))}get onchange(){return D(this,Di)}set onchange(t){D(this,Di)&&(this.removeEventListener("change",D(this,Di)),Z(this,Di,void 0)),typeof t=="function"&&(Z(this,Di,t),this.addEventListener("change",t))}};Ii=new WeakMap,Li=new WeakMap,Di=new WeakMap;var Rs,Ir=class{constructor(){fe(this,"src");fe(this,"id");fe(this,"bitrate");fe(this,"codec");te(this,Rs,!1)}get selected(){return D(this,Rs)}set selected(e){D(this,Rs)!==e&&(Z(this,Rs,e),sm(this))}};Rs=new WeakMap;function ya(s,e){let t=s.audioTracks;q(e).media=new WeakRef(s),q(e).renditionSet||(q(e).renditionSet=new Set);let i=q(t).trackSet;i.add(e);let r=i.size-1;r in is.prototype||Object.defineProperty(is.prototype,r,{get(){return[...q(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new ni("addtrack",{track:e}))})}function Ea(s){var i,r;let e=(r=(i=q(s).media)==null?void 0:i.deref())==null?void 0:r.audioTracks;if(!e)return;q(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new ni("removetrack",{track:s}))})}function rm(s){var t,i;let e=(i=(t=q(s).media)==null?void 0:t.deref())==null?void 0:i.audioTracks;!e||q(e).changeRequested||(q(e).changeRequested=!0,queueMicrotask(()=>{delete q(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var ki,Pi,Ci,xs,va,is=class extends EventTarget{constructor(){super();te(this,xs);te(this,ki);te(this,Pi);te(this,Ci);q(this).trackSet=new Set}[Symbol.iterator](){return D(this,xs,va).values()}get length(){return D(this,xs,va).size}getTrackById(t){var i;return(i=[...D(this,xs,va)].find(r=>r.id===t))!=null?i:null}get onaddtrack(){return D(this,ki)}set onaddtrack(t){D(this,ki)&&(this.removeEventListener("addtrack",D(this,ki)),Z(this,ki,void 0)),typeof t=="function"&&(Z(this,ki,t),this.addEventListener("addtrack",t))}get onremovetrack(){return D(this,Pi)}set onremovetrack(t){D(this,Pi)&&(this.removeEventListener("removetrack",D(this,Pi)),Z(this,Pi,void 0)),typeof t=="function"&&(Z(this,Pi,t),this.addEventListener("removetrack",t))}get onchange(){return D(this,Ci)}set onchange(t){D(this,Ci)&&(this.removeEventListener("change",D(this,Ci)),Z(this,Ci,void 0)),typeof t=="function"&&(Z(this,Ci,t),this.addEventListener("change",t))}};ki=new WeakMap,Pi=new WeakMap,Ci=new WeakMap,xs=new WeakSet,va=function(){return q(this).trackSet};var Is,Ls=class{constructor(){fe(this,"id");fe(this,"kind");fe(this,"label","");fe(this,"language","");fe(this,"sourceBuffer");te(this,Is,!1)}addRendition(e,t,i){let r=new Ir;return r.src=e,r.codec=t,r.bitrate=i,tm(this,r),r}removeRendition(e){im(e)}get enabled(){return D(this,Is)}set enabled(e){D(this,Is)!==e&&(Z(this,Is,e),rm(this))}};Is=new WeakMap;var nm=Ta(globalThis.HTMLMediaElement,"video"),am=Ta(globalThis.HTMLMediaElement,"audio");function om(s){if(!(s!=null&&s.prototype))return s;let e=Ta(s,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"videoTracks",{get(){return ZS(this)}});let t=Ta(s,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"audioTracks",{get(){return eb(this)}}),"addVideoTrack"in s.prototype||(s.prototype.addVideoTrack=function(n,a="",o=""){let l=new bs;return l.kind=n,l.label=a,l.language=o,ma(this,l),l}),"removeVideoTrack"in s.prototype||(s.prototype.removeVideoTrack=pa),"addAudioTrack"in s.prototype||(s.prototype.addAudioTrack=function(n,a="",o=""){let l=new Ls;return l.kind=n,l.label=a,l.language=o,ya(this,l),l}),"removeAudioTrack"in s.prototype||(s.prototype.removeAudioTrack=Ea),"videoRenditions"in s.prototype||Object.defineProperty(s.prototype,"videoRenditions",{get(){return i(this)}});let i=n=>{let a=q(n).videoRenditions;return a||(a=new es,q(a).media=new WeakRef(n),q(n).videoRenditions=a),a};"audioRenditions"in s.prototype||Object.defineProperty(s.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=q(n).audioRenditions;return a||(a=new ts,q(a).media=new WeakRef(n),q(n).audioRenditions=a),a};return s}function Ta(s,e){var t;if(s!=null&&s.prototype)return(t=Object.getOwnPropertyDescriptor(s.prototype,`${e}Tracks`))==null?void 0:t.get}function ZS(s){var t;let e=q(s).videoTracks;if(!e&&(e=new Zi,q(s).videoTracks=e,nm)){let i=nm.call((t=s.nativeEl)!=null?t:s);for(let o of i)ma(s,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof bs)){for(let l of i)pa(l);return}ma(s,o.track)},a=o=>{pa(o.track)};i.addEventListener("change",r),i.addEventListener("addtrack",n),i.addEventListener("removetrack",a)}return e}function eb(s){var t;let e=q(s).audioTracks;if(!e&&(e=new is,q(s).audioTracks=e,am)){let i=am.call((t=s.nativeEl)!=null?t:s);for(let o of i)ya(s,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof Ls)){for(let l of i)Ea(l);return}ya(s,o.track)},a=o=>{Ea(o.track)};i.addEventListener("change",r),i.addEventListener("addtrack",n),i.addEventListener("removetrack",a)}return e}var Dr,Lr=class extends zg(om(Mg)){constructor(){super(...arguments);te(this,Dr)}get autoplay(){let t=this.getAttribute("autoplay");return t===null?!1:t===""?!0:t}set autoplay(t){let i=this.autoplay;t!==i&&(t?this.setAttribute("autoplay",typeof t=="string"?t:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var t;return(t=D(this,Dr))!=null?t:this.muxCastCustomData}set castCustomData(t){Z(this,Dr,t)}};Dr=new WeakMap;Pr.customElements.get("mux-video")||(Pr.customElements.define("mux-video",Lr),Pr.MuxVideoElement=Lr);var qA=Lr;})();
|
|
141
143
|
/*! Bundled license information:
|
|
142
144
|
|
|
143
145
|
mux-embed/dist/mux.mjs:
|