@mux/mux-player 3.14.1-canary.0 → 3.14.1-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-player.js +40 -40
- package/dist/mux-player.mjs +40 -40
- package/package.json +1 -1
package/dist/mux-player.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";(()=>{var DR=Object.defineProperty;var CR=Object.getPrototypeOf;var wR=Reflect.get;var ey=i=>{throw TypeError(i)};var MR=(i,e,t)=>e in i?DR(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Oe=(i,e,t)=>MR(i,typeof e!="symbol"?e+"":e,t),Lm=(i,e,t)=>e.has(i)||ey("Cannot "+t);var M=(i,e,t)=>(Lm(i,e,"read from private field"),t?t.call(i):e.get(i)),fe=(i,e,t)=>e.has(i)?ey("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),le=(i,e,t,s)=>(Lm(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),ze=(i,e,t)=>(Lm(i,e,"access private method"),t);var Jd=(i,e,t)=>wR(CR(i),t,e);var na=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends na{}globalThis.DocumentFragment=i}var Bo=class extends na{},xm=class extends na{},PR={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(Bo)}},$o,km=class{constructor(e,t={}){fe(this,$o);le(this,$o,t==null?void 0:t.detail)}get detail(){return M(this,$o)}initCustomEvent(){}};$o=new WeakMap;function OR(i,e){return new Bo}var ty={document:{createElement:OR},DocumentFragment,customElements:PR,CustomEvent:km,EventTarget:na,HTMLElement:Bo,HTMLVideoElement:xm},iy=typeof window=="undefined"||typeof globalThis.customElements=="undefined",eu=iy?ty:globalThis,QU=iy?ty.document:globalThis.document;var NR=Object.create,uy=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,FR=Object.getOwnPropertyNames,BR=Object.getPrototypeOf,$R=Object.prototype.hasOwnProperty,cy=function(i,e){return function(){return i&&(e=i(i=0)),e}},bi=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},HR=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=FR(e),n=0,a=r.length,o;n<a;n++)o=r[n],!$R.call(i,o)&&o!==t&&uy(i,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(s=UR(e,o))||s.enumerable});return i},GR=function(i,e,t){return t=i!=null?NR(BR(i)):{},HR(e||!i||!i.__esModule?uy(t,"default",{value:i,enumerable:!0}):t,i)};function fn(i,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):fn(i,e)}var mn=cy(function(){mn()});function hy(i){"@swc/helpers - typeof";return i&&typeof Symbol!="undefined"&&i.constructor===Symbol?"symbol":typeof i}var fy=cy(function(){}),my=bi(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(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))}}}),KR=bi(function(i,e){mn(),e.exports=t;function t(s,r){if(!fn(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),VR=bi(function(i,e){mn(),e.exports=t;function t(s,r){if(!fn(this,t))return new t(s);this.data=s||"",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(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),py=bi(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),gy=bi(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),vy=bi(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),WR=bi(function(i,e){fy(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(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+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=hy(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 d(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],b=(v.prefix?v.prefix+":":"")+g;f.push({name:b,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return u(h).replace(/"/g,""")}}),Ey=bi(function(i,e){mn();var t=my(),s=py(),r=gy(),n=vy(),a=WR(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!fn(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),qR=bi(function(i,e){mn();var t=Ey();e.exports=s;function s(r){if(!fn(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),YR=bi(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),jR=bi(function(i,e){mn();var t=my(),s=KR(),r=VR(),n=Ey(),a=qR(),o=YR(),l=py(),d=gy(),u=vy();e.exports=c;function c(){if(!fn(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 s(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=u,h.addEventListener=d,h.dispatchEvent=l}),zR=bi(function(i,e){var t=jR();e.exports=new t}),QR=bi(function(i,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},s=zR(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function XR(i){if(Array.isArray(i))return i}function ZR(i,e){var t=i==null?null:typeof Symbol!="undefined"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function JR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1
|
+
"use strict";(()=>{var DR=Object.defineProperty;var CR=Object.getPrototypeOf;var wR=Reflect.get;var ey=i=>{throw TypeError(i)};var MR=(i,e,t)=>e in i?DR(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Oe=(i,e,t)=>MR(i,typeof e!="symbol"?e+"":e,t),Lm=(i,e,t)=>e.has(i)||ey("Cannot "+t);var M=(i,e,t)=>(Lm(i,e,"read from private field"),t?t.call(i):e.get(i)),fe=(i,e,t)=>e.has(i)?ey("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),le=(i,e,t,s)=>(Lm(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),ze=(i,e,t)=>(Lm(i,e,"access private method"),t);var Jd=(i,e,t)=>wR(CR(i),t,e);var na=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends na{}globalThis.DocumentFragment=i}var Bo=class extends na{},xm=class extends na{},PR={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(Bo)}},$o,km=class{constructor(e,t={}){fe(this,$o);le(this,$o,t==null?void 0:t.detail)}get detail(){return M(this,$o)}initCustomEvent(){}};$o=new WeakMap;function OR(i,e){return new Bo}var ty={document:{createElement:OR},DocumentFragment,customElements:PR,CustomEvent:km,EventTarget:na,HTMLElement:Bo,HTMLVideoElement:xm},iy=typeof window=="undefined"||typeof globalThis.customElements=="undefined",eu=iy?ty:globalThis,QU=iy?ty.document:globalThis.document;var NR=Object.create,uy=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,FR=Object.getOwnPropertyNames,BR=Object.getPrototypeOf,$R=Object.prototype.hasOwnProperty,cy=function(i,e){return function(){return i&&(e=i(i=0)),e}},bi=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},HR=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=FR(e),n=0,a=r.length,o;n<a;n++)o=r[n],!$R.call(i,o)&&o!==t&&uy(i,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(s=UR(e,o))||s.enumerable});return i},GR=function(i,e,t){return t=i!=null?NR(BR(i)):{},HR(e||!i||!i.__esModule?uy(t,"default",{value:i,enumerable:!0}):t,i)};function fn(i,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):fn(i,e)}var mn=cy(function(){mn()});function hy(i){"@swc/helpers - typeof";return i&&typeof Symbol!="undefined"&&i.constructor===Symbol?"symbol":typeof i}var fy=cy(function(){}),my=bi(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(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))}}}),KR=bi(function(i,e){mn(),e.exports=t;function t(s,r){if(!fn(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),VR=bi(function(i,e){mn(),e.exports=t;function t(s,r){if(!fn(this,t))return new t(s);this.data=s||"",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(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),py=bi(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),gy=bi(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),vy=bi(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),WR=bi(function(i,e){fy(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(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+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=hy(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 d(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],E=(v.prefix?v.prefix+":":"")+g;f.push({name:E,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return u(h).replace(/"/g,""")}}),Ey=bi(function(i,e){mn();var t=my(),s=py(),r=gy(),n=vy(),a=WR(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!fn(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),qR=bi(function(i,e){mn();var t=Ey();e.exports=s;function s(r){if(!fn(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),YR=bi(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),jR=bi(function(i,e){mn();var t=my(),s=KR(),r=VR(),n=Ey(),a=qR(),o=YR(),l=py(),d=gy(),u=vy();e.exports=c;function c(){if(!fn(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 s(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=u,h.addEventListener=d,h.dispatchEvent=l}),zR=bi(function(i,e){var t=jR();e.exports=new t}),QR=bi(function(i,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},s=zR(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function XR(i){if(Array.isArray(i))return i}function ZR(i,e){var t=i==null?null:typeof Symbol!="undefined"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function JR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
2
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wm(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=i[t];return s}function yy(i,e){if(i){if(typeof i=="string")return wm(i,e);var t=Object.prototype.toString.call(i).slice(8,-1);if(t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set")return Array.from(t);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return wm(i,e)}}function Ks(i,e){return XR(i)||ZR(i,e)||yy(i,e)||JR()}var eL=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof self!="undefined"?self:{},Me=eL,tL={now:function(){var i=Me.performance,e=i&&i.timing,t=e&&e.navigationStart,s=typeof t=="number"&&typeof i.now=="function"?t+i.now():Date.now();return Math.round(s)}},$t=tL,Go=function(){var i,e,t;if(typeof((i=Me.crypto)===null||i===void 0?void 0:i.getRandomValues)=="function"){t=new Uint8Array(32),Me.crypto.getRandomValues(t);for(var s=0;s<32;s++)t[s]=t[s]%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 d=l==="x"?t[n]:t[n]&3|8;return n++,d.toString(16)});var a=$t.now(),o=a==null?void 0:a.toString(16).substring(3);return o?e.substring(0,28)+o:e},by=function(){return("000000"+(Math.random()*Math.pow(36,6)<<0).toString(36)).slice(-6)},Hi=function(i){if(i&&typeof i.nodeName!="undefined")return i.muxId||(i.muxId=by()),i.muxId;var e;try{e=document.querySelector(i)}catch{}return e&&!e.muxId&&(e.muxId=i),(e==null?void 0:e.muxId)||i},su=function(i){var e;i&&typeof i.nodeName!="undefined"?(e=i,i=Hi(e)):e=document.querySelector(i);var t=e&&e.nodeName?e.nodeName.toLowerCase():"";return[e,i,t]};function iL(i){if(Array.isArray(i))return wm(i)}function sL(i){if(typeof Symbol!="undefined"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function rL(){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 Gi(i){return iL(i)||sL(i)||yy(i)||rL()}var hn={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},nL=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=i?[console,i]:[console],l=(t=console.trace).bind.apply(t,Gi(o)),d=(s=console.info).bind.apply(s,Gi(o)),u=(r=console.debug).bind.apply(r,Gi(o)),c=(n=console.warn).bind.apply(n,Gi(o)),h=(a=console.error).bind.apply(a,Gi(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>hn.TRACE))return l.apply(void 0,Gi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.DEBUG))return u.apply(void 0,Gi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.INFO))return d.apply(void 0,Gi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.WARN))return c.apply(void 0,Gi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.ERROR))return h.apply(void 0,Gi(p))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},st=nL("[mux]");function Mm(){var i=Me.doNotTrack||Me.navigator&&Me.navigator.doNotTrack;return i==="1"}function ve(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}mn();function _t(i,e){if(!fn(i,e))throw new TypeError("Cannot call a class as a function")}function sy(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function ki(i,e,t){return e&&sy(i.prototype,e),t&&sy(i,t),i}function z(i,e,t){return e in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function la(i){return la=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},la(i)}function aL(i,e){for(;!Object.prototype.hasOwnProperty.call(i,e)&&(i=la(i),i!==null););return i}function iu(i,e,t){return typeof Reflect!="undefined"&&Reflect.get?iu=Reflect.get:iu=function(s,r,n){var a=aL(s,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||s):o.value}},iu(i,e,t||i)}function Pm(i,e){return Pm=Object.setPrototypeOf||function(t,s){return t.__proto__=s,t},Pm(i,e)}function oL(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&Pm(i,e)}function lL(i,e){if(i==null)return{};var t={},s=Object.keys(i),r,n;for(n=0;n<s.length;n++)r=s[n],!(e.indexOf(r)>=0)&&(t[r]=i[r]);return t}function dL(i,e){if(i==null)return{};var t=lL(i,e),s,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(r=0;r<n.length;r++)s=n[r],!(e.indexOf(s)>=0)&&Object.prototype.propertyIsEnumerable.call(i,s)&&(t[s]=i[s])}return t}function uL(){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}}fy();function cL(i,e){return e&&(hy(e)==="object"||typeof e=="function")?e:ve(i)}function hL(i){var e=uL();return function(){var t=la(i),s;if(e){var r=la(this).constructor;s=Reflect.construct(t,arguments,r)}else s=t.apply(this,arguments);return cL(this,s)}}var Ki=function(i){return Ko(i)[0]},Ko=function(i){if(typeof i!="string"||i==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=i.match(e)||[],s=t[4],r;return s&&(r=(s.match(/[^\.]+\.[^\.]+$/)||[])[0]),[s,r]},fL={exists:function(){var i=Me.performance,e=i&&i.timing;return e!==void 0},domContentLoadedEventEnd:function(){var i=Me.performance,e=i&&i.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var i=Me.performance,e=i&&i.timing;return e&&e.navigationStart}},ru=fL;function Ot(i,e,t){t=t===void 0?1:t,i[e]=i[e]||0,i[e]+=t}function Vo(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},s=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(s=s.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),s.forEach(function(r){z(i,r,t[r])})}return i}function mL(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Nm(i,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)):mL(Object(e)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(e,t))}),i}var pL=["x-cdn","content-type"],Ty=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],gL=pL.concat(Ty);function Um(i){i=i||"";var e={},t=i.trim().split(/[\r\n]+/);return t.forEach(function(s){if(s){var r=s.split(": "),n=r.shift();n&&(gL.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function nu(i){if(i){var e=Ty.find(function(t){return i[t]!==void 0});return e?i[e]:void 0}}var vL=function(i){var e={};for(var t in i){var s=i[t],r=s["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=s["DATA-ID"].replace("io.litix.data.","");e[n]=s.VALUE}}return e},_y=vL,tu=function(i){if(!i)return{};var e=ru.navigationStart(),t=i.loading,s=t?t.start:i.trequest,r=t?t.first:i.tfirst,n=t?t.end:i.tload;return{bytesLoaded:i.total,requestStart:Math.round(e+s),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Ho=function(i){if(!(!i||typeof i.getAllResponseHeaders!="function"))return Um(i.getAllResponseHeaders())},EL=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=i.log,a=i.utils.secondsToMs,o=function(v){var b=parseInt(r.version),E;return b===1&&v.programDateTime!==null&&(E=v.programDateTime),b===0&&v.pdt!==null&&(E=v.pdt),E};if(!ru.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,b){return i.emit(e,v,b)},d=function(v,b){var E=b.levels,T=b.audioTracks,_=b.url,I=b.stats,S=b.networkDetails,x=b.sessionData,k={},R={};E.forEach(function(O,F){k[F]={width:O.width,height:O.height,bitrate:O.bitrate,attrs:O.attrs}}),T.forEach(function(O,F){R[F]={name:O.name,language:O.lang,bitrate:O.bitrate}});var D=tu(I),w=D.bytesLoaded,N=D.requestStart,$=D.responseStart,H=D.responseEnd;l("requestcompleted",Nm(Vo({},_y(x)),{request_event_type:v,request_bytes_loaded:w,request_start:N,request_response_start:$,request_response_end:H,request_type:"manifest",request_hostname:Ki(_),request_response_headers:Ho(S),request_rendition_lists:{media:k,audio:R,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,d);var u=function(v,b){var E=b.details,T=b.level,_=b.networkDetails,I=b.stats,S=tu(I),x=S.bytesLoaded,k=S.requestStart,R=S.responseStart,D=S.responseEnd,w=E.fragments[E.fragments.length-1],N=o(w)+a(w.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:x,request_start:k,request_response_start:R,request_response_end:D,request_current_level:T,request_type:"manifest",request_hostname:Ki(E.url),request_response_headers:Ho(_),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(N)?void 0:N})};t.on(r.Events.LEVEL_LOADED,u);var c=function(v,b){var E=b.details,T=b.networkDetails,_=b.stats,I=tu(_),S=I.bytesLoaded,x=I.requestStart,k=I.responseStart,R=I.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:S,request_start:x,request_response_start:k,request_response_end:R,request_type:"manifest",request_hostname:Ki(E.url),request_response_headers:Ho(T)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(v,b){var E=b.stats,T=b.networkDetails,_=b.frag;E=E||_.stats;var I=tu(E),S=I.bytesLoaded,x=I.requestStart,k=I.responseStart,R=I.responseEnd,D=T?Ho(T):void 0,w={request_event_type:v,request_bytes_loaded:S,request_start:x,request_response_start:k,request_response_end:R,request_hostname:T?Ki(T.responseURL):void 0,request_id:D?nu(D):void 0,request_response_headers:D,request_media_duration:_.duration,request_url:T==null?void 0:T.responseURL};_.type==="main"?(w.request_type="media",w.request_current_level=_.level,w.request_video_width=(t.levels[_.level]||{}).width,w.request_video_height=(t.levels[_.level]||{}).height,w.request_labeled_bitrate=(t.levels[_.level]||{}).bitrate):w.request_type=_.type,l("requestcompleted",w)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,b){var E=b.frag,T=E.start,_=o(E),I={currentFragmentPDT:_,currentFragmentStart:a(T)};l("fragmentchange",I)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,b){var E=b.type,T=b.details,_=b.response,I=b.fatal,S=b.frag,x=b.networkDetails,k=(S==null?void 0:S.url)||b.url||"",R=x?Ho(x):void 0;if((T===r.ErrorDetails.MANIFEST_LOAD_ERROR||T===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT||T===r.ErrorDetails.LEVEL_LOAD_ERROR||T===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:T,request_url:k,request_hostname:Ki(k),request_id:R?nu(R):void 0,request_type:T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:_==null?void 0:_.code,request_error_text:_==null?void 0:_.text}),I){var D,w="".concat(k?"url: ".concat(k,`
|
|
3
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gi(i){return iL(i)||sL(i)||yy(i)||rL()}var hn={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},nL=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=i?[console,i]:[console],l=(t=console.trace).bind.apply(t,Gi(o)),d=(s=console.info).bind.apply(s,Gi(o)),u=(r=console.debug).bind.apply(r,Gi(o)),c=(n=console.warn).bind.apply(n,Gi(o)),h=(a=console.error).bind.apply(a,Gi(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>hn.TRACE))return l.apply(void 0,Gi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.DEBUG))return u.apply(void 0,Gi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.INFO))return d.apply(void 0,Gi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.WARN))return c.apply(void 0,Gi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>hn.ERROR))return h.apply(void 0,Gi(p))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},st=nL("[mux]");function Mm(){var i=Me.doNotTrack||Me.navigator&&Me.navigator.doNotTrack;return i==="1"}function ve(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}mn();function _t(i,e){if(!fn(i,e))throw new TypeError("Cannot call a class as a function")}function sy(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function ki(i,e,t){return e&&sy(i.prototype,e),t&&sy(i,t),i}function z(i,e,t){return e in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function la(i){return la=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},la(i)}function aL(i,e){for(;!Object.prototype.hasOwnProperty.call(i,e)&&(i=la(i),i!==null););return i}function iu(i,e,t){return typeof Reflect!="undefined"&&Reflect.get?iu=Reflect.get:iu=function(s,r,n){var a=aL(s,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||s):o.value}},iu(i,e,t||i)}function Pm(i,e){return Pm=Object.setPrototypeOf||function(t,s){return t.__proto__=s,t},Pm(i,e)}function oL(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&Pm(i,e)}function lL(i,e){if(i==null)return{};var t={},s=Object.keys(i),r,n;for(n=0;n<s.length;n++)r=s[n],!(e.indexOf(r)>=0)&&(t[r]=i[r]);return t}function dL(i,e){if(i==null)return{};var t=lL(i,e),s,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(r=0;r<n.length;r++)s=n[r],!(e.indexOf(s)>=0)&&Object.prototype.propertyIsEnumerable.call(i,s)&&(t[s]=i[s])}return t}function uL(){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}}fy();function cL(i,e){return e&&(hy(e)==="object"||typeof e=="function")?e:ve(i)}function hL(i){var e=uL();return function(){var t=la(i),s;if(e){var r=la(this).constructor;s=Reflect.construct(t,arguments,r)}else s=t.apply(this,arguments);return cL(this,s)}}var Ki=function(i){return Ko(i)[0]},Ko=function(i){if(typeof i!="string"||i==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=i.match(e)||[],s=t[4],r;return s&&(r=(s.match(/[^\.]+\.[^\.]+$/)||[])[0]),[s,r]},fL={exists:function(){var i=Me.performance,e=i&&i.timing;return e!==void 0},domContentLoadedEventEnd:function(){var i=Me.performance,e=i&&i.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var i=Me.performance,e=i&&i.timing;return e&&e.navigationStart}},ru=fL;function Ot(i,e,t){t=t===void 0?1:t,i[e]=i[e]||0,i[e]+=t}function Vo(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},s=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(s=s.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),s.forEach(function(r){z(i,r,t[r])})}return i}function mL(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Nm(i,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)):mL(Object(e)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(e,t))}),i}var pL=["x-cdn","content-type"],Ty=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],gL=pL.concat(Ty);function Um(i){i=i||"";var e={},t=i.trim().split(/[\r\n]+/);return t.forEach(function(s){if(s){var r=s.split(": "),n=r.shift();n&&(gL.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function nu(i){if(i){var e=Ty.find(function(t){return i[t]!==void 0});return e?i[e]:void 0}}var vL=function(i){var e={};for(var t in i){var s=i[t],r=s["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=s["DATA-ID"].replace("io.litix.data.","");e[n]=s.VALUE}}return e},_y=vL,tu=function(i){if(!i)return{};var e=ru.navigationStart(),t=i.loading,s=t?t.start:i.trequest,r=t?t.first:i.tfirst,n=t?t.end:i.tload;return{bytesLoaded:i.total,requestStart:Math.round(e+s),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Ho=function(i){if(!(!i||typeof i.getAllResponseHeaders!="function"))return Um(i.getAllResponseHeaders())},EL=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=i.log,a=i.utils.secondsToMs,o=function(v){var E=parseInt(r.version),b;return E===1&&v.programDateTime!==null&&(b=v.programDateTime),E===0&&v.pdt!==null&&(b=v.pdt),b};if(!ru.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,E){return i.emit(e,v,E)},d=function(v,E){var b=E.levels,T=E.audioTracks,_=E.url,I=E.stats,S=E.networkDetails,x=E.sessionData,k={},R={};b.forEach(function(O,F){k[F]={width:O.width,height:O.height,bitrate:O.bitrate,attrs:O.attrs}}),T.forEach(function(O,F){R[F]={name:O.name,language:O.lang,bitrate:O.bitrate}});var D=tu(I),w=D.bytesLoaded,N=D.requestStart,$=D.responseStart,H=D.responseEnd;l("requestcompleted",Nm(Vo({},_y(x)),{request_event_type:v,request_bytes_loaded:w,request_start:N,request_response_start:$,request_response_end:H,request_type:"manifest",request_hostname:Ki(_),request_response_headers:Ho(S),request_rendition_lists:{media:k,audio:R,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,d);var u=function(v,E){var b=E.details,T=E.level,_=E.networkDetails,I=E.stats,S=tu(I),x=S.bytesLoaded,k=S.requestStart,R=S.responseStart,D=S.responseEnd,w=b.fragments[b.fragments.length-1],N=o(w)+a(w.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:x,request_start:k,request_response_start:R,request_response_end:D,request_current_level:T,request_type:"manifest",request_hostname:Ki(b.url),request_response_headers:Ho(_),video_holdback:b.holdBack&&a(b.holdBack),video_part_holdback:b.partHoldBack&&a(b.partHoldBack),video_part_target_duration:b.partTarget&&a(b.partTarget),video_target_duration:b.targetduration&&a(b.targetduration),video_source_is_live:b.live,player_manifest_newest_program_time:isNaN(N)?void 0:N})};t.on(r.Events.LEVEL_LOADED,u);var c=function(v,E){var b=E.details,T=E.networkDetails,_=E.stats,I=tu(_),S=I.bytesLoaded,x=I.requestStart,k=I.responseStart,R=I.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:S,request_start:x,request_response_start:k,request_response_end:R,request_type:"manifest",request_hostname:Ki(b.url),request_response_headers:Ho(T)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(v,E){var b=E.stats,T=E.networkDetails,_=E.frag;b=b||_.stats;var I=tu(b),S=I.bytesLoaded,x=I.requestStart,k=I.responseStart,R=I.responseEnd,D=T?Ho(T):void 0,w={request_event_type:v,request_bytes_loaded:S,request_start:x,request_response_start:k,request_response_end:R,request_hostname:T?Ki(T.responseURL):void 0,request_id:D?nu(D):void 0,request_response_headers:D,request_media_duration:_.duration,request_url:T==null?void 0:T.responseURL};_.type==="main"?(w.request_type="media",w.request_current_level=_.level,w.request_video_width=(t.levels[_.level]||{}).width,w.request_video_height=(t.levels[_.level]||{}).height,w.request_labeled_bitrate=(t.levels[_.level]||{}).bitrate):w.request_type=_.type,l("requestcompleted",w)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,E){var b=E.frag,T=b.start,_=o(b),I={currentFragmentPDT:_,currentFragmentStart:a(T)};l("fragmentchange",I)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,E){var b=E.type,T=E.details,_=E.response,I=E.fatal,S=E.frag,x=E.networkDetails,k=(S==null?void 0:S.url)||E.url||"",R=x?Ho(x):void 0;if((T===r.ErrorDetails.MANIFEST_LOAD_ERROR||T===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT||T===r.ErrorDetails.LEVEL_LOAD_ERROR||T===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:T,request_url:k,request_hostname:Ki(k),request_id:R?nu(R):void 0,request_type:T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:_==null?void 0:_.code,request_error_text:_==null?void 0:_.text}),I){var D,w="".concat(k?"url: ".concat(k,`
|
|
4
4
|
`):"")+"".concat(_&&(_.code||_.text)?"response: ".concat(_.code,", ").concat(_.text,`
|
|
5
|
-
`):"")+"".concat(
|
|
6
|
-
`):"")+"".concat(
|
|
7
|
-
`):"")+"".concat(
|
|
8
|
-
`):"")+"".concat(
|
|
9
|
-
`):"")+"".concat(
|
|
10
|
-
`):"")+"".concat(
|
|
11
|
-
`):"")+"".concat(
|
|
12
|
-
`):"");l("error",{player_error_code:
|
|
5
|
+
`):"")+"".concat(E.reason?"failure reason: ".concat(E.reason,`
|
|
6
|
+
`):"")+"".concat(E.level?"level: ".concat(E.level,`
|
|
7
|
+
`):"")+"".concat(E.parent?"parent stream controller: ".concat(E.parent,`
|
|
8
|
+
`):"")+"".concat(E.buffer?"buffer length: ".concat(E.buffer,`
|
|
9
|
+
`):"")+"".concat(E.error?"error: ".concat(E.error,`
|
|
10
|
+
`):"")+"".concat(E.event?"event: ".concat(E.event,`
|
|
11
|
+
`):"")+"".concat(E.err?"error message: ".concat((D=E.err)===null||D===void 0?void 0:D.message,`
|
|
12
|
+
`):"");l("error",{player_error_code:b,player_error_message:T,player_error_context:w})}};t.on(r.Events.ERROR,m);var p=function(v,E){var b=E.frag,T=b&&b._url||"";l("requestcanceled",{request_event_type:v,request_url:T,request_type:"media",request_hostname:Ki(T)})};t.on(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p);var g=function(v,E){var b=E.level,T=t.levels[b];if(T&&T.attrs&&T.attrs.BANDWIDTH){var _=T.attrs.BANDWIDTH,I,S=parseFloat(T.attrs["FRAME-RATE"]);isNaN(S)||(I=S),_?l("renditionchange",{video_source_fps:I,video_source_bitrate:_,video_source_width:T.width,video_source_height:T.height,video_source_rendition_name:T.name,video_source_codec:T==null?void 0:T.videoCodec}):n.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(r.Events.LEVEL_SWITCHED,g),t._stopMuxMonitor=function(){t.off(r.Events.MANIFEST_LOADED,d),t.off(r.Events.LEVEL_LOADED,u),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,m),t.off(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p),t.off(r.Events.LEVEL_SWITCHED,g),t.off(r.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(r.Events.DESTROYING,t._stopMuxMonitor)},yL=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},ry=function(i,e){if(!i||!i.requestEndDate)return{};var t=Ki(i.url),s=i.url,r=i.bytesLoaded,n=new Date(i.requestStartDate).getTime(),a=new Date(i.firstByteDate).getTime(),o=new Date(i.requestEndDate).getTime(),l=isNaN(i.duration)?0:i.duration,d=typeof e.getMetricsFor=="function"?e.getMetricsFor(i.mediaType).HttpList:e.getDashMetrics().getHttpRequests(i.mediaType),u;d.length>0&&(u=Um(d[d.length-1]._responseHeaders||""));var c=u?nu(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:s,requestId:c}},bL=function(i,e){if(typeof e.getCurrentRepresentationForType=="function"){var t=e.getCurrentRepresentationForType(i);return t?{currentLevel:t.absoluteIndex,renditionWidth:t.width||null,renditionHeight:t.height||null,renditionBitrate:t.bandwidth}:{}}var s=e.getQualityFor(i),r=e.getCurrentTrackFor(i).bitrateList;return r?{currentLevel:s,renditionWidth:r[s].width||null,renditionHeight:r[s].height||null,renditionBitrate:r[s].bandwidth}:{}},TL=function(i){var e;return(e=i.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},_L=function(i){try{var e,t,s=(t=i.getVersion)===null||t===void 0||(e=t.call(i))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return s}catch{return!1}},AL=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=i.log;if(!t||!t.on){r.warn("Invalid dash.js player reference. Monitoring blocked.");return}var n=_L(t),a=function(b,T){return i.emit(e,b,T)},o=function(b){var T=b.type,_=b.data,I=(_||{}).url;a("requestcompleted",{request_event_type:T,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:Ki(I),request_url:I})};t.on("manifestLoaded",o);var l={},d=function(b){if(typeof b.getRequests!="function")return null;var T=b.getRequests({state:"executed"});return T.length===0?null:T[T.length-1]},u=function(b){var T=b.type,_=b.fragmentModel,I=b.chunk,S=d(_);c({type:T,request:S,chunk:I})},c=function(b){var T=b.type,_=b.chunk,I=b.request,S=(_||{}).mediaInfo,x=S||{},k=x.type,R=x.bitrateList;R=R||[];var D={};R.forEach(function(K,q){D[q]={},D[q].width=K.width,D[q].height=K.height,D[q].bitrate=K.bandwidth,D[q].attrs={}}),k==="video"?l.video=D:k==="audio"?l.audio=D:l.media=D;var w=ry(I,t),N=w.requestStart,$=w.requestResponseStart,H=w.requestResponseEnd,O=w.requestResponseHeaders,F=w.requestMediaDuration,B=w.requestHostname,W=w.requestUrl,Z=w.requestId;a("requestcompleted",{request_event_type:T,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:-1,request_type:k+"_init",request_response_headers:O,request_hostname:B,request_id:Z,request_url:W,request_media_duration:F,request_rendition_lists:l})};n>=4?t.on("initFragmentLoaded",c):t.on("initFragmentLoaded",u);var h=function(b){var T=b.type,_=b.fragmentModel,I=b.chunk,S=d(_);f({type:T,request:S,chunk:I})},f=function(b){var T=b.type,_=b.chunk,I=b.request,S=_||{},x=S.mediaInfo,k=S.start,R=x||{},D=R.type,w=ry(I,t),N=w.requestStart,$=w.requestResponseStart,H=w.requestResponseEnd,O=w.requestBytesLoaded,F=w.requestResponseHeaders,B=w.requestMediaDuration,W=w.requestHostname,Z=w.requestUrl,K=w.requestId,q=bL(D,t),ce=q.currentLevel,re=q.renditionWidth,ye=q.renditionHeight,ue=q.renditionBitrate;a("requestcompleted",{request_event_type:T,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:O,request_type:D,request_response_headers:F,request_hostname:W,request_id:K,request_url:Z,request_media_start_time:k,request_media_duration:B,request_current_level:ce,request_labeled_bitrate:ue,request_video_width:re,request_video_height:ye})};n>=4?t.on("mediaFragmentLoaded",f):t.on("mediaFragmentLoaded",h);var m={video:void 0,audio:void 0,totalBitrate:void 0},p=function(){if(m.video&&typeof m.video.bitrate=="number"){if(!(m.video.width&&m.video.height)){r.warn("have bitrate info for video but missing width/height");return}var b=m.video.bitrate;if(m.audio&&typeof m.audio.bitrate=="number"&&(b+=m.audio.bitrate),b!==m.totalBitrate)return m.totalBitrate=b,{video_source_bitrate:b,video_source_height:m.video.height,video_source_width:m.video.width,video_source_codec:TL(m.video.codec)}}},g=function(b,T,_){var I=b.mediaType;if(I==="audio"||I==="video"){var S;if(typeof t.getRepresentationsByType=="function")if(b.newRepresentation)S={bitrate:b.newRepresentation.bandwidth,width:b.newRepresentation.width,height:b.newRepresentation.height,qualityIndex:b.newRepresentation.absoluteIndex};else{var x=t.getRepresentationsByType(I);if(x&&typeof b.newQuality=="number"){var k=x.find(function(D){return D.absoluteIndex===b.newQuality||D.index===b.newQuality});k&&(S={bitrate:k.bandwidth,width:k.width,height:k.height,qualityIndex:b.newQuality})}}else{if(typeof b.newQuality!="number"){r.warn("missing evt.newQuality in qualityChangeRendered event",b);return}S=t.getBitrateInfoListFor(I).find(function(D){var w=D.qualityIndex;return w===b.newQuality})}if(!(S&&typeof S.bitrate=="number")){r.warn("missing bitrate info for ".concat(I));return}m[I]=Nm(Vo({},S),{codec:t.getCurrentTrackFor(I).codec});var R=p();R&&a("renditionchange",R)}};t.on("qualityChangeRendered",g);var v=function(b){var T=b.request,_=b.mediaType;T=T||{},a("requestcanceled",{request_event_type:T.type+"_"+T.action,request_url:T.url,request_type:_,request_hostname:Ki(T.url)})};t.on("fragmentLoadingAbandoned",v);var E=function(b){var T=b.error,_,I,S=(T==null||(_=T.data)===null||_===void 0?void 0:_.request)||{},x=(T==null||(I=T.data)===null||I===void 0?void 0:I.response)||{};(T==null?void 0:T.code)===27&&a("requestfailed",{request_error:S.type+"_"+S.action,request_url:S.url,request_hostname:Ki(S.url),request_type:S.mediaType,request_error_code:x.status,request_error_text:x.statusText});var k="".concat(S!=null&&S.url?"url: ".concat(S.url,`
|
|
13
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:T==null?void 0:T.code,player_error_message:T==null?void 0:T.message,player_error_context:k})};t.on("error",b),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",g),t.off("error",b),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},SL=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},ny=0,IL=function(){"use strict";function i(){_t(this,i),z(this,"_listeners",void 0)}return ki(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++ny,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++ny;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=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(d,u){d=d.slice(),d.forEach(function(c){c.call(s,{type:e},u)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),i}(),RL=IL,LL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_playbackHeartbeatInterval",void 0),z(this,"_playheadShouldBeProgressing",void 0),z(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(s,r){t._playbackHeartbeatInterval!==null&&(Me.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return ki(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Me.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Me.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i}(),xL=LL,kL=function i(e){"use strict";var t=this;_t(this,i),z(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,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 s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.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})},DL=kL,CL=function(){"use strict";function i(e){_t(this,i),z(this,"_watchTimeTrackerLastCheckedTime",void 0),z(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 ki(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),Ot(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i}(),wL=CL,ML=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),z(this,"_lastTime",void 0),z(this,"_isAdPlaying",void 0),z(this,"_callbackUpdatePlaybackTime",void 0),z(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=$t.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s);var r=function(){t.pm.data.player_is_paused||s()};e.on("seeked",r),e.on("rebufferend",r);var n=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",n),e.on("seeking",n),e.on("rebufferstart",n),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=$t.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return ki(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=$t.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=$t.now(),s=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=s),r>0&&r<=1e3&&Ot(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&s>0&&s<=1e3&&(this._isAdPlaying&&Ot(this.pm.data,"ad_playing_time_ms_cumulative",s),Ot(this.pm.data,"view_playing_time_ms_cumulative",s)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i}(),PL=ML,OL=function(){"use strict";function i(e){_t(this,i),z(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 ki(i,[{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 s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.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())}}}]),i}(),NL=OL,ay=5*60*1e3,UL=function i(e){"use strict";if(_t(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;Ot(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>ay&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(ay,"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||(Ot(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},FL=UL,BL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_lastCheckedTime",void 0),z(this,"_lastPlayheadTime",void 0),z(this,"_lastPlayheadTimeUpdatedTime",void 0),z(this,"_rebuffering",void 0),z(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:$t.now()})}))}return ki(i,[{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 s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=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 s=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}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i}(),$L=BL,HL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.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||$t.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return ki(i,[{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))}}]),i}(),GL=HL,KL=function i(e){"use strict";var t=this;_t(this,i),z(this,"_lastPlayerHeight",void 0),z(this,"_lastPlayerWidth",void 0),z(this,"_lastPlayheadPosition",void 0),z(this,"_lastSourceHeight",void 0),z(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];s.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),d=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,d),Ot(e.data,"view_total_content_playback_time",a),Ot(e.data,"view_total_upscaling",l*a),Ot(e.data,"view_total_downscaling",d*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})})},VL=KL,WL=2e3,qL=function i(e){"use strict";var t=this;_t(this,i),z(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=$t.now(),a=(e.data.viewer_time||n)-(s||n);Ot(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,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=WL){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,Ot(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,s=-1})},YL=qL,oy=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},jL=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],zL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_adHasPlayed",void 0),z(this,"_adRequests",void 0),z(this,"_adResponses",void 0),z(this,"_currentAdRequestNumber",void 0),z(this,"_currentAdResponseNumber",void 0),z(this,"_prerollPlayTime",void 0),z(this,"_wouldBeNewAdPlay",void 0),z(this,"isAdBreak",void 0),z(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}),jL.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),oy(t._adRequests,n),Ot(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||Ot(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),oy(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&Ot(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,Ot(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||Ot(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||Ot(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return ki(i,[{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 s=Ks(Ko(t.ad_tag_url),2),r=s[0],n=s[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=Ks(Ko(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)}}]),i}(),QL=zL,XL=function i(e){"use strict";var t=this;_t(this,i),z(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=$t.now(),e.on("before*",r)},r=function(n){var a=$t.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",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},ZL=XL,Ay=function(i){return i()}(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=i({path:"/"},s.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 d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),Sy="muxData",JL=function(i){return Object.entries(i).map(function(e){var t=Ks(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},ex=function(i){return i.split("&").reduce(function(e,t){var s=Ks(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},Iy=function(){var i;try{i=ex(Ay.get(Sy)||"")}catch{i={}}return i},Ry=function(i){try{Ay.set(Sy,JL(i),{expires:365})}catch{}},tx=function(){var i=Iy();return i.mux_viewer_id=i.mux_viewer_id||Go(),i.msn=i.msn||Math.random(),Ry(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},ix=function(){var i=Iy(),e=$t.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=Go(),i.sst=e),i.sex=e+25*60*1e3,Ry(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function sx(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t){var r=/localhost(?::\d+)?$/.test(t)?"http://":"https://";return r+t}i=i||"inferred";var n=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+n:"https://img.litix.io/a.gif"}var rx={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"},nx=Ly(rx),ax={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",lw:"low",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",si:"sid",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"},ly=Ly(ax);function Ly(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function Om(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=nx[a];o||(st.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),ly[l]?o+=ly[l]:Number.isInteger(Number(l))?o+=l:(st.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var ox=GR(QR()),lx=typeof document!="undefined"?document:ox.default,aa=lx,dx={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},ux=56*1024,cx=["hb","requestcompleted","requestfailed","requestcanceled"],hx="https://img.litix.io",Vs=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||hx,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},dx,e)};Vs.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Vs.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Vs.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),Me.clearTimeout(this._sendTimeout)};Vs.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],Om({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);xy(this._beaconUrl,t,!0,function(){})};Vs.prototype._sendBeaconQueue=function(){var i=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),s=$t.now();xy(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,st.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=$t.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};Vs.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};Vs.prototype._startBeaconSending=function(){var i=this;Me.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=Me.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};Vs.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round($t.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(st.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return cx.indexOf(l.e)===-1}),a()),o()||(st.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var fx=typeof aa.exitPictureInPicture=="function"?function(i){return i.length<=ux}:function(i){return!1},xy=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(Me.fetch){Me.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:fx(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(Me.XMLHttpRequest){var r=new Me.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},mx=Vs,px=["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"],gx=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],vx=["ad_id","ad_creative_id","ad_universal_id"],Ex=["viewstart","error","ended","viewend"],yx=10*60*1e3,bx=function(){"use strict";function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};_t(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;z(this,"mux",void 0),z(this,"envKey",void 0),z(this,"options",void 0),z(this,"eventQueue",void 0),z(this,"sampleRate",void 0),z(this,"disableCookies",void 0),z(this,"respectDoNotTrack",void 0),z(this,"previousBeaconData",void 0),z(this,"lastEventTime",void 0),z(this,"rateLimited",void 0),z(this,"pageLevelData",void 0),z(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new mx(sx(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 b;this.respectDoNotTrack=(b=this.options.respectDoNotTrack)!==null&&b!==void 0?b:!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:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.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,page_url:Me==null||(p=Me.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:tx()}return ki(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Mm())return st.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return st.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:ix(),r=Nm(Vo({},this.pageLevelData,t,s,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=Om(o);if(this.lastEventTime=this.mux.utils.now(),a)return st.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||st.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(st.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(Ex.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=Om(r),this.eventQueue.queueEvent(r.event,l),st.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=yx)r=Vo({},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=Ks(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||px.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||vx.includes(t)&&gx.includes(e)||e==="playbackmodechange"&&t.indexOf("player_playback_mode")===0)}}]),i}(),Tx=function i(e){"use strict";_t(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=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 b,E;if(p?(b=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 T=v/E*8e3;a++,s+=v,r+=E,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,T),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,b>0&&(t+=b,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,b),e.data.view_average_request_latency=t/a)}},u=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",d),e.on("requestfailed",u),e.on("requestcanceled",c)},_x=Tx,Ax=60*60*1e3,Sx=function i(e){"use strict";var t=this;_t(this,i),z(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=$t.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>Ax){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,z({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},Ix=Sx,Rx=function i(e){"use strict";_t(this,i);var t=function(o){var l=Lx(o),d=xx(o);if(l!=null&&!dy(l,n)&&a<=d){n=l,a=d;var u={video_cdn:l};e.emit("cdnchange",u)}},s=null,r=null,n=null,a=0;e.on("viewinit",function(){s=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var d=l==null?void 0:l.video_cdn;d&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(dy(d,r)?l.video_previous_cdn=s!=null?s:void 0:(l.video_previous_cdn=r!=null?r:void 0,s=r,r=d))}),e.on("requestcompleted",function(o,l){t(l)})};function dy(i,e){return(i==null?void 0:i.toLowerCase())===(e==null?void 0:e.toLowerCase())}function Lx(i){var e;return i!=null&&i.request_type&&(i.request_type==="media"||i.request_type==="video")&&!((e=i.request_response_headers)===null||e===void 0)&&e["x-cdn"]?i.request_response_headers["x-cdn"]:i!=null&&i.video_cdn?i.video_cdn:null}function xx(i){return i!=null&&i.request_start?i.request_start:i!=null&&i.viewer_time?i.viewer_time:Date.now()}var kx=Rx,Dx=function(i){try{return JSON.parse(i),!0}catch{return!1}},Cx=function i(e){"use strict";var t=this;_t(this,i),z(this,"_emittingAutomaticEvent",!1),z(this,"_hasInitialized",!1),z(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(s,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?Dx(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)})},wx=Cx,Mx=function(){"use strict";function i(e){_t(this,i),z(this,"pm",void 0),z(this,"_currentRangeStart",void 0),z(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 ki(i,[{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 s=Math.abs(t-this._lastPlayheadTime);if(s>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)}}]),i}(),Px=Mx,ds=Object.freeze({CELLULAR:"cellular",WIFI:"wifi",WIRED:"wired",OTHER:"other",NO_CONNECTION:"no_connection",UNKNOWN:"unknown"}),Ox=function(i){if(!i)return ds.UNKNOWN;switch(i){case"cellular":case"wimax":return ds.CELLULAR;case"wifi":return ds.WIFI;case"ethernet":return ds.WIRED;case"none":return ds.NO_CONNECTION;case"bluetooth":case"other":return ds.OTHER;case"unknown":return ds.UNKNOWN;default:var e=i;return ds.OTHER}},Nx=function(i){return typeof i=="object"&&"connection"in i&&typeof i.connection=="object"},Ux=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"pm",void 0),z(this,"lastType",void 0),z(this,"lastLowDataMode",void 0),this.pm=e,this.pm.one("viewinit",function(){var s,r=t.emit.bind(t);r(),Me.addEventListener("online",r),Me.addEventListener("offline",r),(s=i.connection)===null||s===void 0||s.addEventListener("change",r),t.pm.on("destroy",function(){var n;(n=i.connection)===null||n===void 0||n.removeEventListener("change",r),Me.removeEventListener("online",r),Me.removeEventListener("offline",r)})})}return ki(i,[{key:"type",get:function(){var e,t;return((e=Me.navigator)===null||e===void 0?void 0:e.onLine)===!1?ds.NO_CONNECTION:!((t=i.connection)===null||t===void 0)&&t.type?Ox(i.connection.type):ds.UNKNOWN}},{key:"lowDataMode",get:function(){var e;return(e=i.connection)===null||e===void 0?void 0:e.saveData}},{key:"emit",value:function(){var e=this.type,t=this.lowDataMode;e===this.lastType&&t===this.lastLowDataMode||(this.lastType=e,this.lastLowDataMode=t,this.pm.emit("networkchange",Vo({viewer_connection_type:e},t!==void 0&&{viewer_connection_low_data_mode:t})))}}],[{key:"connection",get:function(){return Nx(Me.navigator)?Me.navigator.connection:null}}]),i}(),Fx=Ux,Bx=["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","networkchange","cdnchange","playbackmodechange"],$x=new Set(["requestcompleted","requestfailed","requestcanceled"]),Hx=function(i){"use strict";oL(t,i);var e=hL(t);function t(s,r,n){_t(this,t);var a;a=e.call(this),z(ve(a),"pageLoadEndTime",void 0),z(ve(a),"pageLoadInitTime",void 0),z(ve(a),"_destroyed",void 0),z(ve(a),"_heartBeatTimeout",void 0),z(ve(a),"adTracker",void 0),z(ve(a),"dashjs",void 0),z(ve(a),"data",void 0),z(ve(a),"disablePlayheadRebufferTracking",void 0),z(ve(a),"disableRebufferTracking",void 0),z(ve(a),"disableAdPlaybackRangeFiltering",void 0),z(ve(a),"errorTracker",void 0),z(ve(a),"errorTranslator",void 0),z(ve(a),"emitTranslator",void 0),z(ve(a),"getAdData",void 0),z(ve(a),"getPlayheadTime",void 0),z(ve(a),"getStateData",void 0),z(ve(a),"stateDataTranslator",void 0),z(ve(a),"hlsjs",void 0),z(ve(a),"id",void 0),z(ve(a),"longResumeTracker",void 0),z(ve(a),"minimumRebufferDuration",void 0),z(ve(a),"mux",void 0),z(ve(a),"playbackEventDispatcher",void 0),z(ve(a),"playbackHeartbeat",void 0),z(ve(a),"playbackHeartbeatTime",void 0),z(ve(a),"playheadTime",void 0),z(ve(a),"seekingTracker",void 0),z(ve(a),"sustainedRebufferThreshold",void 0),z(ve(a),"watchTimeTracker",void 0),z(ve(a),"currentFragmentPDT",void 0),z(ve(a),"currentFragmentStart",void 0),a.pageLoadInitTime=ru.navigationStart(),a.pageLoadEndTime=ru.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(m){return m},emitTranslator:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];return p},stateDataTranslator:function(m){return m}};if(a.mux=s,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||{},!1)var l,d;n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),st.level=n.debug?hn.DEBUG:hn.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 bx(s,n.data.env_key,n),a.data={player_instance_id:Go(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var u=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(ve(a));if(a.on("viewinit",function(m,p){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,p),this._initializeViewData(),this.one("play",u),this.one("adbreakstart",u)}),a.on("videochange",function(m,p){this._resetView(p)}),a.on("programchange",function(m,p){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(p,{view_program_changed:!0})),u(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(m,p){this.currentFragmentPDT=p.currentFragmentPDT,this.currentFragmentStart=p.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var c=function(){var m=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",m&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",c,!1);var h=function(m){m.persisted||a.destroy()};window.addEventListener("pagehide",h,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",c),window.removeEventListener("pagehide",h)})}a.on("playerready",function(m,p){Object.assign(this.data,p)}),Bx.forEach(function(m){a.on(m,function(p,g){m.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,g),this._sanitizeData()}),a.on("after"+m,function(){(m!=="error"||this.errorTracker.viewErrored)&&this.send(m)})}),a.on("viewend",function(m,p){Object.assign(a.data,p)});var f=function(m){var p=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=p-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",f),a.longResumeTracker=new Ix(ve(a)),a.errorTracker=new DL(ve(a)),new ZL(ve(a)),a.seekingTracker=new YL(ve(a)),a.playheadTime=new NL(ve(a)),a.playbackHeartbeat=new xL(ve(a)),new VL(ve(a)),a.watchTimeTracker=new wL(ve(a)),new PL(ve(a)),new Px(ve(a)),a.adTracker=new QL(ve(a)),new $L(ve(a)),new FL(ve(a)),new GL(ve(a)),new _x(ve(a)),new kx(ve(a)),new wx(ve(a)),new Fx(ve(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return ki(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=iu(la(t.prototype),"emit",this)).call.apply(n,[this].concat(Gi(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(s){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(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=Ks(Ko(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(d){return d[0]!==d[1]}).map(function(d){return"".concat(d[0],":").concat(d[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,$x.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s,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(!((s=this.data)===null||s===void 0)&&s.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=dL(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=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(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.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 s=this,r=this.data.view_id=Go(),n=function(){r===s.data.view_id&&Ot(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.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=s.hlsjs,EL(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(yL(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.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=s.dashjs,AL(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(SL(this.dashjs),this.dashjs=void 0)}}]),t}(RL),Gx=Hx;function Dm(){return aa&&!!(aa.fullscreenElement||aa.webkitFullscreenElement||aa.mozFullScreenElement||aa.msFullscreenElement)}var Kx=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],Vx={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function Wx(i,e,t){var s=Ks(su(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={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 d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,b=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:Dm(),video_poster_url:r.poster,video_source_url:v||b||r.currentSrc,video_source_duration:d(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 T=r.getStartDate();if(T&&typeof T.getTime=="function"&&T.getTime()){var _=T.getTime();if(E.player_program_time=_+g,r.seekable.length>0){var I=_+r.seekable.end(r.seekable.length-1);E.player_live_edge_program_time=I}}}return E}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.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,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=Ks(su(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.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(b){r.removeEventListener(b,p.mux.listeners[b],!1),p.addEventListener(b,p.mux.listeners[b],!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){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},Kx.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=Vx[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){i.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=Dm()?"fullscreen":"standard";i.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=Dm(),m=document.fullscreenElement;if(f&&(m===r||m!=null&&m.contains(r)))i.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var p=document.pictureInPictureElement===r,g=p?"pip":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:g,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function qx(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){st.info("safeCall error",n)}return r}var oa;Me&&Me.WeakMap&&(oa=new WeakMap);function Yx(i,e){if(!i||!e||!Me||typeof Me.getComputedStyle!="function")return"";var t;return oa&&oa.has(i)&&(t=oa.get(i)),t||(t=Me.getComputedStyle(i,null),oa&&oa.set(i,t)),t.getPropertyValue(e)}function jx(i){return Math.floor(i*1e3)}var cn={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"},au=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};au.prototype.process=function(i){var e;for(this.buffer+=i,e=this.buffer.indexOf(`
|
|
14
|
+
`):"");a("error",{player_error_code:T==null?void 0:T.code,player_error_message:T==null?void 0:T.message,player_error_context:k})};t.on("error",E),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",g),t.off("error",E),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},SL=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},ny=0,IL=function(){"use strict";function i(){_t(this,i),z(this,"_listeners",void 0)}return ki(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++ny,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++ny;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=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(d,u){d=d.slice(),d.forEach(function(c){c.call(s,{type:e},u)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),i}(),RL=IL,LL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_playbackHeartbeatInterval",void 0),z(this,"_playheadShouldBeProgressing",void 0),z(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(s,r){t._playbackHeartbeatInterval!==null&&(Me.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return ki(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Me.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Me.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i}(),xL=LL,kL=function i(e){"use strict";var t=this;_t(this,i),z(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,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 s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.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})},DL=kL,CL=function(){"use strict";function i(e){_t(this,i),z(this,"_watchTimeTrackerLastCheckedTime",void 0),z(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 ki(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),Ot(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i}(),wL=CL,ML=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),z(this,"_lastTime",void 0),z(this,"_isAdPlaying",void 0),z(this,"_callbackUpdatePlaybackTime",void 0),z(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=$t.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s);var r=function(){t.pm.data.player_is_paused||s()};e.on("seeked",r),e.on("rebufferend",r);var n=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",n),e.on("seeking",n),e.on("rebufferstart",n),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=$t.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return ki(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=$t.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=$t.now(),s=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=s),r>0&&r<=1e3&&Ot(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&s>0&&s<=1e3&&(this._isAdPlaying&&Ot(this.pm.data,"ad_playing_time_ms_cumulative",s),Ot(this.pm.data,"view_playing_time_ms_cumulative",s)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i}(),PL=ML,OL=function(){"use strict";function i(e){_t(this,i),z(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 ki(i,[{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 s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.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())}}}]),i}(),NL=OL,ay=5*60*1e3,UL=function i(e){"use strict";if(_t(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;Ot(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>ay&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(ay,"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||(Ot(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},FL=UL,BL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_lastCheckedTime",void 0),z(this,"_lastPlayheadTime",void 0),z(this,"_lastPlayheadTimeUpdatedTime",void 0),z(this,"_rebuffering",void 0),z(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:$t.now()})}))}return ki(i,[{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 s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=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 s=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}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i}(),$L=BL,HL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.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||$t.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return ki(i,[{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))}}]),i}(),GL=HL,KL=function i(e){"use strict";var t=this;_t(this,i),z(this,"_lastPlayerHeight",void 0),z(this,"_lastPlayerWidth",void 0),z(this,"_lastPlayheadPosition",void 0),z(this,"_lastSourceHeight",void 0),z(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];s.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),d=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,d),Ot(e.data,"view_total_content_playback_time",a),Ot(e.data,"view_total_upscaling",l*a),Ot(e.data,"view_total_downscaling",d*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})})},VL=KL,WL=2e3,qL=function i(e){"use strict";var t=this;_t(this,i),z(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=$t.now(),a=(e.data.viewer_time||n)-(s||n);Ot(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,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=WL){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,Ot(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,s=-1})},YL=qL,oy=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},jL=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],zL=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"_adHasPlayed",void 0),z(this,"_adRequests",void 0),z(this,"_adResponses",void 0),z(this,"_currentAdRequestNumber",void 0),z(this,"_currentAdResponseNumber",void 0),z(this,"_prerollPlayTime",void 0),z(this,"_wouldBeNewAdPlay",void 0),z(this,"isAdBreak",void 0),z(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}),jL.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),oy(t._adRequests,n),Ot(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||Ot(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),oy(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&Ot(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,Ot(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||Ot(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||Ot(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return ki(i,[{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 s=Ks(Ko(t.ad_tag_url),2),r=s[0],n=s[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=Ks(Ko(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)}}]),i}(),QL=zL,XL=function i(e){"use strict";var t=this;_t(this,i),z(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=$t.now(),e.on("before*",r)},r=function(n){var a=$t.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",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},ZL=XL,Ay=function(i){return i()}(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=i({path:"/"},s.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 d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),Sy="muxData",JL=function(i){return Object.entries(i).map(function(e){var t=Ks(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},ex=function(i){return i.split("&").reduce(function(e,t){var s=Ks(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},Iy=function(){var i;try{i=ex(Ay.get(Sy)||"")}catch{i={}}return i},Ry=function(i){try{Ay.set(Sy,JL(i),{expires:365})}catch{}},tx=function(){var i=Iy();return i.mux_viewer_id=i.mux_viewer_id||Go(),i.msn=i.msn||Math.random(),Ry(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},ix=function(){var i=Iy(),e=$t.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=Go(),i.sst=e),i.sex=e+25*60*1e3,Ry(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function sx(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t){var r=/localhost(?::\d+)?$/.test(t)?"http://":"https://";return r+t}i=i||"inferred";var n=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+n:"https://img.litix.io/a.gif"}var rx={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"},nx=Ly(rx),ax={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",lw:"low",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",si:"sid",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"},ly=Ly(ax);function Ly(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function Om(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=nx[a];o||(st.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),ly[l]?o+=ly[l]:Number.isInteger(Number(l))?o+=l:(st.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var ox=GR(QR()),lx=typeof document!="undefined"?document:ox.default,aa=lx,dx={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},ux=56*1024,cx=["hb","requestcompleted","requestfailed","requestcanceled"],hx="https://img.litix.io",Vs=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||hx,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},dx,e)};Vs.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Vs.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Vs.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),Me.clearTimeout(this._sendTimeout)};Vs.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],Om({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);xy(this._beaconUrl,t,!0,function(){})};Vs.prototype._sendBeaconQueue=function(){var i=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),s=$t.now();xy(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,st.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=$t.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};Vs.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};Vs.prototype._startBeaconSending=function(){var i=this;Me.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=Me.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};Vs.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round($t.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(st.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return cx.indexOf(l.e)===-1}),a()),o()||(st.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var fx=typeof aa.exitPictureInPicture=="function"?function(i){return i.length<=ux}:function(i){return!1},xy=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(Me.fetch){Me.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:fx(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(Me.XMLHttpRequest){var r=new Me.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},mx=Vs,px=["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"],gx=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],vx=["ad_id","ad_creative_id","ad_universal_id"],Ex=["viewstart","error","ended","viewend"],yx=10*60*1e3,bx=function(){"use strict";function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};_t(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;z(this,"mux",void 0),z(this,"envKey",void 0),z(this,"options",void 0),z(this,"eventQueue",void 0),z(this,"sampleRate",void 0),z(this,"disableCookies",void 0),z(this,"respectDoNotTrack",void 0),z(this,"previousBeaconData",void 0),z(this,"lastEventTime",void 0),z(this,"rateLimited",void 0),z(this,"pageLevelData",void 0),z(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new mx(sx(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 E;this.respectDoNotTrack=(E=this.options.respectDoNotTrack)!==null&&E!==void 0?E:!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:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.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,page_url:Me==null||(p=Me.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:tx()}return ki(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Mm())return st.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return st.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:ix(),r=Nm(Vo({},this.pageLevelData,t,s,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=Om(o);if(this.lastEventTime=this.mux.utils.now(),a)return st.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||st.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(st.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(Ex.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=Om(r),this.eventQueue.queueEvent(r.event,l),st.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=yx)r=Vo({},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=Ks(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||px.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||vx.includes(t)&&gx.includes(e)||e==="playbackmodechange"&&t.indexOf("player_playback_mode")===0)}}]),i}(),Tx=function i(e){"use strict";_t(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=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 E,b;if(p?(E=p-(m!=null?m:0),b=(g!=null?g:0)-p):b=(g!=null?g:0)-(m!=null?m:0),b>0&&v&&v>0){var T=v/b*8e3;a++,s+=v,r+=b,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,T),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,E>0&&(t+=E,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,E),e.data.view_average_request_latency=t/a)}},u=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",d),e.on("requestfailed",u),e.on("requestcanceled",c)},_x=Tx,Ax=60*60*1e3,Sx=function i(e){"use strict";var t=this;_t(this,i),z(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=$t.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>Ax){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,z({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},Ix=Sx,Rx=function i(e){"use strict";_t(this,i);var t=function(o){var l=Lx(o),d=xx(o);if(l!=null&&!dy(l,n)&&a<=d){n=l,a=d;var u={video_cdn:l};e.emit("cdnchange",u)}},s=null,r=null,n=null,a=0;e.on("viewinit",function(){s=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var d=l==null?void 0:l.video_cdn;d&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(dy(d,r)?l.video_previous_cdn=s!=null?s:void 0:(l.video_previous_cdn=r!=null?r:void 0,s=r,r=d))}),e.on("requestcompleted",function(o,l){t(l)})};function dy(i,e){return(i==null?void 0:i.toLowerCase())===(e==null?void 0:e.toLowerCase())}function Lx(i){var e;return i!=null&&i.request_type&&(i.request_type==="media"||i.request_type==="video")&&!((e=i.request_response_headers)===null||e===void 0)&&e["x-cdn"]?i.request_response_headers["x-cdn"]:i!=null&&i.video_cdn?i.video_cdn:null}function xx(i){return i!=null&&i.request_start?i.request_start:i!=null&&i.viewer_time?i.viewer_time:Date.now()}var kx=Rx,Dx=function(i){try{return JSON.parse(i),!0}catch{return!1}},Cx=function i(e){"use strict";var t=this;_t(this,i),z(this,"_emittingAutomaticEvent",!1),z(this,"_hasInitialized",!1),z(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(s,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?Dx(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)})},wx=Cx,Mx=function(){"use strict";function i(e){_t(this,i),z(this,"pm",void 0),z(this,"_currentRangeStart",void 0),z(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 ki(i,[{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 s=Math.abs(t-this._lastPlayheadTime);if(s>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)}}]),i}(),Px=Mx,ds=Object.freeze({CELLULAR:"cellular",WIFI:"wifi",WIRED:"wired",OTHER:"other",NO_CONNECTION:"no_connection",UNKNOWN:"unknown"}),Ox=function(i){if(!i)return ds.UNKNOWN;switch(i){case"cellular":case"wimax":return ds.CELLULAR;case"wifi":return ds.WIFI;case"ethernet":return ds.WIRED;case"none":return ds.NO_CONNECTION;case"bluetooth":case"other":return ds.OTHER;case"unknown":return ds.UNKNOWN;default:var e=i;return ds.OTHER}},Nx=function(i){return typeof i=="object"&&"connection"in i&&typeof i.connection=="object"},Ux=function(){"use strict";function i(e){var t=this;_t(this,i),z(this,"pm",void 0),z(this,"lastType",void 0),z(this,"lastLowDataMode",void 0),this.pm=e,this.pm.one("viewinit",function(){var s,r=t.emit.bind(t);r(),Me.addEventListener("online",r),Me.addEventListener("offline",r),(s=i.connection)===null||s===void 0||s.addEventListener("change",r),t.pm.on("destroy",function(){var n;(n=i.connection)===null||n===void 0||n.removeEventListener("change",r),Me.removeEventListener("online",r),Me.removeEventListener("offline",r)})})}return ki(i,[{key:"type",get:function(){var e,t;return((e=Me.navigator)===null||e===void 0?void 0:e.onLine)===!1?ds.NO_CONNECTION:!((t=i.connection)===null||t===void 0)&&t.type?Ox(i.connection.type):ds.UNKNOWN}},{key:"lowDataMode",get:function(){var e;return(e=i.connection)===null||e===void 0?void 0:e.saveData}},{key:"emit",value:function(){var e=this.type,t=this.lowDataMode;e===this.lastType&&t===this.lastLowDataMode||(this.lastType=e,this.lastLowDataMode=t,this.pm.emit("networkchange",Vo({viewer_connection_type:e},t!==void 0&&{viewer_connection_low_data_mode:t})))}}],[{key:"connection",get:function(){return Nx(Me.navigator)?Me.navigator.connection:null}}]),i}(),Fx=Ux,Bx=["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","networkchange","cdnchange","playbackmodechange"],$x=new Set(["requestcompleted","requestfailed","requestcanceled"]),Hx=function(i){"use strict";oL(t,i);var e=hL(t);function t(s,r,n){_t(this,t);var a;a=e.call(this),z(ve(a),"pageLoadEndTime",void 0),z(ve(a),"pageLoadInitTime",void 0),z(ve(a),"_destroyed",void 0),z(ve(a),"_heartBeatTimeout",void 0),z(ve(a),"adTracker",void 0),z(ve(a),"dashjs",void 0),z(ve(a),"data",void 0),z(ve(a),"disablePlayheadRebufferTracking",void 0),z(ve(a),"disableRebufferTracking",void 0),z(ve(a),"disableAdPlaybackRangeFiltering",void 0),z(ve(a),"errorTracker",void 0),z(ve(a),"errorTranslator",void 0),z(ve(a),"emitTranslator",void 0),z(ve(a),"getAdData",void 0),z(ve(a),"getPlayheadTime",void 0),z(ve(a),"getStateData",void 0),z(ve(a),"stateDataTranslator",void 0),z(ve(a),"hlsjs",void 0),z(ve(a),"id",void 0),z(ve(a),"longResumeTracker",void 0),z(ve(a),"minimumRebufferDuration",void 0),z(ve(a),"mux",void 0),z(ve(a),"playbackEventDispatcher",void 0),z(ve(a),"playbackHeartbeat",void 0),z(ve(a),"playbackHeartbeatTime",void 0),z(ve(a),"playheadTime",void 0),z(ve(a),"seekingTracker",void 0),z(ve(a),"sustainedRebufferThreshold",void 0),z(ve(a),"watchTimeTracker",void 0),z(ve(a),"currentFragmentPDT",void 0),z(ve(a),"currentFragmentStart",void 0),a.pageLoadInitTime=ru.navigationStart(),a.pageLoadEndTime=ru.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(m){return m},emitTranslator:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];return p},stateDataTranslator:function(m){return m}};if(a.mux=s,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||{},!1)var l,d;n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),st.level=n.debug?hn.DEBUG:hn.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 bx(s,n.data.env_key,n),a.data={player_instance_id:Go(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var u=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(ve(a));if(a.on("viewinit",function(m,p){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,p),this._initializeViewData(),this.one("play",u),this.one("adbreakstart",u)}),a.on("videochange",function(m,p){this._resetView(p)}),a.on("programchange",function(m,p){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(p,{view_program_changed:!0})),u(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(m,p){this.currentFragmentPDT=p.currentFragmentPDT,this.currentFragmentStart=p.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var c=function(){var m=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",m&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",c,!1);var h=function(m){m.persisted||a.destroy()};window.addEventListener("pagehide",h,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",c),window.removeEventListener("pagehide",h)})}a.on("playerready",function(m,p){Object.assign(this.data,p)}),Bx.forEach(function(m){a.on(m,function(p,g){m.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,g),this._sanitizeData()}),a.on("after"+m,function(){(m!=="error"||this.errorTracker.viewErrored)&&this.send(m)})}),a.on("viewend",function(m,p){Object.assign(a.data,p)});var f=function(m){var p=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=p-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",f),a.longResumeTracker=new Ix(ve(a)),a.errorTracker=new DL(ve(a)),new ZL(ve(a)),a.seekingTracker=new YL(ve(a)),a.playheadTime=new NL(ve(a)),a.playbackHeartbeat=new xL(ve(a)),new VL(ve(a)),a.watchTimeTracker=new wL(ve(a)),new PL(ve(a)),new Px(ve(a)),a.adTracker=new QL(ve(a)),new $L(ve(a)),new FL(ve(a)),new GL(ve(a)),new _x(ve(a)),new kx(ve(a)),new wx(ve(a)),new Fx(ve(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return ki(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=iu(la(t.prototype),"emit",this)).call.apply(n,[this].concat(Gi(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(s){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(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=Ks(Ko(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(d){return d[0]!==d[1]}).map(function(d){return"".concat(d[0],":").concat(d[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,$x.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s,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(!((s=this.data)===null||s===void 0)&&s.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=dL(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=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(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.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 s=this,r=this.data.view_id=Go(),n=function(){r===s.data.view_id&&Ot(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.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=s.hlsjs,EL(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(yL(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.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=s.dashjs,AL(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(SL(this.dashjs),this.dashjs=void 0)}}]),t}(RL),Gx=Hx;function Dm(){return aa&&!!(aa.fullscreenElement||aa.webkitFullscreenElement||aa.mozFullScreenElement||aa.msFullscreenElement)}var Kx=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],Vx={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function Wx(i,e,t){var s=Ks(su(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={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 d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,E=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),b={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:Dm(),video_poster_url:r.poster,video_source_url:v||E||r.currentSrc,video_source_duration:d(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 T=r.getStartDate();if(T&&typeof T.getTime=="function"&&T.getTime()){var _=T.getTime();if(b.player_program_time=_+g,r.seekable.length>0){var I=_+r.seekable.end(r.seekable.length-1);b.player_live_edge_program_time=I}}}return b}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.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,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=Ks(su(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.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(E){r.removeEventListener(E,p.mux.listeners[E],!1),p.addEventListener(E,p.mux.listeners[E],!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){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},Kx.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=Vx[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){i.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=Dm()?"fullscreen":"standard";i.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=Dm(),m=document.fullscreenElement;if(f&&(m===r||m!=null&&m.contains(r)))i.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var p=document.pictureInPictureElement===r,g=p?"pip":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:g,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function qx(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){st.info("safeCall error",n)}return r}var oa;Me&&Me.WeakMap&&(oa=new WeakMap);function Yx(i,e){if(!i||!e||!Me||typeof Me.getComputedStyle!="function")return"";var t;return oa&&oa.has(i)&&(t=oa.get(i)),t||(t=Me.getComputedStyle(i,null),oa&&oa.set(i,t)),t.getPropertyValue(e)}function jx(i){return Math.floor(i*1e3)}var cn={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"},au=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};au.prototype.process=function(i){var e;for(this.buffer+=i,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)};au.prototype.processLine=function(i){var e=i.indexOf(":"),t=Zx(i,e),s=t[0],r=t.length===2?Fm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case cn.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case cn.PART_INF:{Cm(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case cn.SERVER_CONTROL:{Cm(this.manifest,t),this.setHoldBack();break}case cn.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case cn.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 cn.VERSION:{Cm(this.manifest,t);break}case cn.SESSION_DATA:{var o=Jx(t[1]),l=_y(o);Object.assign(this.manifest.sessionData,l)}}};au.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var Cm=function(i,e){var t=ky(e[0].replace("#EXT-X-","")),s;Xx(e[1])?(s={},s=Object.assign(Qx(e[1]),s)):s=Fm(e[1]),i[t]=s},ky=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},Fm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},zx=function(i){var e={},t=i.split("=");if(t.length>1){var s=ky(t[0]);e[s]=Fm(t[1])}return e},Qx=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=zx(r);t=Object.assign(n,t)}return t},Xx=function(i){return i.indexOf("=")>-1},Zx=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},Jx=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},ek=au,tk={safeCall:qx,safeIncrement:Ot,getComputedStyle:Yx,secondsToMs:jx,assign:Object.assign,headersStringToObject:Um,cdnHeadersToRequestId:nu,extractHostnameAndDomain:Ko,extractHostname:Ki,manifestParser:ek,generateShortID:by,generateUUID:Go,now:$t.now,findMediaElement:su},ik=tk,sk={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",NETWORK_CHANGE:"networkchange",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"},rk=sk,nk="mux-embed",ak="5.18.2",ok="2.1",kt={},vr=function(i){var e=arguments;typeof i=="string"?vr.hasOwnProperty(i)?Me.setTimeout(function(){e=Array.prototype.splice.call(e,1),vr[i].apply(null,e)},0):st.warn("`"+i+"` is an unknown task"):typeof i=="function"?Me.setTimeout(function(){i(vr)},0):st.warn("`"+i+"` is invalid.")},lk={loaded:$t.now(),NAME:nk,VERSION:ak,API_VERSION:ok,PLAYER_TRACKED:!1,monitor:function(i,e){return Wx(vr,i,e)},destroyMonitor:function(i){var e=Ks(su(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():st.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=Hi(i);kt[t]?kt[t].addHLSJS(e):st.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=Hi(i);kt[t]?kt[t].addDashJS(e):st.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=Hi(i);kt[e]?kt[e].removeHLSJS():st.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=Hi(i);kt[e]?kt[e].removeDashJS():st.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){Mm()&&e&&e.respectDoNotTrack&&st.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=Hi(i);kt[t]=new Gx(vr,t,e)},emit:function(i,e,t){var s=Hi(i);kt[s]?(kt[s].emit(e,t),e==="destroy"&&delete kt[s]):st.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=Hi(i);kt[t]?kt[t].emit("hb",e):st.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=Hi(i);kt[t]?kt[t].emitTranslator=e:st.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=Hi(i);kt[t]?kt[t].stateDataTranslator=e:st.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=Hi(i);kt[t]?kt[t].getPlayheadTime=e:st.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Mm,log:st,utils:ik,events:rk,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(vr,lk);typeof Me!="undefined"&&typeof Me.addEventListener=="function"&&Me.addEventListener("pagehide",function(i){i.persisted||(vr.WINDOW_UNLOADING=!0)},!1);var ou=vr;var Q=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},dk=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=uk},uk=Number.MAX_SAFE_INTEGER||9007199254740991,re=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),P=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",i.UNKNOWN="unknown",i}({}),y=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({});function ck(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Bm={exports:{}},Dy;function hk(){return Dy||(Dy=1,function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.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(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;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=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[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}};i.exports=o})()}(Bm)),Bm.exports}var Ng=hk(),il=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}}},Re=function(i){return i.MANIFEST="manifest",i.LEVEL="level",i.AUDIO_TRACK="audioTrack",i.SUBTITLE_TRACK="subtitleTrack",i.MEDIA_FRAGMENT="media-fragment",i.KEY="key",i.STEERING_MANIFEST="steering-manifest",i.SERVER_CERTIFICATE="server-certificate",i.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",i}({}),te=function(i){return i.MAIN="main",i.AUDIO="audio",i.SUBTITLE="subtitle",i}({}),Je={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ku=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,fk(this,"stats")}setByteRange(e,t){let s=e.split("@",2),r;s.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[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={[Je.AUDIO]:null,[Je.VIDEO]:null,[Je.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 il),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Ng.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Je.AUDIO]=null,e[Je.VIDEO]=null,e[Je.AUDIOVIDEO]=null,this.url=null}};function Et(i){return i.sn!=="initSegment"}function zo(i,e){return i.sn===(e==null?void 0:e.sn)&&i.level===e.level}function hp(i,e){return i.sn===(e==null?void 0:e.sn)&&i.level===e.level&&i.cc===e.cc}var fa=class extends ku{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(Q(e)&&Q(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 s=Object.keys(t);if(s.length===1){let r=this._decryptdata=t[s[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=Q(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 s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[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(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Et(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 s;let r=t[e];r&&!((s=this._decryptdata)!=null&&s.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,s,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},fp=class extends ku{constructor(e,t,s,r,n){super(s),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===te.SUBTITLE&&this.stats.loading.end>0)}};function tT(i,e){let t=Object.getPrototypeOf(i);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||tT(t,e)}}function fk(i,e){let t=tT(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}function mk(i,e,t){return(e=vk(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Qe(){return Qe=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},Qe.apply(null,arguments)}function Cy(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function ae(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Cy(Object(t),!0).forEach(function(s){mk(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Cy(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function dc(i,e){if(i==null)return{};var t,s,r=pk(i,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(s=0;s<n.length;s++)t=n[s],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(i,t)&&(r[t]=i[t])}return r}function pk(i,e){if(i==null)return{};var t={};for(var s in i)if({}.hasOwnProperty.call(i,s)){if(e.indexOf(s)!==-1)continue;t[s]=i[s]}return t}function gk(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function vk(i){var e=gk(i,"string");return typeof e=="symbol"?e:e+""}function Du(i){switch(i.details){case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_TIMEOUT:case P.LEVEL_LOAD_TIMEOUT:case P.MANIFEST_LOAD_TIMEOUT:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:case P.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function iT(i){return i.details.startsWith("key")}function sT(i){return iT(i)&&!!i.frag&&!i.frag.decryptdata}function wy(i,e){let t=Du(e);return i.default[`${t?"timeout":"error"}Retry`]}function Ug(i,e){let t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function My(i){return ae(ae({},i),{errorRetry:null,timeoutRetry:null})}function sl(i,e,t,s){if(!i)return!1;let r=s==null?void 0:s.code,n=e<i.maxNumRetry&&(Ek(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function Ek(i){return rl(i)||!!i&&(i<400||i>499)}function rl(i){return i===0&&navigator.onLine===!1}function rT(i,e){return e>0&&i.loadError>0&&i.loadErrorTime!==0&&self.performance.now()-i.loadErrorTime>e}var yr=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},mp=class{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new yr(e),this.fast_=new yr(t),this.defaultTTFB_=r,this.ttfb_=new yr(e)}update(e,t){let{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new yr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new yr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new yr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;let s=Math.min(this.minDelayMs_,t/1e5),r=8*t,n=Math.max(e,s)/1e3,a=r/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},si=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 s=`[${e}]:`;this.trace=br,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},br=function(){},yk={trace:br,debug:br,log:br,warn:br,info:br,error:br};function pp(){return Qe({},yk)}function bk(i,e){let t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):br}function Py(i,e,t){return e[i]?e[i].bind(e):bk(i,t)}var gp=pp();function Tk(i,e,t){let s=pp();if(typeof console=="object"&&i===!0||typeof i=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=Py(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return pp()}r.forEach(n=>{gp[n]=Py(n,i)})}else Qe(gp,s);return s}var $e=gp;function Ir(i=!0){return typeof self=="undefined"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _k(i){return typeof self!="undefined"&&i===self.ManagedMediaSource}function nT(i,e){let t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function Ak(i){return btoa(String.fromCharCode(...i))}function uc(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer!="undefined"&&i instanceof SharedArrayBuffer}var Sk="utf-16",$m="utf-16be",Oy="utf-16le",Au="utf-8";function Ik(i,e={}){let t;uc(i)?t=new DataView(i):t=new DataView(i.buffer,i.byteOffset,i.byteLength);let s=0,{encoding:r}=e;if(!r){let d=t.getUint8(0),u=t.getUint8(1);d==239&&u==187&&t.getUint8(2)==191?(r=Au,s=3):d==254&&u==255?(r=$m,s=2):d==255&&u==254?(r=Oy,s=2):r=Au}if(typeof TextDecoder!="undefined")return new TextDecoder(r).decode(t);let{byteLength:n}=t,a=r!==$m,o="",l;for(;s<n;){switch(r){case Au:if(l=t.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<n){let d=t.getUint8(s+1);d>=128&&d<=191?(l=(l&31)<<6|d&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=n-1){let d=t.getUint8(s+1),u=t.getUint8(s+2);d>=128&&d<=191&&u>=128&&u<=191?(l=(l&15)<<12|(d&63)<<6|u&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=n-1){let d=t.getUint8(s+1),u=t.getUint8(s+2),c=t.getUint8(s+3);d>=128&&d<=191&&u>=128&&u<=191&&c>=128&&c<=191?(l=(l&7)<<18|(d&63)<<12|(u&63)<<6|c&63,s+=4):s++}else s++;else s++;break;case $m:case Sk:case Oy:l=t.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function Rk(i){let e=typeof i=="string"?new URL(i):i;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function aT(i,e){if(i<0)return-aT(-i,e);let t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){let s=Math.floor(i*t);return(s%2===0?s:s+1)/t}else return Math.round(i*t)/t}function Lk(i,e){let t;try{t=new URL(i)}catch{return i}let s=new URL(e);if(t.origin!==s.origin)return i;let r=t.pathname.split("/").slice(1),n=s.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 oT(){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,s=>{let r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?r:r&3|8).toString(16)})}}}function Fg(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function cc(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function xk(i,e){return Fg(i,e)&&cc(i,e+6)+10<=i.length-e}function lT(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function nl(i,e){let t=e,s=0;for(;Fg(i,e);){s+=10;let r=cc(i,e+6);s+=r,lT(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function kk(i){return uc(i)?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function Hm(i,e=0,t=1/0){return Dk(i,e,t,Uint8Array)}function Dk(i,e,t,s){let r=Ck(i),n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);let a=wk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new s(r,d,Math.floor(Math.min(d+Math.max(t,0),o))-d)}function Ck(i){return uc(i)?i:i.buffer}function wk(i){return i&&uc(i.buffer)&&i.byteLength!==void 0&&i.byteOffset!==void 0}function Si(i,e=!1){let t=e?i.indexOf(0):i.length,s=Ik(new DataView(i.buffer,i.byteOffset,t),{encoding:Au});return e?s:s.replace(/\0/g,"")}function Mk(i){let e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=i.data.subarray(1).indexOf(0);if(s===-1)return;let r=Si(Hm(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=Si(Hm(i.data,3+s,a)),l;return r==="-->"?l=Si(Hm(i.data,4+s+a)):l=kk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function Pk(i){if(i.size<2)return;let e=Si(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function Ok(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1,{data:s}=i,r=Si(s.subarray(t),!0);t+=r.length+1;let n=Si(s.subarray(t));return{key:i.type,info:r,data:n}}let e=Si(i.data.subarray(1));return{key:i.type,info:"",data:e}}function Nk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1,s=Si(i.data.subarray(t),!0);t+=s.length+1;let r=Si(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=Si(i.data);return{key:i.type,info:"",data:e}}function Uk(i){return i.type==="PRIV"?Pk(i):i.type[0]==="W"?Nk(i):i.type==="APIC"?Mk(i):Ok(i)}function Fk(i){let e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=cc(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}var lu=10,Bk=10;function dT(i){let e=0,t=[];for(;Fg(i,e);){let s=cc(i,e+6);i[e+5]>>6&1&&(e+=lu),e+=lu;let r=e+s;for(;e+Bk<r;){let n=Fk(i.subarray(e)),a=Uk(n);a&&t.push(a),e+=n.size+lu}lT(i,e)&&(e+=lu)}return t}function uT(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function $k(i){if(i.data.byteLength===8){let e=new Uint8Array(i.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function Bg(i){let e=dT(i);for(let t of e)if(uT(t))return $k(t)}function Ct(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function cT(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function $g(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function ji(i){return String.fromCharCode.apply(null,i)}var hs=Math.pow(2,32)-1,me={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},hT={video:1,audio:2,id3:3,text:4};function fT(i,e){let t=i[e]<<8|i[e+1];return t<0?65536+t:t}function ee(i,e){let t=i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3];return t<0?4294967296+t:t}function Ny(i,e){let t=ee(i,e);return t*=Math.pow(2,32),t+=ee(i,e+4),t}function du(i,e){let t="";for(let s=e;s<i.length;s++)if(t+=String.fromCharCode(i[s]),i[s]===0)return t;return null}function vp(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function At(i,e,t){i[e]=t>>24,i[e+1]=t>>16&255,i[e+2]=t>>8&255,i[e+3]=t&255}function Uy(i,e,t){let s=e.byteOffset-i.byteOffset-8,r=8+t,n=e.byteLength+8-r;n<8||(At(i,s,r),At(i,s+r,n),At(i,s+r+4,me.free))}function Ep(i,e){return[i.byteOffset-e-8,i.byteOffset-e+i.byteLength]}function mT(i,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,d])=>o+d-l,0),s=new Uint8Array(i.byteLength-t),r=0,n=0;for(let o=0;o<e.length;o++){let[l,d]=e[o];s.set(i.subarray(r,l),n),n+=l-r,r=d}return s.set(i.subarray(r),n),{result:s,dropped:t,droppedBefore:o=>e.reduce((l,[d,u])=>u<=o?l+u-d:l,0)}}function Hk(i){let e=Ee(i,["moov"]);if(e.length!==1||Ee(i,["moof"]).length)return null;let t=i.byteOffset,s=[],r=[],n=!1,a=Ee(e[0],["trak"]);for(let f=0;f<a.length;f++){let m=a[f],p=Ee(m,["mdia","hdlr"])[0];if((p?ji(p.subarray(8,12)):"")==="vide"){n=!0;continue}let v=Ee(m,["tkhd"])[0];if(!v)return null;let b=v[0];r.push(ee(v,b===0?12:20)),s.push(Ep(m,t))}if(!n||!s.length)return null;let o=Ee(e[0],["mvex"])[0],l=0;if(o){let f=Ee(o,["trex"]);for(let m=0;m<f.length;m++){let p=f[m];r.indexOf(ee(p,4))!==-1&&(s.push(Ep(p,t)),l+=p.byteLength+8)}}let{result:d,dropped:u,droppedBefore:c}=mT(i,s),h=e[0].byteOffset-t-8;if(At(d,h,e[0].byteLength+8-u),o&&l){let f=o.byteOffset-t-8;At(d,f-c(f),o.byteLength+8-l)}return d}function Gk(i,e,t,s,r){if(t<1)return null;let n=Ee(i,["moof"]);if(n.length!==1)return null;let a=n[0],o=i.byteOffset,l=[],d=[],u=Ee(a,["traf"]),c=!0;for(let p=0;p<u.length;p++){let g=u[p],v=Ee(g,["tfhd"])[0];if(!v)return null;ee(v,4)===e?(l.push(g),ee(v,0)&131072||(c=!1)):d.push(Ep(g,o))}if(!l.length||d.length&&!c)return null;if(s!==void 0){let p=t;for(let v=0;v<l.length;v++){let b=l[v],E=0,T=Ee(b,["trun"]);for(let S=0;S<T.length;S++){let x=T[S],k=Math.min(p,ee(x,4));if(k){At(i,x.byteOffset-o+4,k);let R=ee(x,0)&16777215,D=(R&256?4:0)+(R&512?4:0)+(R&1024?4:0)+(R&2048?4:0);Uy(i,x,8+(R&1?4:0)+(R&4?4:0)+k*D)}else At(i,x.byteOffset-o-4,me.free);p-=k,E+=k}let _=Ee(b,["senc"])[0];_&&At(i,_.byteOffset-o+4,E);let I=Ee(b,["saiz"])[0];if(I){let S=I[1]<<16|I[2]<<8|I[3],x=4;S&1&&(x+=8);let k=I[x];x+=1,At(i,I.byteOffset-o+x,E),Uy(i,I,x+4+(k===0?E:0))}}let g=Ee(i,["mdat"]);if(g.length===1){let v=g[0].byteOffset-o-8;At(i,v,s-v)}}let h=i,f=0,m=()=>0;if(d.length){({result:h,dropped:f,droppedBefore:m}=mT(i,d)),At(h,a.byteOffset-o-8,a.byteLength+8-f);for(let p=0;p<l.length;p++){let g=l[p],v=m(g.byteOffset-o),b=Ee(g,["trun"]);for(let E=0;E<b.length;E++){let T=b[E];ee(T,0)&1&&At(h,T.byteOffset-o-v+8,ee(T,8)-f)}if(v){let E=Ee(g,["saio"]);for(let T=0;T<E.length;T++){let _=E[T],I=_[0]===0?4:8,S=ee(_,0)&1?12:4,x=ee(_,S);for(S+=4;x--;S+=I){let k=S+I-4;At(h,_.byteOffset-o-v+k,ee(_,k)-v)}}}}}if(r){let{durationOffset:p,value:g}=r;At(h,p-m(p),g)}return s!==void 0?h.subarray(0,s-f):h}function Kk(i,e){let t=i.byteLength;for(let s=0;s<t;){let r=ee(i,s);if(r>8&&ee(i,s+4)===me[e])return!0;s=r>1?s+r:t}return!1}function Ee(i,e){let t=[];return e.length&&pT(i,e,0,0,i.byteLength,t),t}function pT(i,e,t,s,r,n){let a=e[t];if((a==null?void 0:a.length)!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),u=a.charCodeAt(3),c=e.length-1;for(let h=s;h<r;){let f=h+8<=r,m=h+4<=r?i[h]*16777216+(i[h+1]<<16|i[h+2]<<8|i[h+3]):ee(i,h),p=m>1?h+m:r;if(f&&i[h+4]===o&&i[h+5]===l&&i[h+6]===d&&i[h+7]===u){let g=Math.min(p,r);t===c?n.push(i.subarray(h+8,g)):pT(i,e,t+1,h+8,g,n)}h=p}}function Vk(i){let e=[],t=i[0],s=8,r=ee(i,s);s+=4;let n=0,a=0;t===0?(n=ee(i,s),a=ee(i,s+4),s+=8):(n=Ny(i,s),a=Ny(i,s+8),s+=16),s+=2;let o=i.length+a,l=fT(i,s);s+=2;for(let d=0;d<l;d++){let u=s,c=ee(i,u);u+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return $e.warn("SIDX has hierarchical references (not supported)"),null;let m=ee(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function gT(i){let e=[],t=Ee(i,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=Ee(n,["tkhd"])[0];if(a){let o=a[0],l=ee(a,o===0?12:20),d=Ee(n,["mdia","mdhd"])[0];if(d){o=d[0];let u=ee(d,o===0?12:20),c=Ee(n,["mdia","hdlr"])[0];if(c){let h=ji(c.subarray(8,12)),f={soun:Je.AUDIO,vide:Je.VIDEO}[h],m=Ee(n,["mdia","minf","stbl","stsd"])[0],p=Wk(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=ae({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return Ee(i,["moov","mvex","trex"]).forEach(r=>{let n=ee(r,4),a=e[n];a&&(a.default={duration:ee(r,12),sampleSize:ee(r,16),flags:ee(r,20)})}),e}function Wk(i){let e=i.subarray(8),t=e.subarray(86),s=ji(e.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let d=Ee(e,[s])[0].subarray(s==="enca"?28:78);Ee(d,["sinf"]).forEach(c=>{let h=Ee(c,["schm"])[0];if(h){let f=ji(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=Ee(c,["frma"])[0];m&&(r=ji(m))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Ee(t,["avcC"])[0];l&&l.length>3&&(r+="."+cu(l[1])+cu(l[2])+cu(l[3]),n=uu(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Ee(e,[s])[0],d=Ee(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=Gm(d,u),u+=2;let c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=Gm(d,u);let h=d[u++];if(h===64)r+="."+cu(h);else break;if(u+=12,d[u++]!==5)break;u=Gm(d,u);let f=d[u++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{let l=Ee(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=ee(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+qk(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){let b=p[v];(b||g)&&(g="."+b.toString(16).toUpperCase()+g)}r+=g}n=uu(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=uu(r,t)||r;break}case"vp09":{let l=Ee(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],u=l[5],c=l[6]>>4&15;r+="."+fs(d)+"."+fs(u)+"."+fs(c)}break}case"av01":{let l=Ee(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,b=l[2]&3;r+="."+d+"."+fs(u)+c+"."+fs(m)+"."+p+"."+g+v+b+"."+fs(1)+"."+fs(1)+"."+fs(1)+"."+0,n=uu("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function uu(i,e){let t=Ee(e,["dvvC"]),s=t.length?t[0]:Ee(e,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+fs(r)+"."+fs(n)}}function qk(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function Gm(i,e){let t=e+5;for(;i[e++]&128&&e<t;);return e}function cu(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function fs(i){return(i<10?"0":"")+i}function Yk(i,e){if(!i||!e)return;let t=e.keyId;(t==null?void 0:t.byteLength)===16&&e.isCommonEncryption&&vT(i,(s,r)=>{let n=s.subarray(8,24);n.some(a=>a!==0)||($e.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Ct(n)} -> ${Ct(t)}`),s.set(t,8))})}function jk(i){let e=[];return vT(i,t=>e.push(t.subarray(8,24))),e}function vT(i,e){Ee(i,["moov","trak"]).forEach(s=>{let r=Ee(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=Ee(n,["enca"]),o=a.length>0;o||(a=Ee(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);Ee(d,["sinf"]).forEach(c=>{let h=ET(c);h&&e(h,o)})})})}function ET(i){let e=Ee(i,["schm"])[0];if(e){let t=ji(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=Ee(i,["schi","tenc"])[0];if(s)return s}}}var Fy;function zk(i){return typeof TextDecoder=="undefined"?Si(i):(Fy||(Fy=new TextDecoder("utf-8"))).decode(i).replace(/\0/g,"")}function Qk(i){let e=i.byteLength,t=[];for(let s=0;s<e;){let r=s+8<=e,n=s+4<=e?i[s]*16777216+(i[s+1]<<16|i[s+2]<<8|i[s+3]):ee(i,s),a=n>1?s+n:e;if(r&&i[s+4]===109&&i[s+5]===111&&i[s+6]===111&&i[s+7]===102){let o=Math.min(a,e);for(let l=s+8;l<o;){let d=l+8<=o,u=l+4<=o?i[l]*16777216+(i[l+1]<<16|i[l+2]<<8|i[l+3]):ee(i,l),c=u>1?l+u:o;if(d&&i[l+4]===116&&i[l+5]===114&&i[l+6]===97&&i[l+7]===102){let h=Math.min(c,o),f,m,p=[];for(let g=l+8;g<h;){let v=g+8<=h,b=g+4<=h?i[g]*16777216+(i[g+1]<<16|i[g+2]<<8|i[g+3]):ee(i,g),E=b>1?g+b:h;if(v&&i[g+4]===116){let T=Math.min(E,h);i[g+5]===102&&i[g+6]===104&&i[g+7]===100?m||(m=i.subarray(g+8,T)):i[g+5]===102&&i[g+6]===100&&i[g+7]===116?f||(f=i.subarray(g+8,T)):i[g+5]===114&&i[g+6]===117&&i[g+7]===110&&p.push(i.subarray(g+8,T))}g=E}t.push({moofOffset:i.byteOffset+s,tfdt:f,tfhd:m,truns:p})}l=c}}s=a}return t}function Xk(i,e,t,s,r=!0){return yT(i,e,s,r)}function Zk(i,e,t,s,r=!1){let n=[],a=e.samples,o=yT(a,t,s,r,{isHEVCFlavor:Tl(e.codec),samples:n,timeOffset:i,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:r,tracks:o}}}function yT(i,e,t,s,r){let n={},a=!1,o=Qk(i),l=i.byteLength;for(let c=0;c<o.length;c++){let{moofOffset:h,tfdt:f,tfhd:m,truns:p}=o[c],g=ee(m,4),v=e[g];if(!v)continue;let b=n[g]||(n[g]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type}),E;if(f){let F=f[0];E=ee(f,4),F===1&&(E===hs?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=hs+1,E+=ee(f,8))),Q(E)&&(!Q(b.start)||E<b.start)&&(b.start=E),r&&Q(E)&&(r.timeOffset=E/r.timescale)}let T=(r==null?void 0:r.trackId)===g&&v.type===Je.VIDEO,_=v.default,I=ee(m,0)&16777215,S=(_==null?void 0:_.duration)||0,x,k=(_==null?void 0:_.sampleSize)||0,R=8;I&1&&(R+=8),I&2&&(R+=4),I&8&&(S=ee(m,R),x=m.byteOffset-i.byteOffset+R,R+=4),I&16&&(k=ee(m,R));let D=0,w=(I&1)!==0,N=!w&&(I&131072)!==0;w?(D=ee(m,8),D*=Math.pow(2,32),D+=ee(m,12)):N&&(D=h);let $=E||0,H=0,O=S;for(let F=0;F<p.length;F++){let B=p[F],W=ee(B,4),Z=b.sampleCount;b.sampleCount+=W;let K=B[3]&1,q=0,ce=B[3]&4,se=B[2]&1,ye=B[2]&2,ue=B[2]&4,Ce=B[2]&8,Te=8;K&&(q=vp(B,Te),Te+=4),ce&&(!(B[Te+1]&1)&&b.keyFrameIndex===void 0&&(b.keyFrameIndex=Z),Te+=4);let Ne=D+q;if(!s&&B[1]===0&&B[2]===6&&B[3]===1){var d,u;let Xe=$,ei=Ne,yi=Te,ie=-1,xe=0,we=0,pt=(d=r==null?void 0:r.timeOffset)!=null?d:0,gt=S/((u=r==null?void 0:r.timescale)!=null?u:1),Ie=(r==null?void 0:r.isHEVCFlavor)===!0,Wt=Ie?2:1;for(let Pt=0;Pt<W;Pt++){let qt=B[Te]===0?B[Te+1]<<16|B[Te+2]<<8|B[Te+3]:ee(B,Te),di=ie===-1&&b.keyFrameIndex===void 0&&(B[Te+5]&1)===0;Te+=8;let ti=Ne+qt;if(T){if(qt>0){let Bt=Ne;do{let ls=i[Bt]===0?i[Bt+1]<<16|i[Bt+2]<<8|i[Bt+3]:ee(i,Bt);Bt+=4;let vt=i[Bt],je=Ie?vt>>1&63:vt&31;(Ie?je===39||je===40:je===6)&&al(i.subarray(Bt,Bt+ls),Wt,pt,r.samples),Bt+=ls}while(Bt<ti)}pt+=gt}Ne=ti,di&&(ie=Pt,xe=Ne)}if(Ne<=l)we=W;else{let Pt=ei,qt=yi;for(let di=0;di<W;di++){let ti=B[qt]===0?B[qt+1]<<16|B[qt+2]<<8|B[qt+3]:ee(B,qt);if(Pt+=ti,Pt>l)break;we=di+1,qt+=8}}if(T&&(r.timeOffset=pt),ie!==-1&&xe<=l&&b.keyFrameIndex===void 0&&(b.keyFrameIndex=ie,b.keyFrameStart=Xe+ie*S),we){(!Q(b.ptsMin)||Xe<b.ptsMin)&&(b.ptsMin=Xe);let Pt=Xe+we*S;(!Q(b.ptsMax)||Pt>b.ptsMax)&&(b.ptsMax=Pt)}let Gs=S*W;$=Xe+Gs,H+=Gs;continue}let mt,Ft;s&&(mt=[],Ft={sampleOffset:Ne,samples:mt,defaultSampleDurationOffset:x},Ne<=l&&b.trun.push(Ft));let Zt;for(let Xe=0;Xe<W;Xe++){let ei;se?(s&&(ei=B.byteOffset-i.byteOffset+Te),O=ee(B,Te),Te+=4):O=S,ye?(Zt=ee(B,Te),Te+=4):Zt=k;let yi,ie;ue&&(ie=B[Te+1]&1?1:0,s&&(yi={isNonSync:ie,dependsOn:(B[Te]&3)===1?1:2}),Te+=4);let xe=0;if(Ce&&(xe=B[0]===0?ee(B,Te):vp(B,Te),Te+=4),T){let we=Ne,pt=0;for(;pt<Zt;){let gt=ee(i,we);we+=4,bT(r.isHEVCFlavor,i[we])&&al(i.subarray(we,we+gt),r.isHEVCFlavor?2:1,r.timeOffset+xe/r.timescale,r.samples),we+=gt,pt+=gt+4}r.timeOffset+=O/r.timescale}if(Ne+=Zt,Ne<=l){Ft&&ei!==void 0&&(Ft.lastSampleDurationOffset=ei),ie===0&&b.keyFrameIndex===void 0&&(b.keyFrameIndex=Xe,b.keyFrameStart=$);let we=$+xe;(!Q(b.ptsMin)||we<b.ptsMin)&&(b.ptsMin=we),(!Q(b.ptsMax)||we+O>b.ptsMax)&&(b.ptsMax=we+O),mt&&(mt[Xe]={cts:xe,duration:O,flags:yi,size:Zt})}$+=O,H+=O}!H&&S&&(H+=S*W)}b.duration+=H,b.duration&&(a=!0)}if(!a){let c=1/0,h=0,f=Ee(i,["sidx"]);for(let m=0;m<f.length;m++){let p=Vk(f[m]);if(p!=null&&p.references){c=Math.min(c,p.earliestPresentationTime/p.timescale);let g=p.references.reduce((v,b)=>v+b.info.duration||0,0);h=Math.max(h,g+p.earliestPresentationTime/p.timescale)}}h&&Q(h)&&Object.keys(n).forEach(m=>{n[m].duration||(n[m].duration=h*n[m].timescale-n[m].start)})}return n}function Jk(i){let e={valid:null,remainder:null},t=Ee(i,["moof"]);if(t.length<2)return e.remainder=i,e;let s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function Ci(i,e){let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function eD(i,e){let t=[],s=e.samples,r=e.timescale,n=e.id,a=!1;return Ee(s,["moof"]).map(l=>{let d=l.byteOffset-8;Ee(l,["traf"]).map(c=>{let h=Ee(c,["tfdt"]).map(f=>{let m=f[0],p=ee(f,4);return m===1&&(p*=Math.pow(2,32),p+=ee(f,8)),p/r})[0];return h!==void 0&&(i=h),Ee(c,["tfhd"]).map(f=>{let m=ee(f,4),p=ee(f,0)&16777215,g=(p&1)!==0,v=0,b=(p&2)!==0,E=(p&8)!==0,T=0,_=(p&16)!==0,I=0,S=(p&32)!==0,x=!g&&(p&131072)!==0,k=8;m===n&&(g?(v=ee(f,k),k+=4,v*=Math.pow(2,32),v+=ee(f,k),k+=4):x&&(v=d),b&&(k+=4),E&&(T=ee(f,k),k+=4),_&&(I=ee(f,k),k+=4),S&&(k+=4),e.type==="video"&&(a=Tl(e.codec)),Ee(c,["trun"]).map(R=>{let D=R[0],w=ee(R,0)&16777215,N=(w&1)!==0,$=0,H=(w&4)!==0,O=(w&256)!==0,F=0,B=(w&512)!==0,W=0,Z=(w&1024)!==0,K=(w&2048)!==0,q=0,ce=ee(R,4),se=8;N&&($=ee(R,se),se+=4),H&&(se+=4);let ye=v+$;for(let ue=0;ue<ce;ue++){if(O?(F=ee(R,se),se+=4):F=T,B?(W=ee(R,se),se+=4):W=I,Z&&(se+=4),K&&(D===0?q=ee(R,se):q=vp(R,se),se+=4),e.type===Je.VIDEO){let Ce=0;for(;Ce<W;){let Te=ee(s,ye);if(ye+=4,bT(a,s[ye])){let Ne=s.subarray(ye,ye+Te);al(Ne,a?2:1,i+q/r,t)}ye+=Te,Ce+=Te+4}}i+=F/r}}))})})}),t}function Tl(i){if(!i)return!1;let e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function bT(i,e){if(i){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function al(i,e,t,s){let r=TT(i),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 d=r.length-n,u=n;if(o<d)n+=o;else if(o>d){$e.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){let h=fT(r,u);if(u+=2,h===49){let f=ee(r,u);if(u+=4,f===1195456820){let m=r[u++];if(m===3){let p=r[u++],g=31&p,v=64&p,b=v?2+g*3:0,E=new Uint8Array(b);if(v){E[0]=p;for(let T=1;T<b;T++)E[T]=r[u++]}s.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[u++].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[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:zk(f),userDataBytes:f})}}}function TT(i){let e=i.byteLength,t,s=i.indexOf(3,3);for(;s!==-1;)i[s-1]===0&&i[s-2]===0&&(t||(t=[])).push(s),s=i.indexOf(3,s+1);if(!t)return i;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]=i[o];return n}function tD(i){let e=i[0],t="",s="",r=0,n=0,a,o=0,l=0,d=4;if(e===0){let c=du(i,d),h=c!==null?du(i,d+c.length):null;c!==null&&h!==null?(t=c,s=h,d+=c.length+h.length,r=ee(i,d),d+=4,n=ee(i,d),d+=4,o=ee(i,d),d+=4,l=ee(i,d),d+=4):($e.warn(`Unterminated ${c===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=i.length)}else if(e===1){r=ee(i,d),d+=4;let c=ee(i,d);d+=4;let h=ee(i,d);d+=4,a=2**32*c+h,dk(a)||(a=Number.MAX_SAFE_INTEGER,$e.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ee(i,d),d+=4,l=ee(i,d),d+=4;let f=du(i,d),m=f!==null?du(i,d+f.length):null;f!==null&&(t=f,d+=f.length),m!==null?(s=m,d+=m.length):($e.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"}`),d=i.length)}let u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function iD(i,...e){let t=e.length,s=8,r=t;for(;r--;)s+=e[r].byteLength;let n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function sD(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>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),iD([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function _T(i){let e=[];if(i instanceof ArrayBuffer){let t=i.byteLength,s=0;for(;s+32<t;){let r=new DataView(i,s),n=nD(r);e.push(n),s+=n.size}}return e}function rD(i){let e=[];for(let t=0;t<i.length;){let s=i[t++],r=s&7;if(r===0){for(;i[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=i[t++])&127)<<a;if(s>>3===2)if(n===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(i[t+o*2],i[t+o*2+1]),16);e.push(a)}else n===16&&e.push(i.subarray(t,t+16));t+=n}return e}function nD(i){let e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};let n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=i.buffer,o=Ct(new Uint8Array(a,t+12,16)),l=null,d=null,u=0;if(n===0)u=28;else{let h=i.getUint32(28);if(!h||s<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));u=32+h*16}if(!u)return{offset:t,size:e};let c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),n===0&&(l=rD(d)),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var ba=AT("userAgent"),aD=AT("vendor"),Km,Vm,Wm;function AT(i){try{return navigator[i]||""}catch{}return""}function oD(){if(Wm===void 0){let i=ba.match(/Safari\/(\d+)/i);Wm=i?parseInt(i[1]):0}return Wm}function Xo(){if(Km===void 0){let i=ba.match(/Chrome\/(\d+)/i);Km=i?parseInt(i[1]):0}return Km}function lD(){if(Vm===void 0){let i=ba.match(/Firefox\/(\d+)/i);Vm=i?parseInt(i[1]):0}return Vm}function ST(){return/\(Windows.+Firefox\//i.test(ba)}function dD(){return aD.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(ba)}function uD(){return/Android/.test(ba)}var va={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 Hg(i,e){let t=va[e];return!!t&&!!t[i.slice(0,4)]}function ol(i,e,t=!0){return!i.split(",").some(s=>!Gg(s,e,t))}function Gg(i,e,t=!0){var s;let r=Ir(t);return(s=r==null?void 0:r.isTypeSupported(ll(i,e)))!=null?s:!1}function ll(i,e){return`${e}/mp4;codecs=${i}`}function By(i){if(i){let e=i.substring(0,4);return va.video[e]}return 2}function Cu(i){let e=ST();return i.split(",").reduce((t,s)=>{let n=e&&Tl(s)?9:va.video[s];return n?(n*2+t)/(t?3:2):(va.audio[s]+t)/(t?2:1)},0)}var qm={};function cD(i,e=!0){if(qm[i])return qm[i];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Gg(t[r],"audio",e))return qm[i]=t[r],t[r];if(t[r]==="mp3"&&(s=Ir(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}var hD=/flac|opus|mp4a\.40\.34/i;function wu(i,e=!0){return i.replace(hD,t=>cD(t.toLowerCase(),e))}function fD(i,e){let t=[];if(i){let s=i.split(",");for(let r=0;r<s.length;r++)Hg(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function Su(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&($y(i,"audio")||$y(i,"video")))return i;if(e){let t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function $y(i,e){return Hg(i,e)&&Gg(i,e)}function mD(i){let e=i.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function pD(i){if(i.startsWith("av01.")){let e=i.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return i}function Hy(i){let e=Ir(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function yp(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var gD={supported:!0,powerEfficient:!0,smooth:!0},vD={supported:!1,smooth:!1,powerEfficient:!1},IT={supported:!0,configurations:[],decodingInfoResults:[gD]};function RT(i,e){return{supported:!1,configurations:e,decodingInfoResults:[vD],error:i}}function ED(i,e,t,s,r,n){let a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n==null?void 0:n.audioCodec,d=n==null?void 0:n.channels,u=d?parseInt(d):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=>Tl(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&Q(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function LT(i,e,t,s={}){let r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(IT);let n=[],a=yD(i),o=a.length,l=bD(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){let c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let u=navigator.userAgent;if(r.split(",").some(c=>Tl(c))&&ST())return Promise.resolve(RT(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{let c=TD(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function yD(i){var e;let t=(e=i.videoCodec)==null?void 0:e.split(","),s=kT(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:ll(pD(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function bD(i,e,t){var s;let r=(s=i.audioCodec)==null?void 0:s.split(","),n=kT(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let m={contentType:ll(f,"audio"),bitrate:t?xT(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function xT(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function kT(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function TD(i){let e="",{audio:t,video:s}=i;if(s){let r=yp(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let r=yp(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}function Ar(i,e,t){let s=encodeURIComponent(e),r=`${s}=${encodeURIComponent(t)}`,n=!1,a=[];i.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?n||(a.push(r),n=!0):o&&a.push(o)}),n||a.push(r),i.search=a.join("&")}var bp=["NONE","TYPE-0","TYPE-1",null];function _D(i){return bp.indexOf(i)>-1}var Mu=["SDR","PQ","HLG"];function AD(i){return!!i&&Mu.indexOf(i)>-1}var Iu={No:"",Yes:"YES",v2:"v2"};function Gy(i){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?Iu.v2:Iu.Yes:Iu.No}var Pu=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&Ar(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Ar(t,"_HLS_part",this.part.toString()),this.skip&&Ar(t,"_HLS_skip",this.skip),t.href}},Tn=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(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Ky(this._audioGroups,e)}hasSubtitleGroup(e){return Ky(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Ky(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function SD(){if(typeof matchMedia=="function"){let i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function ID(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||Mu.slice(0);let r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&SD(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var RD=i=>{let e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},rt=(i,e)=>JSON.stringify(i,RD(e));function LD(i,e,t,s,r){let n=Object.keys(i),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,l=r==null?void 0:r.videoCodec,d=a&&parseInt(a)===2,u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[],{preferHDR:b,allowedVideoRanges:E}=ID(e,r);for(let x=n.length;x--;){let k=i[n[x]];u||(u=k.channels[2]>0),h=Math.min(h,k.minHeight),f=Math.min(f,k.minFramerate),m=Math.min(m,k.minBitrate),E.filter(D=>k.videoRanges[D]>0).length>0&&(c=!0)}h=Q(h)?h:0,f=Q(f)?f:0;let T=Math.max(1080,h),_=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),c||(e=void 0);let I=n.length>1;return{codecSet:n.reduce((x,k)=>{let R=i[k];if(k===x)return x;if(v=c?E.filter(D=>R.videoRanges[D]>0):[],I){if(R.minBitrate>t)return us(k,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),x;if(!R.hasDefaultAudio)return us(k,"no renditions with default or auto-select sound found"),x;if(o&&k.indexOf(o.substring(0,4))%5!==0)return us(k,`audio codec preference "${o}" not found`),x;if(a&&!d){if(!R.channels[a])return us(k,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),x}else if((!o||d)&&u&&R.channels[2]===0)return us(k,"no renditions with stereo sound found"),x;if(R.minHeight>T)return us(k,`min resolution of ${R.minHeight} > maximum of ${T}`),x;if(R.minFramerate>_)return us(k,`min framerate of ${R.minFramerate} > maximum of ${_}`),x;if(!v.some(D=>R.videoRanges[D]>0))return us(k,`no variants with VIDEO-RANGE of ${rt(v)} found`),x;if(l&&k.indexOf(l.substring(0,4))%5!==0)return us(k,`video codec preference "${l}" not found`),x;if(R.maxScore<g)return us(k,`max score of ${R.maxScore} < selected max of ${g}`),x}return x&&(Cu(k)>=Cu(x)||R.fragmentError>i[x].fragmentError)?x:(p=R.minIndex,g=R.maxScore,k)},void 0),videoRanges:v,preferHDR:b,minFramerate:f,minBitrate:m,minIndex:p}}function us(i,e){$e.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function DT(i){return i.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function xD(i,e,t,s){return i.slice(t,s+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 d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),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(u=>{if(!u)return;let c=e.groups[u];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 Vy(i){if(!i)return i;let{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function ps(i,e,t){if("attrs"in i){let s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){let r=e[s];if(yn(i,r,t))return s}return-1}function yn(i,e,t){let{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||kD(n,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||DD(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function kD(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function DD(i,e=""){let t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function En(i,e){let{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function CD(i,e,t,s,r){let n=e[s],o=e.reduce((h,f,m)=>{let p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=Wy(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;let f=h.audioGroups,m=t.filter(p=>dl(p.groupId,f));return ps(i,m,r)>-1});return c>-1?c:Wy(e,s,h=>{let f=h.audioGroups,m=t.filter(p=>dl(p.groupId,f));return ps(i,m,r)>-1})}function Wy(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function Ou(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}function dl(i,e){return e?e.indexOf(i)!==-1:!0}function CT(i,e){if(e||i){let t=Qe({},e);return i&&(i.videoCodec&&(t.videoCodec=i.videoCodec),i.videoRange&&(t.allowedVideoRanges=[i.videoRange])),t}}var Tp=class extends si{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 s;let{fragCurrent:r,partCurrent:n,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.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 b=a.mainForwardBufferInfo;if(!v&&b===null)return;let E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(h<=Math.max(E,1e3*(c/(T*2))))return;let _=b?b.len/T:0,I=u.loading.first?u.loading.first-u.loading.start:-1,S=u.loaded&&I>-1,x=this.getBwEstimate(),k=a.levels,R=k[m],D=Math.max(u.loaded,Math.round(c*(r.bitrate||R.averageBitrate)/8)),w=S?h-I:h;w<1&&S&&(w=Math.min(h,u.loaded*8/x));let N=S?u.loaded*1e3/w:0,$=E/1e3,H=N?(D-u.loaded)/N:D*8/x+$;if(H<=_)return;let O=N?N*8:x,F=((s=(t==null?void 0:t.details)||a.latestLevelDetails)==null?void 0:s.live)===!0,B=a.config.abrBandWidthUpFactor,W=Number.POSITIVE_INFINITY,Z;for(Z=m-1;Z>f;Z--){let se=k[Z].maxBitrate,ye=!k[Z].details||F;if(W=this.getTimeToLoadFrag($,O,c*se,ye),W<Math.min(_,c+$))break}if(W>=H||W>c*10)return;S?this.bwEstimator.sample(h-Math.min(E,I),u.loaded):this.bwEstimator.sampleTTFB(h);let K=k[Z].maxBitrate;this.getBwEstimate()*B>K&&(this.firstAutoFloor=Math.min(Z,a.firstLevel),this.resetEstimator(K));let q=this.findBestLevel(K,f,Z,0,_,1,1);q>-1&&(Z=q),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)};au.prototype.processLine=function(i){var e=i.indexOf(":"),t=Zx(i,e),s=t[0],r=t.length===2?Fm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case cn.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case cn.PART_INF:{Cm(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case cn.SERVER_CONTROL:{Cm(this.manifest,t),this.setHoldBack();break}case cn.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case cn.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 cn.VERSION:{Cm(this.manifest,t);break}case cn.SESSION_DATA:{var o=Jx(t[1]),l=_y(o);Object.assign(this.manifest.sessionData,l)}}};au.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var Cm=function(i,e){var t=ky(e[0].replace("#EXT-X-","")),s;Xx(e[1])?(s={},s=Object.assign(Qx(e[1]),s)):s=Fm(e[1]),i[t]=s},ky=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},Fm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},zx=function(i){var e={},t=i.split("=");if(t.length>1){var s=ky(t[0]);e[s]=Fm(t[1])}return e},Qx=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=zx(r);t=Object.assign(n,t)}return t},Xx=function(i){return i.indexOf("=")>-1},Zx=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},Jx=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},ek=au,tk={safeCall:qx,safeIncrement:Ot,getComputedStyle:Yx,secondsToMs:jx,assign:Object.assign,headersStringToObject:Um,cdnHeadersToRequestId:nu,extractHostnameAndDomain:Ko,extractHostname:Ki,manifestParser:ek,generateShortID:by,generateUUID:Go,now:$t.now,findMediaElement:su},ik=tk,sk={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",NETWORK_CHANGE:"networkchange",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"},rk=sk,nk="mux-embed",ak="5.18.2",ok="2.1",kt={},vr=function(i){var e=arguments;typeof i=="string"?vr.hasOwnProperty(i)?Me.setTimeout(function(){e=Array.prototype.splice.call(e,1),vr[i].apply(null,e)},0):st.warn("`"+i+"` is an unknown task"):typeof i=="function"?Me.setTimeout(function(){i(vr)},0):st.warn("`"+i+"` is invalid.")},lk={loaded:$t.now(),NAME:nk,VERSION:ak,API_VERSION:ok,PLAYER_TRACKED:!1,monitor:function(i,e){return Wx(vr,i,e)},destroyMonitor:function(i){var e=Ks(su(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():st.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=Hi(i);kt[t]?kt[t].addHLSJS(e):st.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=Hi(i);kt[t]?kt[t].addDashJS(e):st.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=Hi(i);kt[e]?kt[e].removeHLSJS():st.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=Hi(i);kt[e]?kt[e].removeDashJS():st.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){Mm()&&e&&e.respectDoNotTrack&&st.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=Hi(i);kt[t]=new Gx(vr,t,e)},emit:function(i,e,t){var s=Hi(i);kt[s]?(kt[s].emit(e,t),e==="destroy"&&delete kt[s]):st.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=Hi(i);kt[t]?kt[t].emit("hb",e):st.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=Hi(i);kt[t]?kt[t].emitTranslator=e:st.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=Hi(i);kt[t]?kt[t].stateDataTranslator=e:st.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=Hi(i);kt[t]?kt[t].getPlayheadTime=e:st.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Mm,log:st,utils:ik,events:rk,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(vr,lk);typeof Me!="undefined"&&typeof Me.addEventListener=="function"&&Me.addEventListener("pagehide",function(i){i.persisted||(vr.WINDOW_UNLOADING=!0)},!1);var ou=vr;var Q=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},dk=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=uk},uk=Number.MAX_SAFE_INTEGER||9007199254740991,ne=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),P=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",i.UNKNOWN="unknown",i}({}),y=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({});function ck(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Bm={exports:{}},Dy;function hk(){return Dy||(Dy=1,function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.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(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;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=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[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}};i.exports=o})()}(Bm)),Bm.exports}var Ng=hk(),il=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}}},Re=function(i){return i.MANIFEST="manifest",i.LEVEL="level",i.AUDIO_TRACK="audioTrack",i.SUBTITLE_TRACK="subtitleTrack",i.MEDIA_FRAGMENT="media-fragment",i.KEY="key",i.STEERING_MANIFEST="steering-manifest",i.SERVER_CERTIFICATE="server-certificate",i.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",i}({}),te=function(i){return i.MAIN="main",i.AUDIO="audio",i.SUBTITLE="subtitle",i}({}),Je={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ku=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,fk(this,"stats")}setByteRange(e,t){let s=e.split("@",2),r;s.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[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={[Je.AUDIO]:null,[Je.VIDEO]:null,[Je.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 il),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Ng.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Je.AUDIO]=null,e[Je.VIDEO]=null,e[Je.AUDIOVIDEO]=null,this.url=null}};function Et(i){return i.sn!=="initSegment"}function zo(i,e){return i.sn===(e==null?void 0:e.sn)&&i.level===e.level}function hp(i,e){return i.sn===(e==null?void 0:e.sn)&&i.level===e.level&&i.cc===e.cc}var fa=class extends ku{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(Q(e)&&Q(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 s=Object.keys(t);if(s.length===1){let r=this._decryptdata=t[s[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=Q(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 s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[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(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Et(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 s;let r=t[e];r&&!((s=this._decryptdata)!=null&&s.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,s,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},fp=class extends ku{constructor(e,t,s,r,n){super(s),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===te.SUBTITLE&&this.stats.loading.end>0)}};function tT(i,e){let t=Object.getPrototypeOf(i);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||tT(t,e)}}function fk(i,e){let t=tT(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}function mk(i,e,t){return(e=vk(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Qe(){return Qe=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},Qe.apply(null,arguments)}function Cy(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function ae(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Cy(Object(t),!0).forEach(function(s){mk(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Cy(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function dc(i,e){if(i==null)return{};var t,s,r=pk(i,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(s=0;s<n.length;s++)t=n[s],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(i,t)&&(r[t]=i[t])}return r}function pk(i,e){if(i==null)return{};var t={};for(var s in i)if({}.hasOwnProperty.call(i,s)){if(e.indexOf(s)!==-1)continue;t[s]=i[s]}return t}function gk(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function vk(i){var e=gk(i,"string");return typeof e=="symbol"?e:e+""}function Du(i){switch(i.details){case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_TIMEOUT:case P.LEVEL_LOAD_TIMEOUT:case P.MANIFEST_LOAD_TIMEOUT:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:case P.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function iT(i){return i.details.startsWith("key")}function sT(i){return iT(i)&&!!i.frag&&!i.frag.decryptdata}function wy(i,e){let t=Du(e);return i.default[`${t?"timeout":"error"}Retry`]}function Ug(i,e){let t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function My(i){return ae(ae({},i),{errorRetry:null,timeoutRetry:null})}function sl(i,e,t,s){if(!i)return!1;let r=s==null?void 0:s.code,n=e<i.maxNumRetry&&(Ek(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function Ek(i){return rl(i)||!!i&&(i<400||i>499)}function rl(i){return i===0&&navigator.onLine===!1}function rT(i,e){return e>0&&i.loadError>0&&i.loadErrorTime!==0&&self.performance.now()-i.loadErrorTime>e}var yr=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},mp=class{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new yr(e),this.fast_=new yr(t),this.defaultTTFB_=r,this.ttfb_=new yr(e)}update(e,t){let{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new yr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new yr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new yr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;let s=Math.min(this.minDelayMs_,t/1e5),r=8*t,n=Math.max(e,s)/1e3,a=r/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},si=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 s=`[${e}]:`;this.trace=br,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},br=function(){},yk={trace:br,debug:br,log:br,warn:br,info:br,error:br};function pp(){return Qe({},yk)}function bk(i,e){let t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):br}function Py(i,e,t){return e[i]?e[i].bind(e):bk(i,t)}var gp=pp();function Tk(i,e,t){let s=pp();if(typeof console=="object"&&i===!0||typeof i=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=Py(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return pp()}r.forEach(n=>{gp[n]=Py(n,i)})}else Qe(gp,s);return s}var $e=gp;function Ir(i=!0){return typeof self=="undefined"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _k(i){return typeof self!="undefined"&&i===self.ManagedMediaSource}function nT(i,e){let t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function Ak(i){return btoa(String.fromCharCode(...i))}function uc(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer!="undefined"&&i instanceof SharedArrayBuffer}var Sk="utf-16",$m="utf-16be",Oy="utf-16le",Au="utf-8";function Ik(i,e={}){let t;uc(i)?t=new DataView(i):t=new DataView(i.buffer,i.byteOffset,i.byteLength);let s=0,{encoding:r}=e;if(!r){let d=t.getUint8(0),u=t.getUint8(1);d==239&&u==187&&t.getUint8(2)==191?(r=Au,s=3):d==254&&u==255?(r=$m,s=2):d==255&&u==254?(r=Oy,s=2):r=Au}if(typeof TextDecoder!="undefined")return new TextDecoder(r).decode(t);let{byteLength:n}=t,a=r!==$m,o="",l;for(;s<n;){switch(r){case Au:if(l=t.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<n){let d=t.getUint8(s+1);d>=128&&d<=191?(l=(l&31)<<6|d&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=n-1){let d=t.getUint8(s+1),u=t.getUint8(s+2);d>=128&&d<=191&&u>=128&&u<=191?(l=(l&15)<<12|(d&63)<<6|u&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=n-1){let d=t.getUint8(s+1),u=t.getUint8(s+2),c=t.getUint8(s+3);d>=128&&d<=191&&u>=128&&u<=191&&c>=128&&c<=191?(l=(l&7)<<18|(d&63)<<12|(u&63)<<6|c&63,s+=4):s++}else s++;else s++;break;case $m:case Sk:case Oy:l=t.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function Rk(i){let e=typeof i=="string"?new URL(i):i;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function aT(i,e){if(i<0)return-aT(-i,e);let t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){let s=Math.floor(i*t);return(s%2===0?s:s+1)/t}else return Math.round(i*t)/t}function Lk(i,e){let t;try{t=new URL(i)}catch{return i}let s=new URL(e);if(t.origin!==s.origin)return i;let r=t.pathname.split("/").slice(1),n=s.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 oT(){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,s=>{let r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?r:r&3|8).toString(16)})}}}function Fg(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function cc(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function xk(i,e){return Fg(i,e)&&cc(i,e+6)+10<=i.length-e}function lT(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function nl(i,e){let t=e,s=0;for(;Fg(i,e);){s+=10;let r=cc(i,e+6);s+=r,lT(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function kk(i){return uc(i)?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function Hm(i,e=0,t=1/0){return Dk(i,e,t,Uint8Array)}function Dk(i,e,t,s){let r=Ck(i),n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);let a=wk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new s(r,d,Math.floor(Math.min(d+Math.max(t,0),o))-d)}function Ck(i){return uc(i)?i:i.buffer}function wk(i){return i&&uc(i.buffer)&&i.byteLength!==void 0&&i.byteOffset!==void 0}function Si(i,e=!1){let t=e?i.indexOf(0):i.length,s=Ik(new DataView(i.buffer,i.byteOffset,t),{encoding:Au});return e?s:s.replace(/\0/g,"")}function Mk(i){let e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=i.data.subarray(1).indexOf(0);if(s===-1)return;let r=Si(Hm(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=Si(Hm(i.data,3+s,a)),l;return r==="-->"?l=Si(Hm(i.data,4+s+a)):l=kk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function Pk(i){if(i.size<2)return;let e=Si(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function Ok(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1,{data:s}=i,r=Si(s.subarray(t),!0);t+=r.length+1;let n=Si(s.subarray(t));return{key:i.type,info:r,data:n}}let e=Si(i.data.subarray(1));return{key:i.type,info:"",data:e}}function Nk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1,s=Si(i.data.subarray(t),!0);t+=s.length+1;let r=Si(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=Si(i.data);return{key:i.type,info:"",data:e}}function Uk(i){return i.type==="PRIV"?Pk(i):i.type[0]==="W"?Nk(i):i.type==="APIC"?Mk(i):Ok(i)}function Fk(i){let e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=cc(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}var lu=10,Bk=10;function dT(i){let e=0,t=[];for(;Fg(i,e);){let s=cc(i,e+6);i[e+5]>>6&1&&(e+=lu),e+=lu;let r=e+s;for(;e+Bk<r;){let n=Fk(i.subarray(e)),a=Uk(n);a&&t.push(a),e+=n.size+lu}lT(i,e)&&(e+=lu)}return t}function uT(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function $k(i){if(i.data.byteLength===8){let e=new Uint8Array(i.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function Bg(i){let e=dT(i);for(let t of e)if(uT(t))return $k(t)}function Ct(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function cT(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function $g(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function ji(i){return String.fromCharCode.apply(null,i)}var hs=Math.pow(2,32)-1,me={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},hT={video:1,audio:2,id3:3,text:4};function fT(i,e){let t=i[e]<<8|i[e+1];return t<0?65536+t:t}function ee(i,e){let t=i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3];return t<0?4294967296+t:t}function Ny(i,e){let t=ee(i,e);return t*=Math.pow(2,32),t+=ee(i,e+4),t}function du(i,e){let t="";for(let s=e;s<i.length;s++)if(t+=String.fromCharCode(i[s]),i[s]===0)return t;return null}function vp(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function At(i,e,t){i[e]=t>>24,i[e+1]=t>>16&255,i[e+2]=t>>8&255,i[e+3]=t&255}function Uy(i,e,t){let s=e.byteOffset-i.byteOffset-8,r=8+t,n=e.byteLength+8-r;n<8||(At(i,s,r),At(i,s+r,n),At(i,s+r+4,me.free))}function Ep(i,e){return[i.byteOffset-e-8,i.byteOffset-e+i.byteLength]}function mT(i,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,d])=>o+d-l,0),s=new Uint8Array(i.byteLength-t),r=0,n=0;for(let o=0;o<e.length;o++){let[l,d]=e[o];s.set(i.subarray(r,l),n),n+=l-r,r=d}return s.set(i.subarray(r),n),{result:s,dropped:t,droppedBefore:o=>e.reduce((l,[d,u])=>u<=o?l+u-d:l,0)}}function Hk(i){let e=Ee(i,["moov"]);if(e.length!==1||Ee(i,["moof"]).length)return null;let t=i.byteOffset,s=[],r=[],n=!1,a=Ee(e[0],["trak"]);for(let f=0;f<a.length;f++){let m=a[f],p=Ee(m,["mdia","hdlr"])[0];if((p?ji(p.subarray(8,12)):"")==="vide"){n=!0;continue}let v=Ee(m,["tkhd"])[0];if(!v)return null;let E=v[0];r.push(ee(v,E===0?12:20)),s.push(Ep(m,t))}if(!n||!s.length)return null;let o=Ee(e[0],["mvex"])[0],l=0;if(o){let f=Ee(o,["trex"]);for(let m=0;m<f.length;m++){let p=f[m];r.indexOf(ee(p,4))!==-1&&(s.push(Ep(p,t)),l+=p.byteLength+8)}}let{result:d,dropped:u,droppedBefore:c}=mT(i,s),h=e[0].byteOffset-t-8;if(At(d,h,e[0].byteLength+8-u),o&&l){let f=o.byteOffset-t-8;At(d,f-c(f),o.byteLength+8-l)}return d}function Gk(i,e,t,s,r){if(t<1)return null;let n=Ee(i,["moof"]);if(n.length!==1)return null;let a=n[0],o=i.byteOffset,l=[],d=[],u=Ee(a,["traf"]),c=!0;for(let p=0;p<u.length;p++){let g=u[p],v=Ee(g,["tfhd"])[0];if(!v)return null;ee(v,4)===e?(l.push(g),ee(v,0)&131072||(c=!1)):d.push(Ep(g,o))}if(!l.length||d.length&&!c)return null;if(s!==void 0){let p=t;for(let v=0;v<l.length;v++){let E=l[v],b=0,T=Ee(E,["trun"]);for(let S=0;S<T.length;S++){let x=T[S],k=Math.min(p,ee(x,4));if(k){At(i,x.byteOffset-o+4,k);let R=ee(x,0)&16777215,D=(R&256?4:0)+(R&512?4:0)+(R&1024?4:0)+(R&2048?4:0);Uy(i,x,8+(R&1?4:0)+(R&4?4:0)+k*D)}else At(i,x.byteOffset-o-4,me.free);p-=k,b+=k}let _=Ee(E,["senc"])[0];_&&At(i,_.byteOffset-o+4,b);let I=Ee(E,["saiz"])[0];if(I){let S=I[1]<<16|I[2]<<8|I[3],x=4;S&1&&(x+=8);let k=I[x];x+=1,At(i,I.byteOffset-o+x,b),Uy(i,I,x+4+(k===0?b:0))}}let g=Ee(i,["mdat"]);if(g.length===1){let v=g[0].byteOffset-o-8;At(i,v,s-v)}}let h=i,f=0,m=()=>0;if(d.length){({result:h,dropped:f,droppedBefore:m}=mT(i,d)),At(h,a.byteOffset-o-8,a.byteLength+8-f);for(let p=0;p<l.length;p++){let g=l[p],v=m(g.byteOffset-o),E=Ee(g,["trun"]);for(let b=0;b<E.length;b++){let T=E[b];ee(T,0)&1&&At(h,T.byteOffset-o-v+8,ee(T,8)-f)}if(v){let b=Ee(g,["saio"]);for(let T=0;T<b.length;T++){let _=b[T],I=_[0]===0?4:8,S=ee(_,0)&1?12:4,x=ee(_,S);for(S+=4;x--;S+=I){let k=S+I-4;At(h,_.byteOffset-o-v+k,ee(_,k)-v)}}}}}if(r){let{durationOffset:p,value:g}=r;At(h,p-m(p),g)}return s!==void 0?h.subarray(0,s-f):h}function Kk(i,e){let t=i.byteLength;for(let s=0;s<t;){let r=ee(i,s);if(r>8&&ee(i,s+4)===me[e])return!0;s=r>1?s+r:t}return!1}function Ee(i,e){let t=[];return e.length&&pT(i,e,0,0,i.byteLength,t),t}function pT(i,e,t,s,r,n){let a=e[t];if((a==null?void 0:a.length)!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),u=a.charCodeAt(3),c=e.length-1;for(let h=s;h<r;){let f=h+8<=r,m=h+4<=r?i[h]*16777216+(i[h+1]<<16|i[h+2]<<8|i[h+3]):ee(i,h),p=m>1?h+m:r;if(f&&i[h+4]===o&&i[h+5]===l&&i[h+6]===d&&i[h+7]===u){let g=Math.min(p,r);t===c?n.push(i.subarray(h+8,g)):pT(i,e,t+1,h+8,g,n)}h=p}}function Vk(i){let e=[],t=i[0],s=8,r=ee(i,s);s+=4;let n=0,a=0;t===0?(n=ee(i,s),a=ee(i,s+4),s+=8):(n=Ny(i,s),a=Ny(i,s+8),s+=16),s+=2;let o=i.length+a,l=fT(i,s);s+=2;for(let d=0;d<l;d++){let u=s,c=ee(i,u);u+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return $e.warn("SIDX has hierarchical references (not supported)"),null;let m=ee(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function gT(i){let e=[],t=Ee(i,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=Ee(n,["tkhd"])[0];if(a){let o=a[0],l=ee(a,o===0?12:20),d=Ee(n,["mdia","mdhd"])[0];if(d){o=d[0];let u=ee(d,o===0?12:20),c=Ee(n,["mdia","hdlr"])[0];if(c){let h=ji(c.subarray(8,12)),f={soun:Je.AUDIO,vide:Je.VIDEO}[h],m=Ee(n,["mdia","minf","stbl","stsd"])[0],p=Wk(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=ae({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return Ee(i,["moov","mvex","trex"]).forEach(r=>{let n=ee(r,4),a=e[n];a&&(a.default={duration:ee(r,12),sampleSize:ee(r,16),flags:ee(r,20)})}),e}function Wk(i){let e=i.subarray(8),t=e.subarray(86),s=ji(e.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let d=Ee(e,[s])[0].subarray(s==="enca"?28:78);Ee(d,["sinf"]).forEach(c=>{let h=Ee(c,["schm"])[0];if(h){let f=ji(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=Ee(c,["frma"])[0];m&&(r=ji(m))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Ee(t,["avcC"])[0];l&&l.length>3&&(r+="."+cu(l[1])+cu(l[2])+cu(l[3]),n=uu(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Ee(e,[s])[0],d=Ee(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=Gm(d,u),u+=2;let c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=Gm(d,u);let h=d[u++];if(h===64)r+="."+cu(h);else break;if(u+=12,d[u++]!==5)break;u=Gm(d,u);let f=d[u++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{let l=Ee(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=ee(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+qk(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){let E=p[v];(E||g)&&(g="."+E.toString(16).toUpperCase()+g)}r+=g}n=uu(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=uu(r,t)||r;break}case"vp09":{let l=Ee(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],u=l[5],c=l[6]>>4&15;r+="."+fs(d)+"."+fs(u)+"."+fs(c)}break}case"av01":{let l=Ee(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,E=l[2]&3;r+="."+d+"."+fs(u)+c+"."+fs(m)+"."+p+"."+g+v+E+"."+fs(1)+"."+fs(1)+"."+fs(1)+"."+0,n=uu("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function uu(i,e){let t=Ee(e,["dvvC"]),s=t.length?t[0]:Ee(e,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+fs(r)+"."+fs(n)}}function qk(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function Gm(i,e){let t=e+5;for(;i[e++]&128&&e<t;);return e}function cu(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function fs(i){return(i<10?"0":"")+i}function Yk(i,e){if(!i||!e)return;let t=e.keyId;(t==null?void 0:t.byteLength)===16&&e.isCommonEncryption&&vT(i,(s,r)=>{let n=s.subarray(8,24);n.some(a=>a!==0)||($e.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Ct(n)} -> ${Ct(t)}`),s.set(t,8))})}function jk(i){let e=[];return vT(i,t=>e.push(t.subarray(8,24))),e}function vT(i,e){Ee(i,["moov","trak"]).forEach(s=>{let r=Ee(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=Ee(n,["enca"]),o=a.length>0;o||(a=Ee(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);Ee(d,["sinf"]).forEach(c=>{let h=ET(c);h&&e(h,o)})})})}function ET(i){let e=Ee(i,["schm"])[0];if(e){let t=ji(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=Ee(i,["schi","tenc"])[0];if(s)return s}}}var Fy;function zk(i){return typeof TextDecoder=="undefined"?Si(i):(Fy||(Fy=new TextDecoder("utf-8"))).decode(i).replace(/\0/g,"")}function Qk(i){let e=i.byteLength,t=[];for(let s=0;s<e;){let r=s+8<=e,n=s+4<=e?i[s]*16777216+(i[s+1]<<16|i[s+2]<<8|i[s+3]):ee(i,s),a=n>1?s+n:e;if(r&&i[s+4]===109&&i[s+5]===111&&i[s+6]===111&&i[s+7]===102){let o=Math.min(a,e);for(let l=s+8;l<o;){let d=l+8<=o,u=l+4<=o?i[l]*16777216+(i[l+1]<<16|i[l+2]<<8|i[l+3]):ee(i,l),c=u>1?l+u:o;if(d&&i[l+4]===116&&i[l+5]===114&&i[l+6]===97&&i[l+7]===102){let h=Math.min(c,o),f,m,p=[];for(let g=l+8;g<h;){let v=g+8<=h,E=g+4<=h?i[g]*16777216+(i[g+1]<<16|i[g+2]<<8|i[g+3]):ee(i,g),b=E>1?g+E:h;if(v&&i[g+4]===116){let T=Math.min(b,h);i[g+5]===102&&i[g+6]===104&&i[g+7]===100?m||(m=i.subarray(g+8,T)):i[g+5]===102&&i[g+6]===100&&i[g+7]===116?f||(f=i.subarray(g+8,T)):i[g+5]===114&&i[g+6]===117&&i[g+7]===110&&p.push(i.subarray(g+8,T))}g=b}t.push({moofOffset:i.byteOffset+s,tfdt:f,tfhd:m,truns:p})}l=c}}s=a}return t}function Xk(i,e,t,s,r=!0){return yT(i,e,s,r)}function Zk(i,e,t,s,r=!1){let n=[],a=e.samples,o=yT(a,t,s,r,{isHEVCFlavor:Tl(e.codec),samples:n,timeOffset:i,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:r,tracks:o}}}function yT(i,e,t,s,r){let n={},a=!1,o=Qk(i),l=i.byteLength;for(let c=0;c<o.length;c++){let{moofOffset:h,tfdt:f,tfhd:m,truns:p}=o[c],g=ee(m,4),v=e[g];if(!v)continue;let E=n[g]||(n[g]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type}),b;if(f){let F=f[0];b=ee(f,4),F===1&&(b===hs?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(b*=hs+1,b+=ee(f,8))),Q(b)&&(!Q(E.start)||b<E.start)&&(E.start=b),r&&Q(b)&&(r.timeOffset=b/r.timescale)}let T=(r==null?void 0:r.trackId)===g&&v.type===Je.VIDEO,_=v.default,I=ee(m,0)&16777215,S=(_==null?void 0:_.duration)||0,x,k=(_==null?void 0:_.sampleSize)||0,R=8;I&1&&(R+=8),I&2&&(R+=4),I&8&&(S=ee(m,R),x=m.byteOffset-i.byteOffset+R,R+=4),I&16&&(k=ee(m,R));let D=0,w=(I&1)!==0,N=!w&&(I&131072)!==0;w?(D=ee(m,8),D*=Math.pow(2,32),D+=ee(m,12)):N&&(D=h);let $=b||0,H=0,O=S;for(let F=0;F<p.length;F++){let B=p[F],W=ee(B,4),Z=E.sampleCount;E.sampleCount+=W;let K=B[3]&1,q=0,ce=B[3]&4,re=B[2]&1,ye=B[2]&2,ue=B[2]&4,Ce=B[2]&8,Te=8;K&&(q=vp(B,Te),Te+=4),ce&&(!(B[Te+1]&1)&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=Z),Te+=4);let Ne=D+q;if(!s&&B[1]===0&&B[2]===6&&B[3]===1){var d,u;let Xe=$,ei=Ne,yi=Te,ie=-1,xe=0,we=0,pt=(d=r==null?void 0:r.timeOffset)!=null?d:0,gt=S/((u=r==null?void 0:r.timescale)!=null?u:1),Ie=(r==null?void 0:r.isHEVCFlavor)===!0,Wt=Ie?2:1;for(let Pt=0;Pt<W;Pt++){let qt=B[Te]===0?B[Te+1]<<16|B[Te+2]<<8|B[Te+3]:ee(B,Te),di=ie===-1&&E.keyFrameIndex===void 0&&(B[Te+5]&1)===0;Te+=8;let ti=Ne+qt;if(T){if(qt>0){let Bt=Ne;do{let ls=i[Bt]===0?i[Bt+1]<<16|i[Bt+2]<<8|i[Bt+3]:ee(i,Bt);Bt+=4;let vt=i[Bt],je=Ie?vt>>1&63:vt&31;(Ie?je===39||je===40:je===6)&&al(i.subarray(Bt,Bt+ls),Wt,pt,r.samples),Bt+=ls}while(Bt<ti)}pt+=gt}Ne=ti,di&&(ie=Pt,xe=Ne)}if(Ne<=l)we=W;else{let Pt=ei,qt=yi;for(let di=0;di<W;di++){let ti=B[qt]===0?B[qt+1]<<16|B[qt+2]<<8|B[qt+3]:ee(B,qt);if(Pt+=ti,Pt>l)break;we=di+1,qt+=8}}if(T&&(r.timeOffset=pt),ie!==-1&&xe<=l&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=ie,E.keyFrameStart=Xe+ie*S),we){(!Q(E.ptsMin)||Xe<E.ptsMin)&&(E.ptsMin=Xe);let Pt=Xe+we*S;(!Q(E.ptsMax)||Pt>E.ptsMax)&&(E.ptsMax=Pt)}let Gs=S*W;$=Xe+Gs,H+=Gs;continue}let mt,Ft;s&&(mt=[],Ft={sampleOffset:Ne,samples:mt,defaultSampleDurationOffset:x},Ne<=l&&E.trun.push(Ft));let Zt;for(let Xe=0;Xe<W;Xe++){let ei;re?(s&&(ei=B.byteOffset-i.byteOffset+Te),O=ee(B,Te),Te+=4):O=S,ye?(Zt=ee(B,Te),Te+=4):Zt=k;let yi,ie;ue&&(ie=B[Te+1]&1?1:0,s&&(yi={isNonSync:ie,dependsOn:(B[Te]&3)===1?1:2}),Te+=4);let xe=0;if(Ce&&(xe=B[0]===0?ee(B,Te):vp(B,Te),Te+=4),T){let we=Ne,pt=0;for(;pt<Zt;){let gt=ee(i,we);we+=4,bT(r.isHEVCFlavor,i[we])&&al(i.subarray(we,we+gt),r.isHEVCFlavor?2:1,r.timeOffset+xe/r.timescale,r.samples),we+=gt,pt+=gt+4}r.timeOffset+=O/r.timescale}if(Ne+=Zt,Ne<=l){Ft&&ei!==void 0&&(Ft.lastSampleDurationOffset=ei),ie===0&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=Xe,E.keyFrameStart=$);let we=$+xe;(!Q(E.ptsMin)||we<E.ptsMin)&&(E.ptsMin=we),(!Q(E.ptsMax)||we+O>E.ptsMax)&&(E.ptsMax=we+O),mt&&(mt[Xe]={cts:xe,duration:O,flags:yi,size:Zt})}$+=O,H+=O}!H&&S&&(H+=S*W)}E.duration+=H,E.duration&&(a=!0)}if(!a){let c=1/0,h=0,f=Ee(i,["sidx"]);for(let m=0;m<f.length;m++){let p=Vk(f[m]);if(p!=null&&p.references){c=Math.min(c,p.earliestPresentationTime/p.timescale);let g=p.references.reduce((v,E)=>v+E.info.duration||0,0);h=Math.max(h,g+p.earliestPresentationTime/p.timescale)}}h&&Q(h)&&Object.keys(n).forEach(m=>{n[m].duration||(n[m].duration=h*n[m].timescale-n[m].start)})}return n}function Jk(i){let e={valid:null,remainder:null},t=Ee(i,["moof"]);if(t.length<2)return e.remainder=i,e;let s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function Ci(i,e){let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function eD(i,e){let t=[],s=e.samples,r=e.timescale,n=e.id,a=!1;return Ee(s,["moof"]).map(l=>{let d=l.byteOffset-8;Ee(l,["traf"]).map(c=>{let h=Ee(c,["tfdt"]).map(f=>{let m=f[0],p=ee(f,4);return m===1&&(p*=Math.pow(2,32),p+=ee(f,8)),p/r})[0];return h!==void 0&&(i=h),Ee(c,["tfhd"]).map(f=>{let m=ee(f,4),p=ee(f,0)&16777215,g=(p&1)!==0,v=0,E=(p&2)!==0,b=(p&8)!==0,T=0,_=(p&16)!==0,I=0,S=(p&32)!==0,x=!g&&(p&131072)!==0,k=8;m===n&&(g?(v=ee(f,k),k+=4,v*=Math.pow(2,32),v+=ee(f,k),k+=4):x&&(v=d),E&&(k+=4),b&&(T=ee(f,k),k+=4),_&&(I=ee(f,k),k+=4),S&&(k+=4),e.type==="video"&&(a=Tl(e.codec)),Ee(c,["trun"]).map(R=>{let D=R[0],w=ee(R,0)&16777215,N=(w&1)!==0,$=0,H=(w&4)!==0,O=(w&256)!==0,F=0,B=(w&512)!==0,W=0,Z=(w&1024)!==0,K=(w&2048)!==0,q=0,ce=ee(R,4),re=8;N&&($=ee(R,re),re+=4),H&&(re+=4);let ye=v+$;for(let ue=0;ue<ce;ue++){if(O?(F=ee(R,re),re+=4):F=T,B?(W=ee(R,re),re+=4):W=I,Z&&(re+=4),K&&(D===0?q=ee(R,re):q=vp(R,re),re+=4),e.type===Je.VIDEO){let Ce=0;for(;Ce<W;){let Te=ee(s,ye);if(ye+=4,bT(a,s[ye])){let Ne=s.subarray(ye,ye+Te);al(Ne,a?2:1,i+q/r,t)}ye+=Te,Ce+=Te+4}}i+=F/r}}))})})}),t}function Tl(i){if(!i)return!1;let e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function bT(i,e){if(i){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function al(i,e,t,s){let r=TT(i),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 d=r.length-n,u=n;if(o<d)n+=o;else if(o>d){$e.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){let h=fT(r,u);if(u+=2,h===49){let f=ee(r,u);if(u+=4,f===1195456820){let m=r[u++];if(m===3){let p=r[u++],g=31&p,v=64&p,E=v?2+g*3:0,b=new Uint8Array(E);if(v){b[0]=p;for(let T=1;T<E;T++)b[T]=r[u++]}s.push({type:m,payloadType:a,pts:t,bytes:b})}}}}}else if(a===5&&o>16){let c=[];for(let m=0;m<16;m++){let p=r[u++].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[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:zk(f),userDataBytes:f})}}}function TT(i){let e=i.byteLength,t,s=i.indexOf(3,3);for(;s!==-1;)i[s-1]===0&&i[s-2]===0&&(t||(t=[])).push(s),s=i.indexOf(3,s+1);if(!t)return i;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]=i[o];return n}function tD(i){let e=i[0],t="",s="",r=0,n=0,a,o=0,l=0,d=4;if(e===0){let c=du(i,d),h=c!==null?du(i,d+c.length):null;c!==null&&h!==null?(t=c,s=h,d+=c.length+h.length,r=ee(i,d),d+=4,n=ee(i,d),d+=4,o=ee(i,d),d+=4,l=ee(i,d),d+=4):($e.warn(`Unterminated ${c===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=i.length)}else if(e===1){r=ee(i,d),d+=4;let c=ee(i,d);d+=4;let h=ee(i,d);d+=4,a=2**32*c+h,dk(a)||(a=Number.MAX_SAFE_INTEGER,$e.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ee(i,d),d+=4,l=ee(i,d),d+=4;let f=du(i,d),m=f!==null?du(i,d+f.length):null;f!==null&&(t=f,d+=f.length),m!==null?(s=m,d+=m.length):($e.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"}`),d=i.length)}let u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function iD(i,...e){let t=e.length,s=8,r=t;for(;r--;)s+=e[r].byteLength;let n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function sD(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>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),iD([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function _T(i){let e=[];if(i instanceof ArrayBuffer){let t=i.byteLength,s=0;for(;s+32<t;){let r=new DataView(i,s),n=nD(r);e.push(n),s+=n.size}}return e}function rD(i){let e=[];for(let t=0;t<i.length;){let s=i[t++],r=s&7;if(r===0){for(;i[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=i[t++])&127)<<a;if(s>>3===2)if(n===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(i[t+o*2],i[t+o*2+1]),16);e.push(a)}else n===16&&e.push(i.subarray(t,t+16));t+=n}return e}function nD(i){let e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};let n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=i.buffer,o=Ct(new Uint8Array(a,t+12,16)),l=null,d=null,u=0;if(n===0)u=28;else{let h=i.getUint32(28);if(!h||s<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));u=32+h*16}if(!u)return{offset:t,size:e};let c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),n===0&&(l=rD(d)),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var ba=AT("userAgent"),aD=AT("vendor"),Km,Vm,Wm;function AT(i){try{return navigator[i]||""}catch{}return""}function oD(){if(Wm===void 0){let i=ba.match(/Safari\/(\d+)/i);Wm=i?parseInt(i[1]):0}return Wm}function Xo(){if(Km===void 0){let i=ba.match(/Chrome\/(\d+)/i);Km=i?parseInt(i[1]):0}return Km}function lD(){if(Vm===void 0){let i=ba.match(/Firefox\/(\d+)/i);Vm=i?parseInt(i[1]):0}return Vm}function ST(){return/\(Windows.+Firefox\//i.test(ba)}function dD(){return aD.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(ba)}function uD(){return/Android/.test(ba)}var va={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 Hg(i,e){let t=va[e];return!!t&&!!t[i.slice(0,4)]}function ol(i,e,t=!0){return!i.split(",").some(s=>!Gg(s,e,t))}function Gg(i,e,t=!0){var s;let r=Ir(t);return(s=r==null?void 0:r.isTypeSupported(ll(i,e)))!=null?s:!1}function ll(i,e){return`${e}/mp4;codecs=${i}`}function By(i){if(i){let e=i.substring(0,4);return va.video[e]}return 2}function Cu(i){let e=ST();return i.split(",").reduce((t,s)=>{let n=e&&Tl(s)?9:va.video[s];return n?(n*2+t)/(t?3:2):(va.audio[s]+t)/(t?2:1)},0)}var qm={};function cD(i,e=!0){if(qm[i])return qm[i];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Gg(t[r],"audio",e))return qm[i]=t[r],t[r];if(t[r]==="mp3"&&(s=Ir(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}var hD=/flac|opus|mp4a\.40\.34/i;function wu(i,e=!0){return i.replace(hD,t=>cD(t.toLowerCase(),e))}function fD(i,e){let t=[];if(i){let s=i.split(",");for(let r=0;r<s.length;r++)Hg(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function Su(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&($y(i,"audio")||$y(i,"video")))return i;if(e){let t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function $y(i,e){return Hg(i,e)&&Gg(i,e)}function mD(i){let e=i.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function pD(i){if(i.startsWith("av01.")){let e=i.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return i}function Hy(i){let e=Ir(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function yp(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var gD={supported:!0,powerEfficient:!0,smooth:!0},vD={supported:!1,smooth:!1,powerEfficient:!1},IT={supported:!0,configurations:[],decodingInfoResults:[gD]};function RT(i,e){return{supported:!1,configurations:e,decodingInfoResults:[vD],error:i}}function ED(i,e,t,s,r,n){let a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n==null?void 0:n.audioCodec,d=n==null?void 0:n.channels,u=d?parseInt(d):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=>Tl(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&Q(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function LT(i,e,t,s={}){let r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(IT);let n=[],a=yD(i),o=a.length,l=bD(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){let c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let u=navigator.userAgent;if(r.split(",").some(c=>Tl(c))&&ST())return Promise.resolve(RT(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{let c=TD(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function yD(i){var e;let t=(e=i.videoCodec)==null?void 0:e.split(","),s=kT(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:ll(pD(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function bD(i,e,t){var s;let r=(s=i.audioCodec)==null?void 0:s.split(","),n=kT(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let m={contentType:ll(f,"audio"),bitrate:t?xT(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function xT(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function kT(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function TD(i){let e="",{audio:t,video:s}=i;if(s){let r=yp(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let r=yp(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}function Ar(i,e,t){let s=encodeURIComponent(e),r=`${s}=${encodeURIComponent(t)}`,n=!1,a=[];i.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?n||(a.push(r),n=!0):o&&a.push(o)}),n||a.push(r),i.search=a.join("&")}var bp=["NONE","TYPE-0","TYPE-1",null];function _D(i){return bp.indexOf(i)>-1}var Mu=["SDR","PQ","HLG"];function AD(i){return!!i&&Mu.indexOf(i)>-1}var Iu={No:"",Yes:"YES",v2:"v2"};function Gy(i){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?Iu.v2:Iu.Yes:Iu.No}var Pu=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&Ar(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Ar(t,"_HLS_part",this.part.toString()),this.skip&&Ar(t,"_HLS_skip",this.skip),t.href}},Tn=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(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Ky(this._audioGroups,e)}hasSubtitleGroup(e){return Ky(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Ky(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function SD(){if(typeof matchMedia=="function"){let i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function ID(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||Mu.slice(0);let r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&SD(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var RD=i=>{let e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},rt=(i,e)=>JSON.stringify(i,RD(e));function LD(i,e,t,s,r){let n=Object.keys(i),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,l=r==null?void 0:r.videoCodec,d=a&&parseInt(a)===2,u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[],{preferHDR:E,allowedVideoRanges:b}=ID(e,r);for(let x=n.length;x--;){let k=i[n[x]];u||(u=k.channels[2]>0),h=Math.min(h,k.minHeight),f=Math.min(f,k.minFramerate),m=Math.min(m,k.minBitrate),b.filter(D=>k.videoRanges[D]>0).length>0&&(c=!0)}h=Q(h)?h:0,f=Q(f)?f:0;let T=Math.max(1080,h),_=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),c||(e=void 0);let I=n.length>1;return{codecSet:n.reduce((x,k)=>{let R=i[k];if(k===x)return x;if(v=c?b.filter(D=>R.videoRanges[D]>0):[],I){if(R.minBitrate>t)return us(k,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),x;if(!R.hasDefaultAudio)return us(k,"no renditions with default or auto-select sound found"),x;if(o&&k.indexOf(o.substring(0,4))%5!==0)return us(k,`audio codec preference "${o}" not found`),x;if(a&&!d){if(!R.channels[a])return us(k,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),x}else if((!o||d)&&u&&R.channels[2]===0)return us(k,"no renditions with stereo sound found"),x;if(R.minHeight>T)return us(k,`min resolution of ${R.minHeight} > maximum of ${T}`),x;if(R.minFramerate>_)return us(k,`min framerate of ${R.minFramerate} > maximum of ${_}`),x;if(!v.some(D=>R.videoRanges[D]>0))return us(k,`no variants with VIDEO-RANGE of ${rt(v)} found`),x;if(l&&k.indexOf(l.substring(0,4))%5!==0)return us(k,`video codec preference "${l}" not found`),x;if(R.maxScore<g)return us(k,`max score of ${R.maxScore} < selected max of ${g}`),x}return x&&(Cu(k)>=Cu(x)||R.fragmentError>i[x].fragmentError)?x:(p=R.minIndex,g=R.maxScore,k)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:m,minIndex:p}}function us(i,e){$e.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function DT(i){return i.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function xD(i,e,t,s){return i.slice(t,s+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 d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),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(u=>{if(!u)return;let c=e.groups[u];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 Vy(i){if(!i)return i;let{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function ps(i,e,t){if("attrs"in i){let s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){let r=e[s];if(yn(i,r,t))return s}return-1}function yn(i,e,t){let{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||kD(n,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||DD(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function kD(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function DD(i,e=""){let t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function En(i,e){let{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function CD(i,e,t,s,r){let n=e[s],o=e.reduce((h,f,m)=>{let p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=Wy(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;let f=h.audioGroups,m=t.filter(p=>dl(p.groupId,f));return ps(i,m,r)>-1});return c>-1?c:Wy(e,s,h=>{let f=h.audioGroups,m=t.filter(p=>dl(p.groupId,f));return ps(i,m,r)>-1})}function Wy(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function Ou(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}function dl(i,e){return e?e.indexOf(i)!==-1:!0}function CT(i,e){if(e||i){let t=Qe({},e);return i&&(i.videoCodec&&(t.videoCodec=i.videoCodec),i.videoRange&&(t.allowedVideoRanges=[i.videoRange])),t}}var Tp=class extends si{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 s;let{fragCurrent:r,partCurrent:n,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.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 E=a.mainForwardBufferInfo;if(!v&&E===null)return;let b=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(h<=Math.max(b,1e3*(c/(T*2))))return;let _=E?E.len/T:0,I=u.loading.first?u.loading.first-u.loading.start:-1,S=u.loaded&&I>-1,x=this.getBwEstimate(),k=a.levels,R=k[m],D=Math.max(u.loaded,Math.round(c*(r.bitrate||R.averageBitrate)/8)),w=S?h-I:h;w<1&&S&&(w=Math.min(h,u.loaded*8/x));let N=S?u.loaded*1e3/w:0,$=b/1e3,H=N?(D-u.loaded)/N:D*8/x+$;if(H<=_)return;let O=N?N*8:x,F=((s=(t==null?void 0:t.details)||a.latestLevelDetails)==null?void 0:s.live)===!0,B=a.config.abrBandWidthUpFactor,W=Number.POSITIVE_INFINITY,Z;for(Z=m-1;Z>f;Z--){let re=k[Z].maxBitrate,ye=!k[Z].details||F;if(W=this.getTimeToLoadFrag($,O,c*re,ye),W<Math.min(_,c+$))break}if(W>=H||W>c*10)return;S?this.bwEstimator.sample(h-Math.min(b,I),u.loaded):this.bwEstimator.sampleTTFB(h);let K=k[Z].maxBitrate;this.getBwEstimate()*B>K&&(this.firstAutoFloor=Math.min(Z,a.firstLevel),this.resetEstimator(K));let q=this.findBestLevel(K,f,Z,0,_,1,1);q>-1&&(Z=q),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
|
|
17
17
|
Fragment duration: ${r.duration.toFixed(3)}
|
|
18
18
|
Time to underbuffer: ${_.toFixed(3)} s
|
|
19
19
|
Estimated load time for current fragment: ${H.toFixed(3)} s
|
|
@@ -21,28 +21,28 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
21
21
|
TTFB estimate: ${I|0} ms
|
|
22
22
|
Current BW estimate: ${Q(x)?x|0:"Unknown"} bps
|
|
23
23
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
24
|
-
Switching to level ${Z} @ ${K|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Z,this.clearTimer();let ce=()=>{this.clearTimer();let
|
|
24
|
+
Switching to level ${Z} @ ${K|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Z,this.clearTimer();let ce=()=>{this.clearTimer();let re=this.hls;if(this.fragCurrent===r&&re.loadLevel===Z&&Z>0){let ye=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Z>0?"and switching down":""}
|
|
25
25
|
Fragment duration: ${r.duration.toFixed(3)} s
|
|
26
|
-
Time to underbuffer: ${ye.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Z>f){let ue=this.findBestLevel(se.levels[f].bitrate,f,Z,0,ye,1,1);ue===-1&&(ue=f),se.nextLoadLevel=se.nextAutoLevel=ue,this.firstAutoFloor=Math.min(ue,se.firstLevel),this.resetEstimator(se.levels[ue].bitrate)}}};g||H>W*2?ce():this.timer=self.setInterval(ce,W*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},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 mp(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;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.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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case P.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&hp(s,r)){let a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){let n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;let{frag:r,part:n}=t,a=n?n.stats:r.stats;if(r.type===te.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,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){let o=n?n.duration:r.duration,l=this.hls.levels[r.level],d=(l.loaded?l.loaded.bytes:0)+a.loaded,u=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:d,duration:u},l.realBitrate=Math.round(8*d/u)}if(r.bitrateTest){let o={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(y.FRAG_BUFFERED,o),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,t){let{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;let o=((s.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(),s.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==te.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:s}=e,r=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(r,s,t,n/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,d=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(l,s),t,d);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=s&&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:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){let g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){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`),u=c=1)}let f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=s.levels[a],p=s.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e==null?void 0:e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,r,n,a,o){let{hls:l,lastLoadedFragLevel:d,fragCurrent:u,partCurrent:c}=this;if(!l)return-1;let h=r+n,f=d===-1?l.firstLevel:d,{levels:m,allAudioTracks:p,loadLevel:g,latestLevelDetails:v,config:b}=l;if(m.length===1)return 0;let E=m[f],T=!!(v!=null&&v.live),_=g===-1||d===-1,I,S="SDR",x=(E==null?void 0:E.frameRate)||0,{audioPreference:k,videoPreference:R}=b,D=this.audioTracksByGroup||(this.audioTracksByGroup=DT(p)),w=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;let F=this.codecTiers||(this.codecTiers=xD(m,D,t,s)),B=LD(F,S,e,k,R),{codecSet:W,videoRanges:Z,minFramerate:K,minBitrate:q,minIndex:ce,preferHDR:se}=B;w=ce,I=W,S=se?Z[Z.length-1]:Z[0],x=K,e=Math.max(e,q),this.log(`picked start tier ${rt(B)}`)}else I=E==null?void 0:E.codecSet,S=E==null?void 0:E.videoRange;let N=c?c.duration:u?u.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let F=s;F>=t;F--){var O;let B=m[F],W=F>f;if(!B)continue;if(b.useMediaCapabilities&&!B.supportedResult&&!B.supportedPromise){let ue=navigator.mediaCapabilities;typeof(ue==null?void 0:ue.decodingInfo)=="function"&&ED(B,D,S,x,e,k)?(B.supportedPromise=LT(B,D,ue,this.supportedCache),B.supportedPromise.then(Ce=>{if(!this.hls)return;B.supportedResult=Ce;let Te=this.hls.levels,Ne=Te.indexOf(B);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${Ne} ${rt(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(mt=>mt.smooth===!1||mt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ne} not smooth or powerEfficient: ${rt(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ne} ${rt(Ce)}`),Ne>-1&&Te.length>1&&(this.log(`Removing unsupported level ${Ne}`),this.hls.removeLevel(Ne),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):B.supportedResult=IT}if((I&&B.codecSet!==I||S&&B.videoRange!==S||W&&x>B.frameRate||!W&&x>0&&x<B.frameRate||(O=B.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(ue=>ue.smooth===!1))&&(!_||F!==w)){H.push(F);continue}let Z=B.details,K=(c?Z==null?void 0:Z.partTarget:Z==null?void 0:Z.averagetargetduration)||N||1,q;W?q=o*e:q=a*e;let ce=N&&r>=N*2&&n===0?B.averageBitrate:B.maxBitrate,se=this.getTimeToLoadFrag($,q,ce*K,!Z||Z.live);if(q>=ce&&(F===d||B.loadError===0&&B.fragmentError===0||rT(B,b.errorPenaltyExpireMs))&&(se<=$||!Q(se)||T&&!this.bitrateTestDelay||se<h)){let ue=this.forcedAutoLevel;return F!==g&&(ue===-1||ue!==g)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[H[0]].codecs}" ${m[H[0]].videoRange}; not compatible with "${I}" ${S}`),this.info(`switch candidate:${f}->${F} adjustedbw(${Math.round(q)})-bitrate=${Math.round(q-ce)} ttfb:${$.toFixed(1)} avgDuration:${K.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${se.toFixed(1)} firstSelection:${_} codecSet:${B.codecSet} videoRange:${B.videoRange} hls.loadLevel:${g}`)),_&&(this.firstSelection=F),F}}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:s}=this.hls;return Math.min(Math.max(e,s),t)}},wT={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];let a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function wD(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!Q(e))return null;let s=i[0].programDateTime;if(e<(s||0))return null;let r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){let a=i[n];if(PD(e,t,a))return a}return null}function Ea(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;let o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&qy(t,s,n)===0||MD(n,i,Math.min(r,s))))return n;let a=wT.search(e,qy.bind(null,t,s));return a&&(a!==i||!n)?a:n}function MD(i,e,t){if((e==null?void 0:e.start)===0&&e.level<i.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function qy(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function PD(i,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function MT(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments,{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return wT.search(s,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 PT(i,e){return e===i.endSN&&i.fragmentHint?i.fragmentHint:i.fragments[1+e-i.startSN]||null}var Gt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ht={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},_p=class extends si{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)===te.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.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 s;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case P.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Zo();return}case P.FRAG_GAP:case P.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Gt.SendAlternateToPenaltyBox;return}case P.PLAYLIST_UNCHANGED_ERROR:case P.LEVEL_EMPTY_ERROR:case P.LEVEL_PARSING_ERROR:{var a;let o=t.parent===te.MAIN?t.level:r.loadLevel;t.details===P.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 P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_LOAD_ERROR:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let o=r.loadLevelObj;if(o&&(n.type===Re.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===Re.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Gt.SendAlternateToPenaltyBox,t.errorAction.flags=Ht.MoveAllAlternatesMatchingHost;return}}return;case P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingHDCP};return;case P.KEY_SYSTEM_SESSION_UPDATE_FAILED:case P.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case P.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingKey};return;case P.BUFFER_ADD_CODEC_ERROR:case P.REMUX_ALLOC_ERROR:case P.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case P.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Ht.ResetMediaSource|Ht.SwitchToSDR;return;case P.INTERNAL_EXCEPTION:case P.BUFFER_APPENDING_ERROR:case P.BUFFER_APPEND_NO_PROGRESS:case P.BUFFER_FULL_ERROR:case P.LEVEL_SWITCH_ERROR:case P.BUFFER_STALLED_ERROR:case P.BUFFER_SEEK_OVER_HOLE:case P.BUFFER_NUDGE_ON_STALL:t.errorAction=Zo();return}t.type===re.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Zo())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,r=wy(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(sl(r,n,Du(e),e.response))return{action:Gt.RetryRequest,flags:Ht.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,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=wy(iT(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==P.FRAG_GAP&&r.fragmentError++,!sT(e)&&sl(o,l,Du(e),e.response)))return{action:Gt.RetryRequest,flags:Ht.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,r.loadErrorTime=self.performance.now(),d===P.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===te.AUDIO&&d===P.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Yy(e))&&c.some(({audioCodec:I})=>r.audioCodec!==I),E=e.sourceBufferName==="video"&&Yy(e)&&c.some(({codecSet:I,audioCodec:S})=>r.codecSet!==I&&r.audioCodec===S),{type:T,groupId:_}=(a=e.context)!=null?a:{};for(let I=c.length;I--;){let S=(I+h)%c.length;if(S!==h&&S>=f&&S<=m&&(c[S].loadError===0||rT(c[S],s.config.errorPenaltyExpireMs))){var o,l;let x=c[S];if(d===P.FRAG_GAP&&p===te.MAIN&&e.frag){let k=c[S].details;if(k){let R=Ea(e.frag,k.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(T===Re.AUDIO_TRACK&&x.hasAudioGroup(_)||T===Re.SUBTITLE_TRACK&&x.hasSubtitleGroup(_))continue;if(p===te.AUDIO&&(o=r.audioGroups)!=null&&o.some(k=>x.hasAudioGroup(k))||p===te.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(k=>x.hasSubtitleGroup(k))||v&&r.audioCodec===x.audioCodec||E&&r.codecSet===x.codecSet||!v&&r.audioCodec!==x.audioCodec)continue}u=S;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Gt.SendAlternateToPenaltyBox,flags:Ht.None,nextAutoLevel:u}}return{action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,r;switch((s=t.errorAction)==null?void 0:s.action){case Gt.DoNothing:break;case Gt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==P.FRAG_GAP&&t.details!==P.PLAYLIST_UNCHANGED_ERROR&&!OT(t)&&(t.fatal=!0);break;case Gt.RetryRequest:break}if((((r=t.errorAction)==null?void 0:r.flags)||0)&Ht.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let r=s.nextAutoLevel;if(s.flags===Ht.None)this.switchLevel(e,r);else if(s.flags&Ht.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let d=l;d--;)o[d].videoRange!=="SDR"?(o[d].fragmentError++,o[d].loadError++):r===void 0&&(r=d)}else if(s.flags&Ht.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l==null?void 0:l.attrs["HDCP-LEVEL"];s.hdcpLevel=d;let u=d==="NONE";d&&!u?(t.maxHdcpLevel=bp[bp.indexOf(d)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=Ht.MoveAllAlternatesMatchingKey)}if(s.flags&Ht.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,d=l.length;for(let c=d;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) ${Ct(o.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${e.error})`),this.hls.removeLevel(c)}let u=e.frag;if(this.hls.levels.length<d)s.resolved=!0;else if(u&&u.type!==te.MAIN){let c=u.decryptdata;c&&!o.matches(c)&&(s.resolved=!0)}}}s.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===P.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=yp(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}};function Yy(i){let e=i.details;return e===P.BUFFER_ADD_CODEC_ERROR||e===P.MEDIA_SOURCE_REQUIRES_RESET||e===P.BUFFER_APPEND_ERROR&&!OT(i)}function OT(i){return i.details===P.BUFFER_APPEND_ERROR&&(i.error.name==="QuotaExceededError"||i.error.name==="InvalidStateError")}function Zo(i){let e={action:Gt.DoNothing,flags:Ht.None};return i&&(e.resolved=!0),e}var ft={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ap=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 s=this.activePartLists[t];if(s)for(let r=s.length;r--;){let n=s[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,s){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&&(!s||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,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 d=this.fragments[l];if(!d||!this.hls)return;let u=d.body;if(o>=u.sn)return;if(!d.buffered&&(!d.loaded||a)){u.type===s&&this.removeFragment(u);return}let c=d.range[e];if(c){if(c.time.length===0){this.removeFragment(u);return}if(c.time.some(h=>{let f=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return f&&this.removeFragment(u),f}),r&&r!==u&&Xo()){let h=r.endPTS,f=u.startPTS;if(h&&f&&d.range.video){let m=f-h;m<0&&m>-.1&&(this.removeFragment(u),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:h+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:s,part:r,id:n}=e;if(!t||!Et(s))return;let a=da(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;let l=!s.relurl;Object.keys(t).forEach(u=>{let c=s.elementaryStreams[u];if(!c)return;let h=t[u],f=l||c.partial===!0;o.range[u]=this.getBufferedTimes(s,r,f,h),this.detectEvictedFragments(u,h,n,s,r)}),o.loaded=null;let d=Object.keys(o.range);if(d.length){if(this.bufferedEnd(o,s),hu(o)||this.removeParts(s.sn-1,s.type),!r){let u=Math.min(.004,s.duration);d.some(c=>{var h;let f=(h=o.range[c])==null?void 0:h.time,m=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<u;return m&&this.addAsGap(s),m})}}else this.removeFragment(s)}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 s=this.activePartLists[t];s&&(this.activePartLists[t]=jy(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){let s=da(e),r=this.fragments[s];return!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,s,r){let n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){let c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let u=l[d];u&&hu(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||hu(t))}getState(e){let t=da(e),s=this.fragments[t];return s?s.buffered?hu(s)?ft.PARTIAL:ft.OK:ft.APPENDING:ft.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Et(t.frag)||t.frag.bitrateTest)return;let s=t.frag,r=t.part?null:t,n=da(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:r,timeRanges:n}=t;if(!Et(s))return;let a=s.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=da(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){let n=t[s[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,s){let{fragments:r}=this,n=0,a=0,o=Object.keys(r);for(let l=0;l<o.length;l++){let d=r[o[l]];if(!d||!d.buffered||d.body.type!==t)continue;let u=d.body;if(u.gap)return 0;let c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&u.bitrate*8*u.duration;if(u.end<=e&&c&&(n+=c,a=Math.max(a,u.end),n>=s))return a}return a>0?a:0}removeFragmentsInRange(e,t,s,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!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=da(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let r=e.sn;this.activePartLists[e.type]=jy(s,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(s=>s.clearElementaryStreamInfo())}};function hu(i){var e,t,s,r;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial||(r=i.range.subs)!=null&&r.partial)}function da(i){return`${i.type}_${i.level}_${i.sn}`}function jy(i,e){return i.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Rr={cbc:0,ctr:1},Sp=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Rr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Rr.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 OD(i){let e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}var Ip=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),s=new Uint32Array(4);for(let r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=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 b=f[m],E=f[b],T=f[E],_=f[v]*257^v*16843008;r[m]=_<<24|_>>>8,n[m]=_<<16|_>>>16,a[m]=_<<8|_>>>24,o[m]=_,_=T*16843009^E*65537^b*257^m*16843008,d[v]=_<<24|_>>>8,u[v]=_<<16|_>>>16,c[v]=_<<8|_>>>24,h[v]=_,m?(m=b^f[f[f[T^b]]],p^=f[f[p]]):m=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)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,d=this.keySchedule=new Uint32Array(a),u=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],b,E;for(o=0;o<a;o++){if(o<n){b=d[o]=t[o];continue}E=b,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]),d[o]=b=(d[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=d[o]:E=d[o-4],l<4||o<=4?u[l]=E:u[l]=m[c[E>>>24]]^p[c[E>>>16&255]]^g[c[E>>>8&255]]^v[c[E&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s),f=h[0],m=h[1],p=h[2],g=h[3],v=new Int32Array(e),b=new Int32Array(v.length),E,T,_,I,S,x,k,R,D,w,N,$,H,O,F=this.networkToHostOrderSwap;for(;t<v.length;){for(D=F(v[t]),w=F(v[t+1]),N=F(v[t+2]),$=F(v[t+3]),S=D^n[0],x=$^n[1],k=N^n[2],R=w^n[3],H=4,O=1;O<r;O++)E=l[S>>>24]^d[x>>16&255]^u[k>>8&255]^c[R&255]^n[H],T=l[x>>>24]^d[k>>16&255]^u[R>>8&255]^c[S&255]^n[H+1],_=l[k>>>24]^d[R>>16&255]^u[S>>8&255]^c[x&255]^n[H+2],I=l[R>>>24]^d[S>>16&255]^u[x>>8&255]^c[k&255]^n[H+3],S=E,x=T,k=_,R=I,H=H+4;E=a[S>>>24]<<24^a[x>>16&255]<<16^a[k>>8&255]<<8^a[R&255]^n[H],T=a[x>>>24]<<24^a[k>>16&255]<<16^a[R>>8&255]<<8^a[S&255]^n[H+1],_=a[k>>>24]<<24^a[R>>16&255]<<16^a[S>>8&255]<<8^a[x&255]^n[H+2],I=a[R>>>24]<<24^a[S>>16&255]<<16^a[x>>8&255]<<8^a[k&255]^n[H+3],b[t]=F(E^f),b[t+1]=F(I^m),b[t+2]=F(_^p),b[t+3]=F(T^g),f=D,m=w,p=N,g=$,t=t+4}return b.buffer}},Rp=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=ND(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function ND(i){switch(i){case Rr.cbc:return"AES-CBC";case Rr.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}var UD=16,ul=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 s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?r.start===0&&r.end>=s.length?s:s.slice(r.start,r.end):OD(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,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,s,r);let d=this.flush();d?a(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Rr.cbc||t.byteLength!==16)return $e.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ci(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Ip),d.expandKey(t);let u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new Rp(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Sp(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>($e.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,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,s=e.length-e.length%UD;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&($e.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},zy=Math.pow(2,17),Nu=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,s,r){let n=e.url;if(!n)return Promise.reject(new Di({type:re.NETWORK_ERROR,details:P.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((d,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){u(Xy(e));return}else e.gap=!1;let c=this.loader=o?new o(a):new l(a),h=Qy(e,null,t);e.loader=c;let f=My(a.fragLoadPolicy.default),m={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zy};c.stats.retry=e.stats.retry,e.stats=c.stats;let p={onSuccess:(g,v,b,E)=>{this.resetLoader(e,c);let T=g.data;b.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),d({frag:e,part:null,payload:T,networkDetails:E})},onError:(g,v,b,E)=>{this.resetLoader(e,c),u(new Di({type:re.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ae({url:n,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:b,stats:E}))},onAbort:(g,v,b)=>{this.resetLoader(e,c),u(new Di({type:re.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:b,stats:g}))},onTimeout:(g,v,b)=>{this.resetLoader(e,c),u(new Di({type:re.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:b,stats:g}))}};if(s){let g=this.gateProgress(s,r);p.onProgress=(v,b,E,T)=>g({frag:e,part:null,payload:E,networkDetails:T})}c.load(h,m,p)})}gateProgress(e,t){let s=e;if(t){let r=[],n=!1;t.then(()=>{n=!0,r.forEach(a=>e(a)),r.length=0}).catch(()=>{}),s=a=>{n?e(a):r.push(a)}}return s}loadPart(e,t,s){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(Xy(e,t));return}let d=this.loader=n?new n(r):new a(r),u=Qy(e,t);e.loader=d;let c=My(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zy};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new Di({type:re.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ae({url:u.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,d),l(new Di({type:re.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Di({type:re.NETWORK_ERROR,details:P.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 s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);let a=s.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 Qy(i,e=null,t){let s=e||i,r={type:Re.MEDIA_FRAGMENT,frag:i,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=Uu(i,e,t);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function Uu(i,e=null,t){let s={},r=e||i,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(Q(n)&&Q(a)){var o;if((i.sn==="initSegment"||t)&&FD((o=i.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16,d=Math.ceil(a/16)*16;s.decryptRange={start:n-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:d}}else s.byteRange={start:n,end:a}}return s}function Xy(i,e){let t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:re.MEDIA_ERROR,details:P.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new Di(s)}function FD(i){return i==="AES-128"||i==="AES-256"}var Di=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Fu=class extends si{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(){}},cl=class{constructor(e,t,s,r=0,n=-1,a=!1,o,l,d){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=fu(),this.buffering={audio:fu(),video:fu(),audiovideo:fu()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=d,this.iframe=l||!1}};function fu(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Zy={length:0,start:()=>0,end:()=>0},be=class i{static isBuffered(e,t){if(e){let s=i.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=i.getBuffered(e);return i.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let r=i.bufferedRanges(e);if(r.length)return i.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);let c=n.length;if(c){let h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){let c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Zy}catch(t){return $e.log("failed to get media.buffered",t),Zy}}},Lp=/\{\$([a-zA-Z0-9-_]+)\}/g;function Jy(i){return Lp.lastIndex=0,Lp.test(i)}function Kg(i,e){if(i.variableList!==null||i.hasVariableRefs){let t=i.variableList;return e.replace(Lp,s=>{let r=s.substring(2,s.length-1),n=t==null?void 0:t[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function eb(i,e,t){let s=i.variableList;s||(i.variableList=s={});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){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function BD(i,e,t){let s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var $D=/^(\d+)x(\d+)$/,tb=/(.+?)=(".*?"|.*?)(?:,|$)/g,ht=class i{constructor(e,t){typeof e=="string"&&(e=i.parseAttrList(e,t)),Qe(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 s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=$D.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,r={},n='"';for(tb.lastIndex=0;(s=tb.exec(e))!==null;){let a=s[1].trim(),o=s[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Kg(t,o);else if(!d&&!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":$e.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},HD="com.apple.hls.interstitial";function GD(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function KD(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}var Bu=class{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:s,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){$e.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Qe(new ht({}),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"]);Q(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?($e.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(Q(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===HD}get isValid(){return!!this.id&&!this._badValueForSameId&&Q(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`:Q(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"}},NT=10,xp=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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||NT}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 $u(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function ib(i,e){return!i&&!e?!0:!i||!e?!1:$u(i,e)}function pa(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Vg(i){switch(i){case"AES-128":case"AES-256":return Rr.cbc;case"AES-256-CTR":return Rr.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function kp(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function VD(i){let e=kp(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function UT(i){let e=function(s,r,n){let a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function FT(i){let e=i.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=$g(a)):t=VD(a)}}return t}var Hu=typeof self!="undefined"?self:void 0,dt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},jt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function mu(i){switch(i){case jt.FAIRPLAY:return dt.FAIRPLAY;case jt.PLAYREADY:return dt.PLAYREADY;case jt.WIDEVINE:return dt.WIDEVINE;case jt.CLEARKEY:return dt.CLEARKEY}}var BT={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ym(i){switch(i){case dt.FAIRPLAY:return jt.FAIRPLAY;case dt.PLAYREADY:return jt.PLAYREADY;case dt.WIDEVINE:return jt.WIDEVINE;case dt.CLEARKEY:return jt.CLEARKEY}}function Wo(i){let{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[dt.FAIRPLAY,dt.WIDEVINE,dt.PLAYREADY,dt.CLEARKEY].filter(r=>!!e[r]):[];return!s[dt.WIDEVINE]&&t&&s.push(dt.WIDEVINE),s}var $T=function(i){return Hu!=null&&(i=Hu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function WD(i,e,t,s){let r;switch(i){case dt.FAIRPLAY:r=["cenc","sinf"];break;case dt.WIDEVINE:case dt.PLAYREADY:r=["cenc"];break;case dt.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return qD(r,e,t,s)}function qD(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function YD(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Wg(i){let e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=ji(e),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=$g(o).subarray(0,16);return UT(l),l}}return null}var ua={},_n=class i{static clearKeyUriToKeyIdMap(){ua={}}static setKeyIdForUri(e,t){ua[e]=t}static addKeyIdForUri(e){let t=Object.keys(ua).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),ua[e]=s,s}constructor(e,t,s,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=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!pa(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(cT(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$u(e.keyFormatVersions,this.keyFormatVersions)&&ib(e.iv,this.iv)&&ib(e.keyId,this.keyId)}isSupported(){if(this.method){if(pa(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case jt.FAIRPLAY:case jt.WIDEVINE:case jt.PLAYREADY:case jt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var s;if(!this.encrypted||!this.uri)return null;if(pa(this.method)){let a=this.iv;return a||(typeof e!="number"&&($e.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=zD(e)),new i(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=ua[this.uri];if(a&&!$u(this.keyId,a)&&i.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=FT(this.uri);if(r)switch(this.keyFormat){case jt.WIDEVINE:if(this.pssh=r,!this.keyId){let a=_T(r.buffer).filter(o=>o.systemId===BT.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=sb(t));break;case jt.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=sD(a,null,r),this.keyId=Wg(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(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=jD(t),a||(a=sb(t),a||(a=ua[this.uri])),a&&(this.keyId=a,i.setKeyIdForUri(this.uri,a))}return this}};function jD(i){let e=i==null?void 0:i[jt.WIDEVINE];return e?e.keyId:null}function sb(i){let e=i==null?void 0:i[jt.PLAYREADY];if(e){let t=FT(e.uri);if(t)return Wg(t)}return null}function zD(i){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}var rb=/#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,nb=/#EXT-X-MEDIA:(.*)/g,QD=/^#EXT(?:INF|-X-TARGETDURATION):/m,jm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),XD=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("|")),_r=class i{static findGroup(e,t){for(let s=0;s<e.length;s++){let r=e[s];if(r.id===t)return r}}static resolve(e,t){return Ng.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return QD.test(e)}static parseMasterPlaylist(e,t){let s=Jy(e),r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(rb.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=rb.exec(e))!=null;)if(a[1]){let l=new ht(a[1],r),d=ab(l,a[2],t,r,n);d&&r.levels.push(d)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"I-FRAME-STREAM-INF":{let u=new ht(d,r),c=ab(u,u.URI,t,r,n,!0);c&&r.iframeVariants.push(c)}break;case"SESSION-DATA":{let u=new ht(d,r),c=u["DATA-ID"];c&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[c]=u);break}case"SESSION-KEY":{let u=ob(d,t,r);u.encrypted&&u.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(u)):$e.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let u=new ht(d,r);eb(r,u,t)}break}case"CONTENT-STEERING":{let u=new ht(d,r);r.contentSteering={uri:i.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=lb(d);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,s){let r,n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(nb.lastIndex=0;(r=nb.exec(e))!==null;){let d=new ht(r[1],s),u=d.TYPE;if(u){let c=o[u],h=n[u]||[];n[u]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?i.resolve(d.URI,t):""};if(m&&(b.assocLang=m),p&&(b.channels=p),g&&(b.characteristics=g),v&&(b.instreamId=v),c!=null&&c.length){let E=i.findGroup(c,b.groupId)||c[0];ub(b,E,"audioCodec"),ub(b,E,"textCodec")}h.push(b)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;let l={url:t},d=new xp(t),u=d.fragments,c=[],h=null,f=0,m=0,p=0,g=0,v=0,b=null,E=new fa(r,l),T,_,I,S=-1,x=!1,k=null,R;if(jm.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Jy(e),((o=jm.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(T=jm.exec(e))!==null;){x&&(x=!1,E=new fa(r,l),E.playlistOffset=p,E.setStart(p),E.sn=f,E.cc=g,v&&(E.bitrate=v),E.level=s,h&&(E.initSegment=h,h.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),k&&(E.setByteRange(k),k=null)));let H=T[1];if(H){E.duration=parseFloat(H);let O=(" "+T[2]).slice(1);E.title=O||null,E.tagList.push(O?["INF",H,O]:["INF",H])}else if(T[3]){if(Q(E.duration)){var D;E.playlistOffset=p,E.setStart(p),I&&hb(E,I,d),E.sn=f,E.level=s,E.cc=g;let O=(" "+T[3]).slice(1);E.relurl=Kg(d,O),Dp(E,b,c),b=E,p+=E.duration,f++,m=0;let F=E.byteRange;if(F.length===2&&(E.bitrate=(F[1]-F[0])*8/E.duration|0),d.iframesOnly&&F[0]&&((D=h)==null?void 0:D.cc)!==g){let B=new fa(r,l);B.relurl=E.relurl,B.setByteRange(`${Math.min(F[0],7*188)}@0`),B.level=s,B.sn="initSegment",I&&(B.levelkeys=I,I.identity&&(B._decryptdata=I.identity.getDecryptData(0))),h=B,E.initSegment=h}u.push(E),x=!0}}else{if(T=T[0].match(XD),!T){$e.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<T.length&&T[_]===void 0;_++);let O=(" "+T[_]).slice(1),F=(" "+T[_+1]).slice(1),B=T[_+2]?(" "+T[_+2]).slice(1):null;switch(O){case"BYTERANGE":b?E.setByteRange(F,b):E.setByteRange(F);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=F,E.tagList.push(["PROGRAM-DATE-TIME",F]),S===-1&&(S=u.length);break;case"PLAYLIST-TYPE":d.type&&Ws(d,O,T),d.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Ws(d,O,T):b!==null&&eC(d,O,T),d.startSN=parseInt(F),f=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&Ws(d,O,T);let W=new ht(F,d),Z=W.decimalInteger("SKIPPED-SEGMENTS");if(Q(Z)){d.skippedSegments+=Z;for(let q=Z;q--;)u.push(null);f+=Z}let K=W.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(K.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Ws(d,O,T),d.targetduration=Math.max(parseInt(F),1);break;case"VERSION":d.version!==null&&Ws(d,O,T),d.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||Ws(d,O,T),d.live=!1;break;case"#":(F||B)&&E.tagList.push(B?[F,B]:[F]);break;case"DISCONTINUITY":g++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([O]);break;case"BITRATE":E.tagList.push([O,F]),v=parseInt(F)*1e3,Q(v)?E.bitrate=v:v=0;break;case"DATERANGE":{let W=new ht(F,d),Z=new Bu(W,d.dateRanges[W.ID],d.dateRangeTagCount);d.dateRangeTagCount++,Z.isValid||d.skippedSegments?d.dateRanges[Z.id]=Z:$e.log(`Ignoring invalid DATERANGE tag: ${Z.invalidReason}: ${F}`),E.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{let W=new ht(F,d);"IMPORT"in W?BD(d,W,a):eb(d,W,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0&&Ws(d,O,T),d.startCC=g=parseInt(F),u.forEach(W=>W&&(W.cc=g));break;case"KEY":{let W=ob(F,t,d);if(W.isSupported()){if(W.method==="NONE"){I=void 0;break}I||(I={});let Z=I[W.keyFormat];Z!=null&&Z.matches(W)||(Z&&(I=Qe({},I)),I[W.keyFormat]=W)}else $e.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":d.startTimeOffset=lb(F);break;case"MAP":{let W=new ht(F,d);if(E.duration){let Z=new fa(r,l);cb(Z,W,s,I),h=Z,E.initSegment=h,h.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime)}else{let Z=E.byteRangeEndOffset;if(Z){let K=E.byteRangeStartOffset;k=`${Z-K}@${K}`}else k=null;cb(E,W,s,I),h=E,x=!0}h.cc=g;break}case"SERVER-CONTROL":{R&&Ws(d,O,T),R=new ht(F),d.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),d.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Ws(d,O,T);let W=new ht(F);d.partTarget=W.decimalFloatingPoint("PART-TARGET");break}case"PART":{let W=d.partList;W||(W=d.partList=[]);let Z=m>0?W[W.length-1]:void 0,K=m++,q=new ht(F,d),ce=new fp(q,E,l,K,Z);W.push(ce),E.duration+=ce.duration;break}case"PRELOAD-HINT":{let W=new ht(F,d);d.preloadHint=W;break}case"RENDITION-REPORT":{let W=new ht(F,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(W);break}default:$e.warn(`line parsed but not handled: ${T}`);break}}}b&&!b.relurl?(u.pop(),p-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(Dp(E,b,c),E.cc=g,d.fragmentHint=E,I&&hb(E,I,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let w=u.length,N=u[0],$=u[w-1];if(p+=d.skippedSegments*d.targetduration,p>0&&w&&$){d.averagetargetduration=p/w;let H=$.sn;d.endSN=H!=="initSegment"?H:0,d.live||($.endList=!0),S>0&&(JD(u,S,S>w-1?E:null),N&&c.unshift(N))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&N&&HT(c,d),d.endCC=g,d}};function ab(i,e,t,s,r,n){var a;if(e===void 0)return null;let o=Kg(s,e),l={attrs:i,bitrate:i.decimalInteger("BANDWIDTH")||i.decimalInteger("AVERAGE-BANDWIDTH"),name:i.NAME,url:_r.resolve(o,t)},d=i.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),db(i.CODECS,l);let u=i["SUPPLEMENTAL-CODECS"];return u&&(l.supplemental={},db(u,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||r.push(l),n&&(l.iframes=!0),l}function HT(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;let s=i[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]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;let c=ZD(e,d,i,u,r);if(c){l.tagAnchor=c.ref;break}}}}function ZD(i,e,t,s,r){let n=t[s];if(n){let o=n.programDateTime;if(e>=o||s===0){var a;let l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=n.sn-i.startSN,u=i.fragments;if(d>=0&&d<u.length){if(u.length>t.length){let c=t[s+1]||u[u.length-1],h=Math.min(c.sn-i.startSN,u.length-1);for(let f=h;f>d;f--){let m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return u[f]}}return u[d]}}}}return null}function ob(i,e,t){var s,r;let n=new ht(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&$e.error(`Invalid IV: ${n.IV}`);let c=o?_r.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new _n(a,c,u,h,l,n.KEYID)}function lb(i){let t=new ht(i).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function db(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{let r=t.filter(n=>Hg(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function ub(i,e,t){let s=e[t];s&&(i[t]=s)}function JD(i,e,t){if(t||(t=i[e]),!!t)for(let s=e;s--;){let r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Dp(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function cb(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function hb(i,e,t){i.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function Ws(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function eC(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function zm(i,e){let t=e.startPTS;if(Q(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function GT(i,e,t,s,r,n,a,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let d=t,u=s,c=e.startPTS,h=e.endPTS;if(Q(c)){let b=Math.abs(c-t);i&&b>i.totalduration?o.warn(`media timestamps and playlist times differ by ${b}s for level ${e.level} ${i.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(b,e.deltaPTS):e.deltaPTS=b,d=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,u=Math.min(s,h),s=Math.max(s,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(s-e.start),e.startPTS=t,e.maxStartPTS=d,e.startDTS=r,e.endPTS=s,e.minEndPTS=u,e.endDTS=n;let m=e.sn;if(!i||m<i.startSN||m>i.endSN)return 0;let p,g=m-i.startSN,v=i.fragments;for(v[g]=e,p=g;p>0;p--)zm(v[p],v[p-1]);for(p=g;p<v.length-1;p++)zm(v[p],v[p+1]);return i.fragmentHint&&zm(v[v.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,f}function tC(i,e,t){if(i===e)return;let s=null,r=i.fragments;for(let u=r.length-1;u>=0;u--){let c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;rC(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){let m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}Q(u.startPTS)&&Q(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=iC(i.dateRanges,e,t));let u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Dp(o[c],o[c-1],u);HT(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let u=WT(i,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}if(sC(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats,c.gap=u.gap||c.gap}),n){let u=e.iframesOnly&&n.type===te.MAIN;GT(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,u,t)}else KT(i,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function iC(i,e,t){let{dateRanges:s,recentlyRemovedDateranges:r}=e,n=Qe({},i);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{let d=n[l],u=new Bu(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${rt(s[l].attr)}"`)}),n):s}function sC(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<n;r++){let a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function rC(i,e,t){var s;let r=e.skippedSegments,n=Math.max(i.startSN,e.startSN)-e.startSN,a=(i.fragmentHint?1:0)+(r?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,o=e.startSN-i.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=(s=i.fragmentHint)!=null&&s.duration?i.fragments.concat(i.fragmentHint):i.fragments;for(let u=n;u<=a;u++){let c=d[o+u],h=l[u];if(r&&!h&&c&&(h=e.fragments[u]=c),c&&h){t(c,h,u,l);let f=c.relurl,m=h.relurl;if(f&&aC(f,m)){e.playlistParsingError=fb(`media sequence mismatch ${h.sn}:`,i,e,c,h);return}else if(c.cc!==h.cc){e.playlistParsingError=fb(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,i,e,c,h);return}}}}function fb(i,e,t,s,r){return new Error(`${i} ${r.url}
|
|
26
|
+
Time to underbuffer: ${ye.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Z>f){let ue=this.findBestLevel(re.levels[f].bitrate,f,Z,0,ye,1,1);ue===-1&&(ue=f),re.nextLoadLevel=re.nextAutoLevel=ue,this.firstAutoFloor=Math.min(ue,re.firstLevel),this.resetEstimator(re.levels[ue].bitrate)}}};g||H>W*2?ce():this.timer=self.setInterval(ce,W*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},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 mp(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;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.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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case P.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&hp(s,r)){let a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){let n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;let{frag:r,part:n}=t,a=n?n.stats:r.stats;if(r.type===te.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,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){let o=n?n.duration:r.duration,l=this.hls.levels[r.level],d=(l.loaded?l.loaded.bytes:0)+a.loaded,u=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:d,duration:u},l.realBitrate=Math.round(8*d/u)}if(r.bitrateTest){let o={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(y.FRAG_BUFFERED,o),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,t){let{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;let o=((s.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(),s.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==te.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:s}=e,r=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(r,s,t,n/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,d=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(l,s),t,d);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=s&&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:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){let g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){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`),u=c=1)}let f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=s.levels[a],p=s.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e==null?void 0:e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,r,n,a,o){let{hls:l,lastLoadedFragLevel:d,fragCurrent:u,partCurrent:c}=this;if(!l)return-1;let h=r+n,f=d===-1?l.firstLevel:d,{levels:m,allAudioTracks:p,loadLevel:g,latestLevelDetails:v,config:E}=l;if(m.length===1)return 0;let b=m[f],T=!!(v!=null&&v.live),_=g===-1||d===-1,I,S="SDR",x=(b==null?void 0:b.frameRate)||0,{audioPreference:k,videoPreference:R}=E,D=this.audioTracksByGroup||(this.audioTracksByGroup=DT(p)),w=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;let F=this.codecTiers||(this.codecTiers=xD(m,D,t,s)),B=LD(F,S,e,k,R),{codecSet:W,videoRanges:Z,minFramerate:K,minBitrate:q,minIndex:ce,preferHDR:re}=B;w=ce,I=W,S=re?Z[Z.length-1]:Z[0],x=K,e=Math.max(e,q),this.log(`picked start tier ${rt(B)}`)}else I=b==null?void 0:b.codecSet,S=b==null?void 0:b.videoRange;let N=c?c.duration:u?u.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let F=s;F>=t;F--){var O;let B=m[F],W=F>f;if(!B)continue;if(E.useMediaCapabilities&&!B.supportedResult&&!B.supportedPromise){let ue=navigator.mediaCapabilities;typeof(ue==null?void 0:ue.decodingInfo)=="function"&&ED(B,D,S,x,e,k)?(B.supportedPromise=LT(B,D,ue,this.supportedCache),B.supportedPromise.then(Ce=>{if(!this.hls)return;B.supportedResult=Ce;let Te=this.hls.levels,Ne=Te.indexOf(B);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${Ne} ${rt(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(mt=>mt.smooth===!1||mt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ne} not smooth or powerEfficient: ${rt(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ne} ${rt(Ce)}`),Ne>-1&&Te.length>1&&(this.log(`Removing unsupported level ${Ne}`),this.hls.removeLevel(Ne),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):B.supportedResult=IT}if((I&&B.codecSet!==I||S&&B.videoRange!==S||W&&x>B.frameRate||!W&&x>0&&x<B.frameRate||(O=B.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(ue=>ue.smooth===!1))&&(!_||F!==w)){H.push(F);continue}let Z=B.details,K=(c?Z==null?void 0:Z.partTarget:Z==null?void 0:Z.averagetargetduration)||N||1,q;W?q=o*e:q=a*e;let ce=N&&r>=N*2&&n===0?B.averageBitrate:B.maxBitrate,re=this.getTimeToLoadFrag($,q,ce*K,!Z||Z.live);if(q>=ce&&(F===d||B.loadError===0&&B.fragmentError===0||rT(B,E.errorPenaltyExpireMs))&&(re<=$||!Q(re)||T&&!this.bitrateTestDelay||re<h)){let ue=this.forcedAutoLevel;return F!==g&&(ue===-1||ue!==g)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[H[0]].codecs}" ${m[H[0]].videoRange}; not compatible with "${I}" ${S}`),this.info(`switch candidate:${f}->${F} adjustedbw(${Math.round(q)})-bitrate=${Math.round(q-ce)} ttfb:${$.toFixed(1)} avgDuration:${K.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${re.toFixed(1)} firstSelection:${_} codecSet:${B.codecSet} videoRange:${B.videoRange} hls.loadLevel:${g}`)),_&&(this.firstSelection=F),F}}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:s}=this.hls;return Math.min(Math.max(e,s),t)}},wT={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];let a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function wD(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!Q(e))return null;let s=i[0].programDateTime;if(e<(s||0))return null;let r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){let a=i[n];if(PD(e,t,a))return a}return null}function Ea(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;let o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&qy(t,s,n)===0||MD(n,i,Math.min(r,s))))return n;let a=wT.search(e,qy.bind(null,t,s));return a&&(a!==i||!n)?a:n}function MD(i,e,t){if((e==null?void 0:e.start)===0&&e.level<i.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function qy(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function PD(i,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function MT(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments,{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return wT.search(s,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 PT(i,e){return e===i.endSN&&i.fragmentHint?i.fragmentHint:i.fragments[1+e-i.startSN]||null}var Gt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ht={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},_p=class extends si{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)===te.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.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 s;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case P.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Zo();return}case P.FRAG_GAP:case P.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Gt.SendAlternateToPenaltyBox;return}case P.PLAYLIST_UNCHANGED_ERROR:case P.LEVEL_EMPTY_ERROR:case P.LEVEL_PARSING_ERROR:{var a;let o=t.parent===te.MAIN?t.level:r.loadLevel;t.details===P.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 P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_LOAD_ERROR:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let o=r.loadLevelObj;if(o&&(n.type===Re.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===Re.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Gt.SendAlternateToPenaltyBox,t.errorAction.flags=Ht.MoveAllAlternatesMatchingHost;return}}return;case P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingHDCP};return;case P.KEY_SYSTEM_SESSION_UPDATE_FAILED:case P.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case P.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingKey};return;case P.BUFFER_ADD_CODEC_ERROR:case P.REMUX_ALLOC_ERROR:case P.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case P.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Ht.ResetMediaSource|Ht.SwitchToSDR;return;case P.INTERNAL_EXCEPTION:case P.BUFFER_APPENDING_ERROR:case P.BUFFER_APPEND_NO_PROGRESS:case P.BUFFER_FULL_ERROR:case P.LEVEL_SWITCH_ERROR:case P.BUFFER_STALLED_ERROR:case P.BUFFER_SEEK_OVER_HOLE:case P.BUFFER_NUDGE_ON_STALL:t.errorAction=Zo();return}t.type===ne.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Zo())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,r=wy(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(sl(r,n,Du(e),e.response))return{action:Gt.RetryRequest,flags:Ht.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,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=wy(iT(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==P.FRAG_GAP&&r.fragmentError++,!sT(e)&&sl(o,l,Du(e),e.response)))return{action:Gt.RetryRequest,flags:Ht.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,r.loadErrorTime=self.performance.now(),d===P.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===te.AUDIO&&d===P.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Yy(e))&&c.some(({audioCodec:I})=>r.audioCodec!==I),b=e.sourceBufferName==="video"&&Yy(e)&&c.some(({codecSet:I,audioCodec:S})=>r.codecSet!==I&&r.audioCodec===S),{type:T,groupId:_}=(a=e.context)!=null?a:{};for(let I=c.length;I--;){let S=(I+h)%c.length;if(S!==h&&S>=f&&S<=m&&(c[S].loadError===0||rT(c[S],s.config.errorPenaltyExpireMs))){var o,l;let x=c[S];if(d===P.FRAG_GAP&&p===te.MAIN&&e.frag){let k=c[S].details;if(k){let R=Ea(e.frag,k.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(T===Re.AUDIO_TRACK&&x.hasAudioGroup(_)||T===Re.SUBTITLE_TRACK&&x.hasSubtitleGroup(_))continue;if(p===te.AUDIO&&(o=r.audioGroups)!=null&&o.some(k=>x.hasAudioGroup(k))||p===te.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(k=>x.hasSubtitleGroup(k))||v&&r.audioCodec===x.audioCodec||b&&r.codecSet===x.codecSet||!v&&r.audioCodec!==x.audioCodec)continue}u=S;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Gt.SendAlternateToPenaltyBox,flags:Ht.None,nextAutoLevel:u}}return{action:Gt.SendAlternateToPenaltyBox,flags:Ht.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,r;switch((s=t.errorAction)==null?void 0:s.action){case Gt.DoNothing:break;case Gt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==P.FRAG_GAP&&t.details!==P.PLAYLIST_UNCHANGED_ERROR&&!OT(t)&&(t.fatal=!0);break;case Gt.RetryRequest:break}if((((r=t.errorAction)==null?void 0:r.flags)||0)&Ht.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let r=s.nextAutoLevel;if(s.flags===Ht.None)this.switchLevel(e,r);else if(s.flags&Ht.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let d=l;d--;)o[d].videoRange!=="SDR"?(o[d].fragmentError++,o[d].loadError++):r===void 0&&(r=d)}else if(s.flags&Ht.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l==null?void 0:l.attrs["HDCP-LEVEL"];s.hdcpLevel=d;let u=d==="NONE";d&&!u?(t.maxHdcpLevel=bp[bp.indexOf(d)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=Ht.MoveAllAlternatesMatchingKey)}if(s.flags&Ht.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,d=l.length;for(let c=d;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) ${Ct(o.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${e.error})`),this.hls.removeLevel(c)}let u=e.frag;if(this.hls.levels.length<d)s.resolved=!0;else if(u&&u.type!==te.MAIN){let c=u.decryptdata;c&&!o.matches(c)&&(s.resolved=!0)}}}s.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===P.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=yp(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}};function Yy(i){let e=i.details;return e===P.BUFFER_ADD_CODEC_ERROR||e===P.MEDIA_SOURCE_REQUIRES_RESET||e===P.BUFFER_APPEND_ERROR&&!OT(i)}function OT(i){return i.details===P.BUFFER_APPEND_ERROR&&(i.error.name==="QuotaExceededError"||i.error.name==="InvalidStateError")}function Zo(i){let e={action:Gt.DoNothing,flags:Ht.None};return i&&(e.resolved=!0),e}var ft={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ap=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 s=this.activePartLists[t];if(s)for(let r=s.length;r--;){let n=s[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,s){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&&(!s||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,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 d=this.fragments[l];if(!d||!this.hls)return;let u=d.body;if(o>=u.sn)return;if(!d.buffered&&(!d.loaded||a)){u.type===s&&this.removeFragment(u);return}let c=d.range[e];if(c){if(c.time.length===0){this.removeFragment(u);return}if(c.time.some(h=>{let f=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return f&&this.removeFragment(u),f}),r&&r!==u&&Xo()){let h=r.endPTS,f=u.startPTS;if(h&&f&&d.range.video){let m=f-h;m<0&&m>-.1&&(this.removeFragment(u),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:h+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:s,part:r,id:n}=e;if(!t||!Et(s))return;let a=da(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;let l=!s.relurl;Object.keys(t).forEach(u=>{let c=s.elementaryStreams[u];if(!c)return;let h=t[u],f=l||c.partial===!0;o.range[u]=this.getBufferedTimes(s,r,f,h),this.detectEvictedFragments(u,h,n,s,r)}),o.loaded=null;let d=Object.keys(o.range);if(d.length){if(this.bufferedEnd(o,s),hu(o)||this.removeParts(s.sn-1,s.type),!r){let u=Math.min(.004,s.duration);d.some(c=>{var h;let f=(h=o.range[c])==null?void 0:h.time,m=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<u;return m&&this.addAsGap(s),m})}}else this.removeFragment(s)}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 s=this.activePartLists[t];s&&(this.activePartLists[t]=jy(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){let s=da(e),r=this.fragments[s];return!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,s,r){let n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){let c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let u=l[d];u&&hu(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||hu(t))}getState(e){let t=da(e),s=this.fragments[t];return s?s.buffered?hu(s)?ft.PARTIAL:ft.OK:ft.APPENDING:ft.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Et(t.frag)||t.frag.bitrateTest)return;let s=t.frag,r=t.part?null:t,n=da(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:r,timeRanges:n}=t;if(!Et(s))return;let a=s.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=da(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){let n=t[s[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,s){let{fragments:r}=this,n=0,a=0,o=Object.keys(r);for(let l=0;l<o.length;l++){let d=r[o[l]];if(!d||!d.buffered||d.body.type!==t)continue;let u=d.body;if(u.gap)return 0;let c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&u.bitrate*8*u.duration;if(u.end<=e&&c&&(n+=c,a=Math.max(a,u.end),n>=s))return a}return a>0?a:0}removeFragmentsInRange(e,t,s,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!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=da(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let r=e.sn;this.activePartLists[e.type]=jy(s,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(s=>s.clearElementaryStreamInfo())}};function hu(i){var e,t,s,r;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial||(r=i.range.subs)!=null&&r.partial)}function da(i){return`${i.type}_${i.level}_${i.sn}`}function jy(i,e){return i.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Rr={cbc:0,ctr:1},Sp=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Rr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Rr.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 OD(i){let e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}var Ip=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),s=new Uint32Array(4);for(let r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=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 E=f[m],b=f[E],T=f[b],_=f[v]*257^v*16843008;r[m]=_<<24|_>>>8,n[m]=_<<16|_>>>16,a[m]=_<<8|_>>>24,o[m]=_,_=T*16843009^b*65537^E*257^m*16843008,d[v]=_<<24|_>>>8,u[v]=_<<16|_>>>16,c[v]=_<<8|_>>>24,h[v]=_,m?(m=E^f[f[f[T^E]]],p^=f[f[p]]):m=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)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,d=this.keySchedule=new Uint32Array(a),u=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],E,b;for(o=0;o<a;o++){if(o<n){E=d[o]=t[o];continue}b=E,o%n===0?(b=b<<8|b>>>24,b=c[b>>>24]<<24|c[b>>>16&255]<<16|c[b>>>8&255]<<8|c[b&255],b^=h[o/n|0]<<24):n>6&&o%n===4&&(b=c[b>>>24]<<24|c[b>>>16&255]<<16|c[b>>>8&255]<<8|c[b&255]),d[o]=E=(d[o-n]^b)>>>0}for(l=0;l<a;l++)o=a-l,l&3?b=d[o]:b=d[o-4],l<4||o<=4?u[l]=b:u[l]=m[c[b>>>24]]^p[c[b>>>16&255]]^g[c[b>>>8&255]]^v[c[b&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s),f=h[0],m=h[1],p=h[2],g=h[3],v=new Int32Array(e),E=new Int32Array(v.length),b,T,_,I,S,x,k,R,D,w,N,$,H,O,F=this.networkToHostOrderSwap;for(;t<v.length;){for(D=F(v[t]),w=F(v[t+1]),N=F(v[t+2]),$=F(v[t+3]),S=D^n[0],x=$^n[1],k=N^n[2],R=w^n[3],H=4,O=1;O<r;O++)b=l[S>>>24]^d[x>>16&255]^u[k>>8&255]^c[R&255]^n[H],T=l[x>>>24]^d[k>>16&255]^u[R>>8&255]^c[S&255]^n[H+1],_=l[k>>>24]^d[R>>16&255]^u[S>>8&255]^c[x&255]^n[H+2],I=l[R>>>24]^d[S>>16&255]^u[x>>8&255]^c[k&255]^n[H+3],S=b,x=T,k=_,R=I,H=H+4;b=a[S>>>24]<<24^a[x>>16&255]<<16^a[k>>8&255]<<8^a[R&255]^n[H],T=a[x>>>24]<<24^a[k>>16&255]<<16^a[R>>8&255]<<8^a[S&255]^n[H+1],_=a[k>>>24]<<24^a[R>>16&255]<<16^a[S>>8&255]<<8^a[x&255]^n[H+2],I=a[R>>>24]<<24^a[S>>16&255]<<16^a[x>>8&255]<<8^a[k&255]^n[H+3],E[t]=F(b^f),E[t+1]=F(I^m),E[t+2]=F(_^p),E[t+3]=F(T^g),f=D,m=w,p=N,g=$,t=t+4}return E.buffer}},Rp=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=ND(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function ND(i){switch(i){case Rr.cbc:return"AES-CBC";case Rr.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}var UD=16,ul=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 s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?r.start===0&&r.end>=s.length?s:s.slice(r.start,r.end):OD(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,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,s,r);let d=this.flush();d?a(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Rr.cbc||t.byteLength!==16)return $e.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ci(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Ip),d.expandKey(t);let u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new Rp(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Sp(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>($e.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,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,s=e.length-e.length%UD;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&($e.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},zy=Math.pow(2,17),Nu=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,s,r){let n=e.url;if(!n)return Promise.reject(new Di({type:ne.NETWORK_ERROR,details:P.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((d,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){u(Xy(e));return}else e.gap=!1;let c=this.loader=o?new o(a):new l(a),h=Qy(e,null,t);e.loader=c;let f=My(a.fragLoadPolicy.default),m={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zy};c.stats.retry=e.stats.retry,e.stats=c.stats;let p={onSuccess:(g,v,E,b)=>{this.resetLoader(e,c);let T=g.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),d({frag:e,part:null,payload:T,networkDetails:b})},onError:(g,v,E,b)=>{this.resetLoader(e,c),u(new Di({type:ne.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ae({url:n,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:E,stats:b}))},onAbort:(g,v,E)=>{this.resetLoader(e,c),u(new Di({type:ne.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:g}))},onTimeout:(g,v,E)=>{this.resetLoader(e,c),u(new Di({type:ne.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:E,stats:g}))}};if(s){let g=this.gateProgress(s,r);p.onProgress=(v,E,b,T)=>g({frag:e,part:null,payload:b,networkDetails:T})}c.load(h,m,p)})}gateProgress(e,t){let s=e;if(t){let r=[],n=!1;t.then(()=>{n=!0,r.forEach(a=>e(a)),r.length=0}).catch(()=>{}),s=a=>{n?e(a):r.push(a)}}return s}loadPart(e,t,s){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(Xy(e,t));return}let d=this.loader=n?new n(r):new a(r),u=Qy(e,t);e.loader=d;let c=My(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zy};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new Di({type:ne.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ae({url:u.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,d),l(new Di({type:ne.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Di({type:ne.NETWORK_ERROR,details:P.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 s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);let a=s.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 Qy(i,e=null,t){let s=e||i,r={type:Re.MEDIA_FRAGMENT,frag:i,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=Uu(i,e,t);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function Uu(i,e=null,t){let s={},r=e||i,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(Q(n)&&Q(a)){var o;if((i.sn==="initSegment"||t)&&FD((o=i.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16,d=Math.ceil(a/16)*16;s.decryptRange={start:n-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:d}}else s.byteRange={start:n,end:a}}return s}function Xy(i,e){let t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:ne.MEDIA_ERROR,details:P.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new Di(s)}function FD(i){return i==="AES-128"||i==="AES-256"}var Di=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Fu=class extends si{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(){}},cl=class{constructor(e,t,s,r=0,n=-1,a=!1,o,l,d){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=fu(),this.buffering={audio:fu(),video:fu(),audiovideo:fu()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=d,this.iframe=l||!1}};function fu(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Zy={length:0,start:()=>0,end:()=>0},be=class i{static isBuffered(e,t){if(e){let s=i.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=i.getBuffered(e);return i.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let r=i.bufferedRanges(e);if(r.length)return i.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);let c=n.length;if(c){let h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){let c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Zy}catch(t){return $e.log("failed to get media.buffered",t),Zy}}},Lp=/\{\$([a-zA-Z0-9-_]+)\}/g;function Jy(i){return Lp.lastIndex=0,Lp.test(i)}function Kg(i,e){if(i.variableList!==null||i.hasVariableRefs){let t=i.variableList;return e.replace(Lp,s=>{let r=s.substring(2,s.length-1),n=t==null?void 0:t[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function eb(i,e,t){let s=i.variableList;s||(i.variableList=s={});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){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function BD(i,e,t){let s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var $D=/^(\d+)x(\d+)$/,tb=/(.+?)=(".*?"|.*?)(?:,|$)/g,ht=class i{constructor(e,t){typeof e=="string"&&(e=i.parseAttrList(e,t)),Qe(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 s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=$D.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,r={},n='"';for(tb.lastIndex=0;(s=tb.exec(e))!==null;){let a=s[1].trim(),o=s[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Kg(t,o);else if(!d&&!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":$e.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},HD="com.apple.hls.interstitial";function GD(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function KD(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}var Bu=class{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:s,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){$e.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Qe(new ht({}),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"]);Q(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?($e.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(Q(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===HD}get isValid(){return!!this.id&&!this._badValueForSameId&&Q(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`:Q(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"}},NT=10,xp=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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||NT}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 $u(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function ib(i,e){return!i&&!e?!0:!i||!e?!1:$u(i,e)}function pa(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Vg(i){switch(i){case"AES-128":case"AES-256":return Rr.cbc;case"AES-256-CTR":return Rr.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function kp(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function VD(i){let e=kp(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function UT(i){let e=function(s,r,n){let a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function FT(i){let e=i.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=$g(a)):t=VD(a)}}return t}var Hu=typeof self!="undefined"?self:void 0,dt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},jt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function mu(i){switch(i){case jt.FAIRPLAY:return dt.FAIRPLAY;case jt.PLAYREADY:return dt.PLAYREADY;case jt.WIDEVINE:return dt.WIDEVINE;case jt.CLEARKEY:return dt.CLEARKEY}}var BT={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ym(i){switch(i){case dt.FAIRPLAY:return jt.FAIRPLAY;case dt.PLAYREADY:return jt.PLAYREADY;case dt.WIDEVINE:return jt.WIDEVINE;case dt.CLEARKEY:return jt.CLEARKEY}}function Wo(i){let{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[dt.FAIRPLAY,dt.WIDEVINE,dt.PLAYREADY,dt.CLEARKEY].filter(r=>!!e[r]):[];return!s[dt.WIDEVINE]&&t&&s.push(dt.WIDEVINE),s}var $T=function(i){return Hu!=null&&(i=Hu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function WD(i,e,t,s){let r;switch(i){case dt.FAIRPLAY:r=["cenc","sinf"];break;case dt.WIDEVINE:case dt.PLAYREADY:r=["cenc"];break;case dt.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return qD(r,e,t,s)}function qD(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function YD(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Wg(i){let e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=ji(e),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=$g(o).subarray(0,16);return UT(l),l}}return null}var ua={},_n=class i{static clearKeyUriToKeyIdMap(){ua={}}static setKeyIdForUri(e,t){ua[e]=t}static addKeyIdForUri(e){let t=Object.keys(ua).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),ua[e]=s,s}constructor(e,t,s,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=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!pa(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(cT(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$u(e.keyFormatVersions,this.keyFormatVersions)&&ib(e.iv,this.iv)&&ib(e.keyId,this.keyId)}isSupported(){if(this.method){if(pa(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case jt.FAIRPLAY:case jt.WIDEVINE:case jt.PLAYREADY:case jt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var s;if(!this.encrypted||!this.uri)return null;if(pa(this.method)){let a=this.iv;return a||(typeof e!="number"&&($e.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=zD(e)),new i(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=ua[this.uri];if(a&&!$u(this.keyId,a)&&i.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=FT(this.uri);if(r)switch(this.keyFormat){case jt.WIDEVINE:if(this.pssh=r,!this.keyId){let a=_T(r.buffer).filter(o=>o.systemId===BT.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=sb(t));break;case jt.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=sD(a,null,r),this.keyId=Wg(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(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=jD(t),a||(a=sb(t),a||(a=ua[this.uri])),a&&(this.keyId=a,i.setKeyIdForUri(this.uri,a))}return this}};function jD(i){let e=i==null?void 0:i[jt.WIDEVINE];return e?e.keyId:null}function sb(i){let e=i==null?void 0:i[jt.PLAYREADY];if(e){let t=FT(e.uri);if(t)return Wg(t)}return null}function zD(i){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}var rb=/#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,nb=/#EXT-X-MEDIA:(.*)/g,QD=/^#EXT(?:INF|-X-TARGETDURATION):/m,jm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),XD=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("|")),_r=class i{static findGroup(e,t){for(let s=0;s<e.length;s++){let r=e[s];if(r.id===t)return r}}static resolve(e,t){return Ng.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return QD.test(e)}static parseMasterPlaylist(e,t){let s=Jy(e),r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(rb.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=rb.exec(e))!=null;)if(a[1]){let l=new ht(a[1],r),d=ab(l,a[2],t,r,n);d&&r.levels.push(d)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"I-FRAME-STREAM-INF":{let u=new ht(d,r),c=ab(u,u.URI,t,r,n,!0);c&&r.iframeVariants.push(c)}break;case"SESSION-DATA":{let u=new ht(d,r),c=u["DATA-ID"];c&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[c]=u);break}case"SESSION-KEY":{let u=ob(d,t,r);u.encrypted&&u.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(u)):$e.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let u=new ht(d,r);eb(r,u,t)}break}case"CONTENT-STEERING":{let u=new ht(d,r);r.contentSteering={uri:i.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=lb(d);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,s){let r,n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(nb.lastIndex=0;(r=nb.exec(e))!==null;){let d=new ht(r[1],s),u=d.TYPE;if(u){let c=o[u],h=n[u]||[];n[u]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],E={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?i.resolve(d.URI,t):""};if(m&&(E.assocLang=m),p&&(E.channels=p),g&&(E.characteristics=g),v&&(E.instreamId=v),c!=null&&c.length){let b=i.findGroup(c,E.groupId)||c[0];ub(E,b,"audioCodec"),ub(E,b,"textCodec")}h.push(E)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;let l={url:t},d=new xp(t),u=d.fragments,c=[],h=null,f=0,m=0,p=0,g=0,v=0,E=null,b=new fa(r,l),T,_,I,S=-1,x=!1,k=null,R;if(jm.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Jy(e),((o=jm.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(T=jm.exec(e))!==null;){x&&(x=!1,b=new fa(r,l),b.playlistOffset=p,b.setStart(p),b.sn=f,b.cc=g,v&&(b.bitrate=v),b.level=s,h&&(b.initSegment=h,h.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),k&&(b.setByteRange(k),k=null)));let H=T[1];if(H){b.duration=parseFloat(H);let O=(" "+T[2]).slice(1);b.title=O||null,b.tagList.push(O?["INF",H,O]:["INF",H])}else if(T[3]){if(Q(b.duration)){var D;b.playlistOffset=p,b.setStart(p),I&&hb(b,I,d),b.sn=f,b.level=s,b.cc=g;let O=(" "+T[3]).slice(1);b.relurl=Kg(d,O),Dp(b,E,c),E=b,p+=b.duration,f++,m=0;let F=b.byteRange;if(F.length===2&&(b.bitrate=(F[1]-F[0])*8/b.duration|0),d.iframesOnly&&F[0]&&((D=h)==null?void 0:D.cc)!==g){let B=new fa(r,l);B.relurl=b.relurl,B.setByteRange(`${Math.min(F[0],7*188)}@0`),B.level=s,B.sn="initSegment",I&&(B.levelkeys=I,I.identity&&(B._decryptdata=I.identity.getDecryptData(0))),h=B,b.initSegment=h}u.push(b),x=!0}}else{if(T=T[0].match(XD),!T){$e.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<T.length&&T[_]===void 0;_++);let O=(" "+T[_]).slice(1),F=(" "+T[_+1]).slice(1),B=T[_+2]?(" "+T[_+2]).slice(1):null;switch(O){case"BYTERANGE":E?b.setByteRange(F,E):b.setByteRange(F);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=F,b.tagList.push(["PROGRAM-DATE-TIME",F]),S===-1&&(S=u.length);break;case"PLAYLIST-TYPE":d.type&&Ws(d,O,T),d.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Ws(d,O,T):E!==null&&eC(d,O,T),d.startSN=parseInt(F),f=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&Ws(d,O,T);let W=new ht(F,d),Z=W.decimalInteger("SKIPPED-SEGMENTS");if(Q(Z)){d.skippedSegments+=Z;for(let q=Z;q--;)u.push(null);f+=Z}let K=W.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(K.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Ws(d,O,T),d.targetduration=Math.max(parseInt(F),1);break;case"VERSION":d.version!==null&&Ws(d,O,T),d.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||Ws(d,O,T),d.live=!1;break;case"#":(F||B)&&b.tagList.push(B?[F,B]:[F]);break;case"DISCONTINUITY":g++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([O]);break;case"BITRATE":b.tagList.push([O,F]),v=parseInt(F)*1e3,Q(v)?b.bitrate=v:v=0;break;case"DATERANGE":{let W=new ht(F,d),Z=new Bu(W,d.dateRanges[W.ID],d.dateRangeTagCount);d.dateRangeTagCount++,Z.isValid||d.skippedSegments?d.dateRanges[Z.id]=Z:$e.log(`Ignoring invalid DATERANGE tag: ${Z.invalidReason}: ${F}`),b.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{let W=new ht(F,d);"IMPORT"in W?BD(d,W,a):eb(d,W,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0&&Ws(d,O,T),d.startCC=g=parseInt(F),u.forEach(W=>W&&(W.cc=g));break;case"KEY":{let W=ob(F,t,d);if(W.isSupported()){if(W.method==="NONE"){I=void 0;break}I||(I={});let Z=I[W.keyFormat];Z!=null&&Z.matches(W)||(Z&&(I=Qe({},I)),I[W.keyFormat]=W)}else $e.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":d.startTimeOffset=lb(F);break;case"MAP":{let W=new ht(F,d);if(b.duration){let Z=new fa(r,l);cb(Z,W,s,I),h=Z,b.initSegment=h,h.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime)}else{let Z=b.byteRangeEndOffset;if(Z){let K=b.byteRangeStartOffset;k=`${Z-K}@${K}`}else k=null;cb(b,W,s,I),h=b,x=!0}h.cc=g;break}case"SERVER-CONTROL":{R&&Ws(d,O,T),R=new ht(F),d.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),d.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Ws(d,O,T);let W=new ht(F);d.partTarget=W.decimalFloatingPoint("PART-TARGET");break}case"PART":{let W=d.partList;W||(W=d.partList=[]);let Z=m>0?W[W.length-1]:void 0,K=m++,q=new ht(F,d),ce=new fp(q,b,l,K,Z);W.push(ce),b.duration+=ce.duration;break}case"PRELOAD-HINT":{let W=new ht(F,d);d.preloadHint=W;break}case"RENDITION-REPORT":{let W=new ht(F,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(W);break}default:$e.warn(`line parsed but not handled: ${T}`);break}}}E&&!E.relurl?(u.pop(),p-=E.duration,d.partList&&(d.fragmentHint=E)):d.partList&&(Dp(b,E,c),b.cc=g,d.fragmentHint=b,I&&hb(b,I,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let w=u.length,N=u[0],$=u[w-1];if(p+=d.skippedSegments*d.targetduration,p>0&&w&&$){d.averagetargetduration=p/w;let H=$.sn;d.endSN=H!=="initSegment"?H:0,d.live||($.endList=!0),S>0&&(JD(u,S,S>w-1?b:null),N&&c.unshift(N))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&N&&HT(c,d),d.endCC=g,d}};function ab(i,e,t,s,r,n){var a;if(e===void 0)return null;let o=Kg(s,e),l={attrs:i,bitrate:i.decimalInteger("BANDWIDTH")||i.decimalInteger("AVERAGE-BANDWIDTH"),name:i.NAME,url:_r.resolve(o,t)},d=i.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),db(i.CODECS,l);let u=i["SUPPLEMENTAL-CODECS"];return u&&(l.supplemental={},db(u,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||r.push(l),n&&(l.iframes=!0),l}function HT(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;let s=i[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]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;let c=ZD(e,d,i,u,r);if(c){l.tagAnchor=c.ref;break}}}}function ZD(i,e,t,s,r){let n=t[s];if(n){let o=n.programDateTime;if(e>=o||s===0){var a;let l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=n.sn-i.startSN,u=i.fragments;if(d>=0&&d<u.length){if(u.length>t.length){let c=t[s+1]||u[u.length-1],h=Math.min(c.sn-i.startSN,u.length-1);for(let f=h;f>d;f--){let m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return u[f]}}return u[d]}}}}return null}function ob(i,e,t){var s,r;let n=new ht(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&$e.error(`Invalid IV: ${n.IV}`);let c=o?_r.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new _n(a,c,u,h,l,n.KEYID)}function lb(i){let t=new ht(i).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function db(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{let r=t.filter(n=>Hg(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function ub(i,e,t){let s=e[t];s&&(i[t]=s)}function JD(i,e,t){if(t||(t=i[e]),!!t)for(let s=e;s--;){let r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Dp(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function cb(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function hb(i,e,t){i.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function Ws(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function eC(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function zm(i,e){let t=e.startPTS;if(Q(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function GT(i,e,t,s,r,n,a,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let d=t,u=s,c=e.startPTS,h=e.endPTS;if(Q(c)){let E=Math.abs(c-t);i&&E>i.totalduration?o.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${i.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,d=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,u=Math.min(s,h),s=Math.max(s,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(s-e.start),e.startPTS=t,e.maxStartPTS=d,e.startDTS=r,e.endPTS=s,e.minEndPTS=u,e.endDTS=n;let m=e.sn;if(!i||m<i.startSN||m>i.endSN)return 0;let p,g=m-i.startSN,v=i.fragments;for(v[g]=e,p=g;p>0;p--)zm(v[p],v[p-1]);for(p=g;p<v.length-1;p++)zm(v[p],v[p+1]);return i.fragmentHint&&zm(v[v.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,f}function tC(i,e,t){if(i===e)return;let s=null,r=i.fragments;for(let u=r.length-1;u>=0;u--){let c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;rC(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){let m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}Q(u.startPTS)&&Q(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=iC(i.dateRanges,e,t));let u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Dp(o[c],o[c-1],u);HT(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let u=WT(i,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}if(sC(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats,c.gap=u.gap||c.gap}),n){let u=e.iframesOnly&&n.type===te.MAIN;GT(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,u,t)}else KT(i,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function iC(i,e,t){let{dateRanges:s,recentlyRemovedDateranges:r}=e,n=Qe({},i);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{let d=n[l],u=new Bu(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${rt(s[l].attr)}"`)}),n):s}function sC(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<n;r++){let a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function rC(i,e,t){var s;let r=e.skippedSegments,n=Math.max(i.startSN,e.startSN)-e.startSN,a=(i.fragmentHint?1:0)+(r?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,o=e.startSN-i.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=(s=i.fragmentHint)!=null&&s.duration?i.fragments.concat(i.fragmentHint):i.fragments;for(let u=n;u<=a;u++){let c=d[o+u],h=l[u];if(r&&!h&&c&&(h=e.fragments[u]=c),c&&h){t(c,h,u,l);let f=c.relurl,m=h.relurl;if(f&&aC(f,m)){e.playlistParsingError=fb(`media sequence mismatch ${h.sn}:`,i,e,c,h);return}else if(c.cc!==h.cc){e.playlistParsingError=fb(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,i,e,c,h);return}}}}function fb(i,e,t,s,r){return new Error(`${i} ${r.url}
|
|
27
27
|
Playlist starting @${e.startSN}
|
|
28
28
|
${e.m3u8}
|
|
29
29
|
|
|
30
30
|
Playlist starting @${t.startSN}
|
|
31
|
-
${t.m3u8}`)}function KT(i,e,t=!0,s){let r=e.startSN+e.skippedSegments-i.startSN,n=i.fragments,a=r>=0,o=0;if(a&&r<n.length)o=n[r].start,s==null||s.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===i.endSN+1)o=i.fragmentEnd,s==null||s.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=i.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=i.fragmentStart,s==null||s.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return nC(e,o),o}function nC(i,e){if(e){let t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function VT(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){let s=i.fragments;if(s.length&&t*4>e){let n=s[s.length-1].duration*1e3;n>0&&n<t&&(t=n)}}else t/=2;return Math.round(t)}function WT(i,e,t){var s;if(!i)return null;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,((s=r)==null?void 0:s.sn)===e)?r:t&&e<i.startSN&&t.sn===e?t:null}function mb(i,e,t){return i?qT(i.partList,e,t):null}function qT(i,e,t){if(i)for(let s=i.length;s--;){let r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function YT(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function aC(i,e){return i!==e&&e?pb(i)!==pb(e):!1}function pb(i){return i.replace(/\?[^?]*$/,"")}function Jo(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function oC(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function gb(i,e){let t=i.start+e;i.setStart(t)}function jT(i,e){let t=e.fragments;for(let s=0,r=t.length;s<r;s++)gb(t[s],i);e.fragmentHint&&gb(e.fragmentHint,i),e.alignedSliding=!0}function Gu(i,e,t){i&&(lC(e,i,t),e.alignedSliding||dC(e,i,t),!e.alignedSliding&&!e.skippedSegments&&KT(i,e,!1,t))}function lC(i,e,t){if(!oC(e,i))return;let s=Math.min(e.endCC,i.endCC),r=Jo(e.fragments,s),n=Jo(i.fragments,s);if(!r||!n)return;let a=r.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),jT(a,i)}function dC(i,e,t){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;let s=i.fragments,r=e.fragments;if(!s.length||!r.length)return;let n,a,o=Math.min(e.endCC,i.endCC);e.startCC<o&&i.startCC<o&&(n=Jo(r,o),a=Jo(s,o)),(!n||!a)&&(n=r[Math.floor(r.length/2)]||r.filter(h=>!!h)[0],a=Jo(s,n.cc)||s[Math.floor(s.length/2)]);let l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;let u=(d-l)/1e3;if(Math.abs(u)>Math.max(60,i.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${i.totalduration})`);return}let c=u-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${c})`),jT(c,i)}function Ye(i,e,t){We(i,e,t),i.addEventListener(e,t)}function We(i,e,t){i.removeEventListener(e,t)}function Ku(i){let e="",t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}var U={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"},hl=class extends Fu{constructor(e,t,s,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=U.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:d,state:u}=this,c=l?l.currentTime:0,h=be.bufferInfo(d||l,c,a.maxBufferHole),f=h.len;if(this.log(`Media seeking to ${c}, state: ${u}, ${f?"in":"out of"} buffer`),this.state===U.ENDED)this.resetLoadingState();else if(o){let p=a.maxFragLookUpTolerance,g=o.start-p,v=o.start+o.duration+p;if(!f||v<h.start||g>h.end){let b=c<g,E=c>v;(b||E)&&(o.loader&&(E||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${b?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let p=this.lastCurrentTime;if(c>p&&(this.lastCurrentTime=c),!this.loadingParts){let g=Math.max(h.end,c),v=this.shouldLoadParts(this.getLevelDetails(),g);v&&(this.log(`LL-Part loading ON after seeking to ${c} with buffer @${g}`),this.loadingParts=v)}}let m=!be.isBuffered(l,c);(!this.hls.hasEnoughToStart||m)&&(this.log(`Setting ${m?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,m&&(this.startPosition=c)),f<1&&this.state===U.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 Nu(e.config),this.initFragmentLoader=new Nu(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ul(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===U.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=U.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.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 s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=be.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 u=l[l.length-1];return be.isBuffered(this.media,u.start+u.duration/2)}let d=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(d.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 s=this.media=this.mediaBuffer=t.media;Ye(s,"seeking",this.onMediaSeeking),Ye(s,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===U.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let s=!!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),We(r,"seeking",this.onMediaSeeking),We(r,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){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=U.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,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){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,s,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===U.FRAG_LOADING||!this.fragCurrent&&a===U.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=U.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(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===U.STOPPED||this.state===U.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:s}=this;if(s.getState(e)===ft.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))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ft.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){let r=t.getPartialFragment(s.end);r&&(t.removeFragment(r),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.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,s=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:s};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(s=>{var r;let n=s.frag;if(!this.levels||!hp(n,(r=this.fragCurrent)==null?void 0:r.initSegment))throw new Di({type:re.NETWORK_ERROR,details:P.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return s}).then(s=>{let{frag:r,payload:n}=s,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&pa(a.method)){let o=self.performance.now(),{decryptRange:l}=Uu(r,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Vg(a.method),l).catch(d=>{throw t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),this.fragmentLoader.abort(),d}).then(d=>{let u=self.performance.now();return t.trigger(y.FRAG_DECRYPTED,{frag:r,part:null,payload:d,stats:{tstart:o,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}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&&Et(e)&&t&&!t.data){var s;return(t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===U.STOPPED||this.state===U.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var s,r;let n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.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:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!hp(e,t)}fragBufferedComplete(e,t){let s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Ku(be.getBuffered(s)):"(detached)"})`),Et(e)){var r;if(e.type!==te.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=U.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==ft.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=U.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let s=e.frag,{part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(d=>!d),{decryptRange:o}=Uu(s,r),l=new cl(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${r?" part: "+r.index:""} of ${this.fragInfo(s,!1,r)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){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=U.KEY_LOADING,n=this.keyLoader.load(e,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(y.KEY_LOADED,a),this.state===U.KEY_LOADING&&(this.state=U.IDLE),a}),this.hls.trigger(y.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,s=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(!zo(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(s=Math.max(e.start,s||0),this.loadingParts){let f=n.partList;if(f&&r){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);let m=this.getNextPart(f,e,s);if(m>-1){let p=f[m];if(e=this.fragCurrent=p.fragment,!zo(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,p)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(p,t.details))return Promise.resolve(null);let g=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${m}/${f.length-1}) of ${this.fragInfo(e,!1,p)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${s}${p.byteRange.length?` range:${p.byteRange.join("-")}`:""}`),this.nextLoadPosition=p.start+p.duration,this.state=U.FRAG_LOADING;let v,b=this.loadInitSegmentIfNeeded(e);if(g||b){let E=!!g;v=Promise.all([g,b]).then(([T])=>E&&(!T||this.fragContextChanged(T.frag))?null:this.doFragPartsLoad(e,p,t,r)).catch(T=>this.handleFragLoadError(T))}else v=this.doFragPartsLoad(e,p,t,r).catch(E=>this.handleFragLoadError(E));return this.hls.trigger(y.FRAG_LOADING,{frag:e,part:p,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} 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),d=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var u;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),l==null||l.catch(()=>null),d==null||d.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: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=U.FRAG_LOADING;let c=this.config.progressive&&e.type!==te.SUBTITLE,h;return c&&d?h=d.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),d,l]).then(([f])=>(!c&&r&&r(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:s}),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,s,r){return new Promise((n,a)=>{var o;let l=[],d=(o=s.details)==null?void 0:o.partList,u=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=mb(s.details,e.sn,c.index+1)||qT(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===P.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===re.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==U.PARSING){!this.fragCurrent&&this.state!==U.STOPPED&&this.state!==U.ERROR&&(this.state=U.IDLE);return}let{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;let r=e.partList[0],n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n&&this.playhead>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=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,d=a>-1?mb(l,n,a):null,u=d?d.fragment:WT(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==U.PARSING)return;Et(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=Ci(a,o)),!l.length)return;let d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!be.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,r=be.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let r=this.playhead,a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){let n=be.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return be.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){let r=e.nextStart;if(r&&s.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<s.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t/2),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.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 s=t.fragments,r=s.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 d;l=this.getInitialLiveFragment(t);let h=this.config.startPosition,f=this.hls.startPosition,m=this.hls.liveSyncPosition,p=((d=l)==null?void 0:d.start)||0,g,v;if(f!==-1&&f>=a?(g=f,v=f===h?"config":"next load start"):m?(g=m,v="live edge"):(g=e,v="buffer pos"),g<p&&(g=p,v="live frag start"),g<a&&(g=a,v="playlist start"),this.startPosition!=g||this.nextLoadPosition!=g){let E=t.live&&!this.filterReplacedPrimary(l,t)?-1:g;this.log(`Setting startPosition to ${E} next load ${g} ${f===-1?"":`(from ${h}) `}based on ${v}. live edge: ${m} live frag start: ${p} playlist start: ${a} buffer pos: ${e}`),this.startPosition=E,this.nextLoadPosition=g}}}else e<=a&&(l=s[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);return!u&&l&&(u=PT(t,l.sn),u&&(this.nextLoadPosition=u.start)),u}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let s=this.fragmentTracker.getState(e);return!!(s===ft.OK||s===ft.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.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(Vu(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(Vu(this.config)&&("type"in e?e:e.fragment).type!==te.SUBTITLE){let s=this.hls.interstitialsManager,r=s==null?void 0:s.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(zT(e,s==null?void 0:s.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let l=0,d=e.length;l<d;l++){let u=e[l];if(a=a&&!u.independent,r>-1&&s<u.start)break;let c=u.loaded||u.gap;c?r=-1:(n||(u.independent||a)&&u.fragment===t)&&(r=l),n=c&&!u.gap}let o=e[r];return o&&o.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,r=null;if(s){if(e.hasProgramDateTime&&(r=wD(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!r){let n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=MT(e,s.cc,s.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,s){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=s,{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===ft.NOT_LOADED&&(n=null);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=Ea(n,a,e,p)}else h=a[a.length-1];if(h){let m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===ft.OK||p===ft.PARTIAL&&h.gap)&&(n=h),zo(h,n)&&(!c||u[0].fragment.sn>h.sn||!s.live)){let g=a[m+1];h.sn<o&&this.fragmentTracker.getState(g)!==ft.OK?h=g:h=null}}return h}alignPlaylists(e,t,s){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&&Q(n);if(a||!o&&!n){Gu(s,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 s=this.startPosition;s<t&&(s=-1);let r=this.timelineOffset;if(s===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&Q(a))s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){let o=this.hls.liveSyncPosition;s=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let s=(t=this.media)==null?void 0:t.currentTime;return Q(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==te.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&&Et(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!==U.FRAG_LOADING_WAITING_RETRY)&&(this.state=U.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let b=this.getCurrentContext(t.chunkMeta);b&&(t.frag=b.frag)}let{frag:s,part:r}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}let a=t.details===P.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);let o=t.errorAction;if(!o){this.state=U.ERROR;return}let{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===Gt.RetryRequest,m=h&&!o.resolved&&d&Ht.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,g=p==null?void 0:p.live;if(!f&&m&&Et(s)&&g&&s.sn<p.endSN&&!sT(t))this.resetFragmentErrors(e),r?r.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var v;let b=rl((v=t.response)==null?void 0:v.code),E=Ug(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=U.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,b){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${E}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==Gt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===Gt.SendAlternateToPenaltyBox?this.state=U.WAITING_LEVEL:this.state=U.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!rl(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=U.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===U.PARSING||this.state===U.PARSED){let t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),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 ${s} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,Number.POSITIVE_INFINITY,s===te.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===te.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==U.STOPPED&&(this.state=U.IDLE)}afterBufferFlushed(e,t){if(!e)return;let s=be.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===U.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==U.STOPPED&&(this.state=U.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,s,r){let n=s.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 m=f.endPTS-f.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${e.sn} ${h} duration reliably (${m})`),c||!1;let p=r.partial?0:GT(n,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:p,type:h,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var o,l,d,u;let c=((o=this.transmuxer)==null?void 0:o.error)===null,h=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((d=(u=this.levels)==null?void 0:u.length)!=null?d:0)>1;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,s),c){let m=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(m.message),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:m,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=U.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,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN}-${(n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 s=(t=e.loader)==null?void 0:t.stats;if(!s)return!1;let r=s.loading.first>0,a=(s.total-s.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 s=0,{hls:r,media:n,config:a,levels:o,playlistType:l}=this,d=this.getLevelDetails();if(n&&!n.paused&&o){var u;let f=l===te.AUDIO?xT(e.audioCodec,128e3):e.maxBitrate,m=1+r.ttfbEstimate/1e3,p=r.bandwidthEstimate*a.abrBandWidthUpFactor,g=d&&(this.loadingParts?d.partTarget:d.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;s=m+f*g/p,e.details||(s+=m)}let c=this.playhead,h=!(d!=null&&d.live)||t.end-c>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:h}}scheduleTrackSwitch(e,t,s){let{media:r,playlistType:n}=this;if(!r||!e)return;let a=s?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let d=l.maxStartPTS?l.maxStartPTS:l.start,u=l.duration,c=Math.max(a.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>c)return;let f=n===te.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){let r=t===te.AUDIO;this.flushMainBuffer(0,s.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 U.KEY_LOADING:case U.FRAG_LOADING:case U.FRAG_LOADING_WAITING_RETRY:case U.PARSING:case U.PARSED:this.state=U.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(be.isBuffered(e,s)?t=this.getAppendedFrag(s):be.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!zo(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:s,config:r,playlistType:n}=this;if(t!=null&&t.readyState&&e&&s&&r){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;let l=n===te.AUDIO?s.nextAudioTrack:s.nextLoadLevel,d=e[l],{fetchdelay:u,okToFlushForwardBuffer:c}=this.calculateOptimalSwitchPoint(d,o);this.scheduleTrackSwitch(o,u,c)}this.tickImmediate()}};function zT(i,e,t){if(e)for(let s=e.length;s--;){let r=e[s].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace&&(i.start>=n&&i.end<=a||t>i.start&&i.end>n&&i.start<a))return!0}return!1}function Vu(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}var Wu=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=uC(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function uC(i,e){let t=new Uint8Array(e),s=0;for(let r=0;r<i.length;r++){let n=i[r];t.set(n,s),s+=n.length}return t}var Qm={exports:{}},vb;function cC(){return vb||(vb=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;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,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];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(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,b,E;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(E=1,b=new Array(v-1);E<v;E++)b[E-1]=arguments[E];g.fn.apply(g.context,b)}else{var T=g.length,_;for(E=0;E<T;E++)switch(g[E].once&&this.removeListener(d,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,u);break;case 3:g[E].fn.call(g[E].context,u,c);break;case 4:g[E].fn.call(g[E].context,u,c,h);break;default:if(!b)for(_=1,b=new Array(v-1);_<v;_++)b[_-1]=arguments[_];g[E].fn.apply(g[E].context,b)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!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!==u||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(d){var u;return d?(u=t?t+d:d,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(Qm)),Qm.exports}var hC=cC(),qg=ck(hC),fl="1.7.3",ya={};function fC(){return typeof __HLS_WORKER_BUNDLE__=="function"}function mC(){let i=ya[fl];if(i)return i.clientCount++,i;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 ya[fl]=r,r}function pC(i){let e=ya[i];if(e)return e.clientCount++,e;let t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return ya[i]=r,r}function gC(i){let e=ya[i||fl];if(e&&e.clientCount--===1){let{worker:s,objectURL:r}=e;delete ya[i||fl],r&&self.URL.revokeObjectURL(r),s.terminate()}}function vC(i,e,t,s){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 g=new Error(`invalid ADTS sampling index:${a}`);i.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d=r[a],u=a;(o===5||o===29)&&(u-=3);let c,h=(u&14)>>1,f=(u&1)<<7|l<<3,m=0;if(o===1&&a>=6){m=5;let g=a-3;c=[m<<3|h,f|(g&14)>>1,(g&1)<<7|8,0]}else c=[o<<3|h,f];let p="mp4a.40."+(m||o);return $e.log(`manifest codec:${s}, parsed codec:${p}, channels:${l}, rate:${d} (ADTS object type:${o} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:d,channelCount:l,codec:p,parsedCodec:p,manifestCodec:s}}function QT(i,e){return i[e]===255&&(i[e+1]&246)===240}function XT(i,e){return i[e+1]&1?7:9}function Yg(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function EC(i,e){return e+5<i.length}function qu(i,e){return e+1<i.length&&QT(i,e)}function yC(i,e){return EC(i,e)&&QT(i,e)&&Yg(i,e)<=i.length-e}function bC(i,e){if(qu(i,e)){let t=XT(i,e);if(e+t>=i.length)return!1;let s=Yg(i,e);if(s<=t)return!1;let r=e+s;return r===i.length||qu(i,r)}return!1}function ZT(i,e,t,s,r){if(!i.samplerate){let n=vC(e,t,s,r);if(!n)return;Qe(i,n)}}function JT(i){return 1024*9e4/i}function TC(i,e){let t=XT(i,e);if(e+t<=i.length){let s=Yg(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function e_(i,e,t,s,r){let n=JT(i.samplerate),a=s+r*n,o=TC(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||i.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}var ii=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function ms(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var ml=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,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Ci(this.cachedData,e),this.cachedData=null);let s=nl(e,0),r=s?s.length:0,n,a=this._audioTrack,o=this._id3Track,l=s?Bg(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=_C(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ii.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else xk(e,r)?(s=nl(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ii.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){let u=e.slice(n);this.cachedData?this.cachedData=Ci(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:ms(),id3Track:o,textTrack:ms()}}demuxSampleAes(e,t,s){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:ms(),id3Track:this._id3Track,textTrack:ms()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},_C=(i,e,t)=>{if(Q(i))return i*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},AC=[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],SC=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],IC=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],RC=[0,1,1,4];function t_(i,e,t,s,r){if(t+24>e.length)return;let n=i_(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function i_(i,e){let t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=AC[l*14+r-1]*1e3,c=SC[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=IC[t][s],m=RC[s],p=f*8*m,g=Math.floor(f*d/c+a)*m,v=Xo();return!!v&&v<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function jg(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function s_(i,e){return e+1<i.length&&jg(i,e)}function LC(i,e){return jg(i,e)&&4<=i.length-e}function r_(i,e){if(e+1<i.length&&jg(i,e)){let s=i_(i,e),r=4;s!=null&&s.frameLength&&(r=s.frameLength);let n=e+r;return n===i.length||s_(i,n)}return!1}var Yu=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ul(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Rr.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){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,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){let a=TT(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,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(s>=n.length);s++){let a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}},Cp=class extends ml{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=nl(e,0),r=(s==null?void 0:s.length)||0;if(r_(e,r))return!1;for(let n=e.length;r<n;r++)if(bC(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return yC(e,t)}appendFrame(e,t,s){ZT(e,this.observer,t,s,e.manifestCodec);let r=e_(e,t,s,this.basePTS,this.frameIndex);if((r==null?void 0:r.missing)===0)return r}demuxSampleAes(e,t,s){let r=this.demux(e,s),n=this.sampleAes=new Yu(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(r.audioTrack.samples,0,()=>{a(r)})})}},n_=(i,e)=>{let t=0,s=5;e+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];let o=Math.min(s,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,s-=o}return t},wp=class extends ml{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){let r=a_(e,t,s,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=nl(e,0);if(!t)return!1;let s=t.length;if(e[s]===11&&e[s+1]===119&&Bg(t)!==void 0){if(n_(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function a_(i,e,t,s,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,u=[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+u>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,b=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,T=s+r*E,_=e.subarray(t,t+u);return i.config=b,i.channelCount=p,i.samplerate=o,i.samples.push({unit:_,pts:T}),u}var Mp=class extends ml{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=nl(e,0),s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Bg(t)!==void 0&&n_(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(r_(e,s))return $e.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return LC(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return t_(e,t,s,this.basePTS,this.frameIndex)}},xC=/\/emsg[-/]ID3/i,Pp=class{constructor(e,t,s,r=$e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=r}resetTimeStamp(){}resetInitSegment(e,t,s,r){let n=this.videoTrack=ms("video",1),a=this.audioTrack=ms("audio",1),o=this.txtTrack=ms("text",1);if(this.id3Track=ms("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=gT(e);if(l.video){let{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){let{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=hT.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Kk(e,"moof")}demux(e,t,s){this.timeOffset=t;let r=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Ci(this.remainderData,e));let d=Jk(r);this.remainderData=d.remainder,n.samples=d.valid||new Uint8Array}else n.samples=r;let o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,s);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let s=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,s,t);return{videoTrack:r,audioTrack:ms(),id3Track:a,textTrack:ms(),initData:this.initData,sampleData:o}}parseFragment(e,t,s,r){let n=this.initData;if(n&&r){let{samples:a,sampleData:o}=Zk(s,e,n,this.logger,r.iframe);return t.samples=a,o}t.samples=eD(s,e)}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let r=Ee(e.samples,["emsg"]);r&&r.forEach(n=>{let a=tD(n);if(xC.test(a.schemeIdUri)){let o=Eb(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:ii.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||ii.misbklv;if(a.schemeIdUri.startsWith(o)){let l=Eb(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:ii.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function Eb(i,e){return Q(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}var kC=1,DC=2,qo=-1,ju=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,r=s.length;if(r){let n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let r=t.byteLength;if(r===0)return[];let n=e.naluState||0,a=n===qo?0:n,o=[],l=0,d=0,u=-1,c=0;for(n===qo&&(u=0,c=this.getNALuType(t,0),d=1);d<r;){let h=t.indexOf(kC,d);if(h===-1)break;d=h+1;let f=h;for(;f>0&&t[f-1]===0;)f--;if(!(h-f+(f===0?a:0)<DC)){if(u>=0)o.push({data:t.subarray(u,f),type:c});else{let p=this.getLastNalUnit(e.samples);p&&(f>0?p.data=Ci(p.data,t.subarray(0,f)):a>0&&(p.data=p.data.subarray(0,p.data.byteLength-a)),p.state=0)}if(d<r)u=d,c=this.getNALuType(t,d);else{l=qo,u=-1;break}}}if(l!==qo){let h=r;for(;h>0&&t[h-1]===0;)h--;l=r-h+(h===0?a:0)}if(u>=0)o.push({data:t.subarray(u),type:c,state:l});else if(o.length===0&&l!==qo){let h=this.getLastNalUnit(e.samples);h&&(h.data=Ci(h.data,t),h.state=l)}return e.naluState=l,o}},bn=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,s=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(s,s+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),s=this.word>>>32-t;if(e>32&&$e.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?s<<t|this.readBits(t):s}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)}},Op=class extends ju{parsePES(e,t,s,r,n){let a=n.iframe,o=this.parseNALu(e,s.data,r),l=this.VideoSample,d,u=!1;s.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(c=>{var h,f;switch(c.type){case 1:{if(a)break;let v=!1;d=!0;let b=c.data;if(u&&b.length>4){let E=this.readSliceType(b);(E===2||E===4||E===7||E===9)&&(v=!0)}if(v){var m;(m=l)!=null&&m.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=v;break}case 5:d=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;d=!0,al(c.data,1,s.pts,t.samples);break}case 7:{var p,g;d=!0,u=!0;let v=c.data,b=this.readSPS(v);if(!e.sps||e.width!==b.width||e.height!==b.height||((p=e.pixelRatio)==null?void 0:p[0])!==b.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==b.pixelRatio[1]){e.width=b.width,e.height=b.height,e.pixelRatio=b.pixelRatio,e.sps=[v];let E=v.subarray(1,4),T="avc1.";for(let _=0;_<3;_++){let I=E[_].toString(16);I.length<2&&(I="0"+I),T+=I}e.codec=T}break}case 8:d=!0,e.pps=[c.data];break;case 9:d=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:d=!0;break;default:d=!1;break}l&&d&&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 bn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){let t=new bn(e),s=0,r=0,n=0,a=0,o,l,d,u=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);u();let b=u();if(c(5),m(3),u(),g(),b===100||b===110||b===122||b===244||b===44||b===83||b===86||b===118||b===128){let x=h();if(x===3&&m(1),g(),g(),m(1),f())for(l=x!==3?8:12,d=0;d<l;d++)f()&&(d<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(),d=0;d<o;d++)p();g(),m(1);let T=h(),_=h(),I=c(1);I===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let S=[1,1];if(f()&&f())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-s*2-r*2),height:(2-I)*(_+1)*16-(I?2:4)*(n+a),pixelRatio:S}}},Np=class extends ju{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null;let d=u=>(a=this.VideoSample=this.createVideoSample(u,s.pts,s.dts),a);n.forEach((u,c)=>{var h,f;if(this.startsNewAccessUnit(a,e,u,c)){this.pushAccessUnit(a,e);let p=u.type>=16&&u.type<=23;a=d(p),l=!1}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=d(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var m;(m=a)!=null&&m.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=d(!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=d(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,al(u.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Qe(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 p=this.readSPS(u.data);e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.codec=p.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let g in p.params)e.params[g]=p.params[g]}this.pushParameterSet(e.sps,u.data,e.vps),a||(a=d(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let p=this.readPPS(u.data);for(let g in p)e.params[g]=p[g]}this.pushParameterSet(e.pps,u.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=d(!1));break;default:o=!1;break}a&&o&&a.units.push(u)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,r){if(!e)return!1;if(!t.audFound&&r===0)return!0;if(!e.frame)return!1;let{type:n,data:a}=s;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),s=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new bn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){let t=new bn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=[],E=[];for(let ie=0;ie<s;ie++)b.push(t.readBoolean()),E.push(t.readBoolean());if(s>0)for(let ie=s;ie<8;ie++)t.readBits(2);for(let ie=0;ie<s;ie++)b[ie]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[ie]&&t.readUByte();t.readUEG();let T=t.readUEG();T==3&&t.skipBits(1);let _=t.readUEG(),I=t.readUEG(),S=t.readBoolean(),x=0,k=0,R=0,D=0;S&&(x+=t.readUEG(),k+=t.readUEG(),R+=t.readUEG(),D+=t.readUEG());let w=t.readUEG(),N=t.readUEG(),$=t.readUEG(),H=t.readBoolean();for(let ie=H?0:s;ie<=s;ie++)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 xe=0;xe<4;xe++)for(let we=0;we<(xe===3?2:6);we++)if(!t.readBoolean())t.readUEG();else{let gt=Math.min(64,1<<4+(xe<<1));xe>1&&t.readEG();for(let Ie=0;Ie<gt;Ie++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let B=t.readUEG(),W=0;for(let ie=0;ie<B;ie++){let xe=!1;if(ie!==0&&(xe=t.readBoolean()),xe){ie===B&&t.readUEG(),t.readBoolean(),t.readUEG();let we=0;for(let pt=0;pt<=W;pt++){let gt=t.readBoolean(),Ie=!1;gt||(Ie=t.readBoolean()),(gt||Ie)&&we++}W=we}else{let we=t.readUEG(),pt=t.readUEG();W=we+pt;for(let gt=0;gt<we;gt++)t.readUEG(),t.readBoolean();for(let gt=0;gt<pt;gt++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let ie=t.readUEG();for(let xe=0;xe<ie;xe++){for(let we=0;we<$+4;we++)t.readBits(1);t.readBits(1)}}let K=0,q=1,ce=1,se=!0,ye=1,ue=0;t.readBoolean(),t.readBoolean();let Ce=!1;if(t.readBoolean()){if(t.readBoolean()){let Wt=t.readUByte(),Gs=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Pt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Wt>0&&Wt<16?(q=Gs[Wt-1],ce=Pt[Wt-1]):Wt===255&&(q=t.readBits(16),ce=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(),Ce=t.readBoolean(),Ce&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ye=t.readBits(32),ue=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Pt=t.readBoolean(),qt=t.readBoolean(),di=!1;(Pt||qt)&&(di=t.readBoolean(),di&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),di&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ti=0;ti<=s;ti++){se=t.readBoolean();let Bt=se||t.readBoolean(),ls=!1;Bt?t.readEG():ls=t.readBoolean();let vt=ls?1:t.readUEG()+1;if(Pt)for(let je=0;je<vt;je++)t.readUEG(),t.readUEG(),di&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(qt)for(let je=0;je<vt;je++)t.readUEG(),t.readUEG(),di&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Ne=_,mt=I;if(S){let ie=1,xe=1;T===1?ie=xe=2:T==2&&(ie=2),Ne=_-ie*k-ie*x,mt=I-xe*D-xe*R}let Ft=r?["A","B","C"][r]:"",Zt=o<<24|l<<16|d<<8|u,Xe=0;for(let ie=0;ie<32;ie++)Xe=(Xe|(Zt>>ie&1)<<31-ie)>>>0;let ei=Xe.toString(16);return a===1&&ei==="2"&&(ei="6"),{codecString:`hvc1.${Ft}${a}.${ei}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:K,chroma_format_idc:T,frame_rate:{fixed:se,fps:ue/ye}},width:Ne,height:mt,pixelRatio:[q,ce]}}readPPS(e){let t=new bn(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 ji(e).substring(3)===ji(t).substring(3)}},Dt=188,zu=class i{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){let s=i.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(Dt*5,t-Dt)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Dt)if(e[l]===71&&(t-l===Dt||e[l+Dt]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Dt*99,e.length-Dt)+1)),n||(n=Qu(e,l)===0),n&&o>1&&(a===0&&o>2||l+Dt>s))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:hT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=i.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Fp(this.logger):null,this._audioTrack=i.createTrack("audio",r),this._id3Track=i.createTrack("id3"),this._txtTrack=i.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,e&&this.demux(e,0,a,(n==null?void 0:n.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s,r=!1,n=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,d=this._audioTrack,u=this._id3Track,c=this._txtTrack,h=s.iframe,f=o.pid,m=o.pesData,p=d.pid,g=u.pid,v=this._klvPid,b=d.pesData,E=u.pesData,T=null,_=null,I=this.pmtParsed,S=this._pmtId,x=e.length;if(this.remainderData&&(e=Ci(this.remainderData,e),x=e.length,this.remainderData=null),x<Dt&&!n)return this.remainderData=e,{audioTrack:d,videoTrack:o,id3Track:u,textTrack:c};let k=Math.max(0,i.syncOffset(e));x-=(x-k)%Dt,x<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let R=0;for(let w=k;w<x;w+=Dt)if(e[w]===71){let N=!!(e[w+1]&64),$=Qu(e,w),H=(e[w+3]&48)>>4,O;if(H>1){if(O=w+5+e[w+4],O===w+Dt)continue}else O=w+4;switch($){case f:N&&(m&&!(l!=null&&l.isCorrupted)&&(a=pn(m,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,a,!1,s)),m={data:[],size:0},l==null||l.reset(f)),l==null||l.handlePacket(e.subarray(w)),m&&(m.data.push(e.subarray(O,w+Dt)),m.size+=w+Dt-O);break;case p:if(h)break;if(N){if(b&&(a=pn(b,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,a,s);break;case"mp3":this.parseMPEGPES(d,a);break;case"ac3":this.parseAC3PES(d,a);break}b={data:[],size:0}}b&&(b.data.push(e.subarray(O,w+Dt)),b.size+=w+Dt-O);break;case g:if(h)break;N&&(E&&(a=pn(E,this.logger))&&this.parseID3PES(u,a),E={data:[],size:0}),E&&(E.data.push(e.subarray(O,w+Dt)),E.size+=w+Dt-O);break;case v:if(h)break;N&&(T&&(a=pn(T,this.logger))&&this.parseKlvPES(u,a),T={data:[],size:0}),T&&(T.data.push(e.subarray(O,w+Dt)),T.size+=w+Dt-O);break;case 0:N&&(O+=e[O]+1),S=this._pmtId=CC(e,O);break;case S:{N&&(O+=e[O]+1);let F=wC(e,O,this.typeSupported,r,this.observer,this.logger,this.config,s);f=F.videoPid,f>0&&(o.pid=f,o.segmentCodec=F.segmentVideoCodec),p=F.audioPid,p>0&&(d.pid=p,d.segmentCodec=F.segmentAudioCodec),g=F.id3Pid,g>0&&(u.pid=g),v=F.klvPid,v>0&&(this._klvPid=v),_!==null&&!I&&(this.logger.warn(`MPEG-TS PMT found at ${w} after unknown PID '${_}'. Backtracking to sync byte @${k} to parse all TS packets.`),_=null,w=k-188),I=this.pmtParsed=!0;break}case 17:case 8191:break;default:_=$;break}}else R++;R>0&&Up(this.observer,new Error(`Found ${R} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=m,d.pesData=b,u.pesData=E;let D={audioTrack:d,videoTrack:o,id3Track:u,textTrack:c};return n&&this.extractRemainingSamples(D,s),D}flush(e,t){let{remainderData:s}=this;this.remainderData=null;let r;return s?r=this.demux(s,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:s,videoTrack:r,id3Track:n,textTrack:a}=e,o=r.pesData,l=s.pesData,d=n.pesData,u=this.videoIntegrityChecker,c;if(o&&!(u!=null&&u.isCorrupted)&&(c=pn(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=pn(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c,t);break;case"mp3":this.parseMPEGPES(s,c);break;case"ac3":this.parseAC3PES(s,c);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;d&&(c=pn(d,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=d}demuxSampleAes(e,t,s,r){let n=this.demux(e,s,r,!0,!this.config.progressive),a=this.sampleAes=new Yu(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Op:e==="hevc"&&(this.videoParser=new Np))}decrypt(e,t){return new Promise(s=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){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=Ci(n.sample.unit,a);else{let m=f-h;n.sample.unit.set(a.subarray(0,h),m),e.samples.push(n.sample),r=n.missing}}let o,l;for(o=r,l=a.length;o<l-1&&!qu(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",Up(this.observer,new Error(h),s,f,this.logger),!f)return}ZT(e,this.observer,a,o,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(n){let h=JT(e.samplerate);d=n.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let u=0,c;for(;o<l;)if(c=e_(e,a,o,d,u),o+=c.length,c.missing){this.aacOverFlow=c;break}else for(u++;o<l-1&&!qu(a,o);o++);}parseMPEGPES(e,t){let s=t.data,r=s.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(s_(s,a)){let l=t_(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=s.length,a=0,o=0,l;for(;o<n&&(l=a_(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=Qe({},t,{type:this._videoTrack?ii.emsg:ii.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;let r=(s=t.pts)!=null?s: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 d=n[a];a+=1;let u=0;if(d&128){let m=d&127;if(m===0||m>4||a+m>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let p=0;p<m;p++)u=u<<8|n[a+p];a+=m}else u=d;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let c=a+u,h=n.subarray(l,c),f={data:h,len:h.byteLength,pts:r,dts:(o=t.dts)!=null?o:r,type:ii.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=c}}};function Qu(i,e){return((i[e+1]&31)<<8)+i[e+2]}function CC(i,e){return(i[e+10]&31)<<8|i[e+11]}function wC(i,e,t,s,r,n,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(i[e+1]&15)<<8|i[e+2],u=e+3+d-4,c=(i[e+10]&15)<<8|i[e+11];for(e+=12+c;e<u;){let h=Qu(i,e),f=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Xm("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(!s){Xm("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(!s){Xm("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 m=e+5,p=f;for(;p>2;){switch(i[m]){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 v=i[m+1]+2;m+=v,p-=v}}break;case 194:case 135:return Up(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 Up(i,e,t,s,r){r.warn(`parsing error: ${e.message}`),i.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:t,error:e,reason:e.message})}function Xm(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function pn(i,e){let t=0,s,r,n,a,o,l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ci(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;let u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[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=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;let h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var Fp=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=Qu(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let s=(e[3]&48)>>4;if(s===0)return;let r=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=r;let a=(s&1)!=0;if((s&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;let d=a?n+1&15:n;if(r!==d){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${d} 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}}},Bp=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}}},Xu,MC={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])},Zm=new Uint8Array([0,0,0,0,0,0,0,0]),PC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),OC=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),NC=new Uint8Array([0,0,0,0,0,0,0,0]),Yo=new Uint8Array([0,0,0,0,0,0,0,1]),yb=new Uint8Array([105,115,111,109]),UC=new Uint8Array([97,118,99,49]),FC=new Uint8Array([0,0,0,1]),Ys=class i{static box(e,...t){let s=8,r=t.length,n=r;for(;r--;)s+=t[r].byteLength;let a=new Uint8Array(s);for(At(a,0,s),At(a,4,e),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return i.box(me.hdlr,MC[e])}static mdat(e){return i.box(me.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(hs+1)),r=Math.floor(t%(hs+1));return i.box(me.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,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return i.box(me.mdia,i.mdhd(e.timescale||0,e.duration||0),i.hdlr(e.type),i.minf(e))}static mfhd(e){return i.box(me.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?i.box(me.minf,i.box(me.smhd,NC),i.DINF,i.stbl(e)):i.box(me.minf,i.box(me.vmhd,OC),i.DINF,i.stbl(e))}static moof(e,t,s){return i.box(me.moof,i.mfhd(e),i.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=i.trak(e[t]);return i.box.apply(null,[me.moov,i.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(i.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=i.trex(e[t]);return i.box.apply(null,[me.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(hs+1)),r=Math.floor(t%(hs+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,s>>24,s>>16&255,s>>8&255,s&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 i.box(me.mvhd,n)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return i.box(me.sdtp,s)}static stbl(e){return i.box(me.stbl,i.stsd(e),i.box(me.stts,Zm),i.box(me.stsc,Zm),i.box(me.stsz,PC),i.box(me.stco,Zm))}static avc1(e){let t=[],s=[],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,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));let o=i.box(me.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return i.box(me.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,d>>8&255,d&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,i.box(me.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(me.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){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 i.box(me.mp4a,i.audioStsd(e),i.box(me.esds,i.esds(e)))}static mp3(e){return i.box(me[".mp3"],i.audioStsd(e))}static ac3(e){return i.box(me["ac-3"],i.audioStsd(e),i.box(me.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return i.box(me.stsd,Yo,i.mp4a(e));if(t==="ac3"&&e.config)return i.box(me.stsd,Yo,i.ac3(e));if(t==="mp3"&&e.codec==="mp3")return i.box(me.stsd,Yo,i.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return i.box(me.stsd,Yo,i.avc1(e));if(t==="hevc"&&e.vps)return i.box(me.stsd,Yo,i.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,s=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(s/(hs+1)),o=Math.floor(s%(hs+1));return i.box(me.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 s=i.sdtp(e),r=e.id,n=Math.floor(t/(hs+1)),a=Math.floor(t%(hs+1));return i.box(me.traf,i.box(me.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),i.box(me.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])),i.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,i.box(me.trak,i.tkhd(e),i.mdia(e))}static trex(e){let t=e.id;return i.box(me.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 s=e.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n),o,l,d,u,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=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&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 i.box(me.trun,a)}static initSegment(e){let t=i.moov(e);return Ci(i.FTYP,t)}static hvc1(e){let t=e.params,s=[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),s.length]),a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}let d=i.box(me.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return i.box(me.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,u>>8&255,u&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]),d,i.box(me.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(me.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Xu=Ys;Ys.FTYP=Xu.box(me.ftyp,yb,FC,yb,UC);Ys.DINF=Xu.box(me.dinf,Xu.box(me.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var o_=9e4;function zg(i,e,t=1,s=!1){let r=i*e*t;return s?Math.round(r):r}function BC(i,e,t=1,s=!1){return zg(i,e,1/t,s)}function jo(i,e=!1){return zg(i,1e3,1/o_,e)}function $C(i,e=1){return zg(i,o_,1/e)}function bb(i){let{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}var HC=10*1e3,GC=1024,KC=1152,VC=1536,$p=8589934592;function Tb(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1,paddingValue:0}}}var ga=class extends si{constructor(e,t,s,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=s,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&&bb(t)} > ${e&&bb(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,s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=Ai(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l,d){let u,c,h,f,m,p,g=n,v=n,E=!d.iframe&&e.pid>-1,T=t.pid>-1,_=t.samples.length,I=e.samples.length>0,S=o&&_>0||_>1;if((!E||I)&&(!T||S)||this.ISGenerated||o){if(this.ISGenerated){var k,R,D,w;let O=this.videoTrackConfig;(O&&(t.width!==O.width||t.height!==O.height||((k=t.pixelRatio)==null?void 0:k[0])!==((R=O.pixelRatio)==null?void 0:R[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((w=O.pixelRatio)==null?void 0:w[1]))||!O&&S||this.nextAudioTs===null&&I)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));let N=this.isVideoContiguous,$=-1,H;if(S&&($=WC(t.samples),!N&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,$>0){this.warn(`Dropped ${$} out of ${_} video samples due to a missing keyframe`);let O=this.getVideoStartPts(t.samples);t.samples=t.samples.slice($),t.dropped+=$,v+=(t.samples[0].pts-O)/t.inputTimeScale,H=v}else $===-1&&(this.warn(`No keyframe found out of ${_} video samples`),p=!1);if(this.ISGenerated){if(I&&S&&n){let O=this.getVideoStartPts(t.samples),B=(Ai(e.samples[0].pts,O)-O)/t.inputTimeScale;g+=Math.max(0,B),v+=Math.max(0,-B)}if(I){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,g,this.isAudioContiguous,a,T||S||l===te.AUDIO?v:void 0,d),S){let O=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,v,N,O,d)}}else S&&(u=this.remuxVideo(t,v,N,0,d));u&&(u.firstKeyFrame=$,u.independent=$!==-1,u.firstKeyFramePTS=H)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(m=l_(s,n,this._initPTS,this._initDTS)),r.samples.length&&(f=d_(r,n,this._initPTS))),{audio:c,video:u,initSegment:h,independent:p,text:f,id3:m}}computeInitPts(e,t,s,r){let n=Math.round(s*t),a=Ai(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n;)a+=$p;return a-n}generateIS(e,t,s,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(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):Ys.initSegment([e]),metadata:{channelCount:e.channelCount}},u){p=e.id,m=e.inputTimeScale;let g=this.computeInitPts(n[0].pts,m,s,"audio");(!d||m!==d.timescale||s===0&&g<d.baseTime)&&(h=f=g)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ys.initSegment([t]),metadata:{width:t.width,height:t.height}},u){p=t.id,m=t.inputTimeScale;let g=this.getVideoStartPts(a),v=Ai(a[0].dts,g),b=this.computeInitPts(v,m,s,"video"),E=this.computeInitPts(g,m,s,"video");(!d||m!==d.timescale||Q(h)||s===0&&E<d.baseTime)&&(f=Math.min(f,b),h=Math.min(h,b))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u&&Q(h)?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} 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,s,r,n){let a=e.inputTimeScale,o=e.samples,l=[],d=o.length,u=this._initPTS,c=u.baseTime*a/u.timescale,h=this.nextVideoTs,f=8,m=this.videoSampleDuration,p,g,v=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,E=!1;if(!s||h===null){let K=c+t*a,q=o[0].pts-Ai(o[0].dts,o[0].pts);Xo()&&h!==null&&Math.abs(K-q-(h+c))<15e3?s=!0:h=K-q-c}let T=h+c;for(let K=0;K<d;K++){let q=o[K];q.pts=Ai(q.pts,T),q.dts=Ai(q.dts,T),q.dts<o[K>0?K-1:K].dts&&(E=!0)}E&&o.sort(function(K,q){let ce=K.dts-q.dts,se=K.pts-q.pts;return ce||se}),p=o[0].dts,g=o[o.length-1].dts;let _=g-p,I=_?Math.round(_/(d-1)):m||e.inputTimeScale/30;if(s){let K=p-T,q=K>I,ce=K<-1;if((q||ce)&&(q?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jo(K,!0)} ms (${K}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jo(-K,!0)} ms (${K}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ce||T>=o[0].pts||Xo())){p=T;let se=o[0].pts-K;if(q)o[0].dts=p,o[0].pts=se;else{let ye=!0;for(let ue=0;ue<o.length&&!(o[ue].dts>se&&ye);ue++){let Ce=o[ue].pts;if(o[ue].dts-=K,o[ue].pts-=K,ue<o.length-1){let Te=o[ue+1].pts,Ne=o[ue].pts,mt=Te<=Ne,Ft=Te<=Ce;ye=mt==Ft}}}this.log(`Video: Initial PTS/DTS adjusted: ${jo(se,!0)}/${jo(p,!0)}, delta: ${jo(K,!0)} ms`)}}p=Math.max(0,p);let S=0,x=0,k=p;for(let K=0;K<d;K++){let q=o[K],ce=q.units,se=ce.length,ye=0;for(let ue=0;ue<se;ue++)ye+=ce[ue].data.length;x+=ye,S+=se,q.length=ye,q.dts<k?(q.dts=k,k+=I/4|0||1):k=q.dts,v=Math.min(q.pts,v),b=Math.max(q.pts,b)}g=o[d-1].dts;let R=x+4*S+8,D;try{D=new Uint8Array(R)}catch(K){this.observer.emit(y.ERROR,y.ERROR,{type:re.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:K,bytes:R,reason:`fail allocating video mdat ${R}`});return}At(D,0,R),At(D,4,me.mdat);let w=!1,N=Number.POSITIVE_INFINITY,$=Number.POSITIVE_INFINITY,H=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let K=0;K<d;K++){let q=o[K],ce=q.units,se=0;for(let Ce=0,Te=ce.length;Ce<Te;Ce++){let Ne=ce[Ce],mt=Ne.data,Ft=Ne.data.byteLength;At(D,f,Ft),f+=4,D.set(mt,f),f+=Ft,se+=4+Ft}let ye;if(K<d-1)m=o[K+1].dts-q.dts,ye=o[K+1].pts-q.pts;else{let Ce=this.config,Te=K>0?q.dts-o[K-1].dts:I;if(ye=K>0?q.pts-o[K-1].pts:I,Ce.stretchShortVideoTrack&&this.nextAudioTs!==null){let Ne=Math.floor(Ce.maxBufferHole*a),mt=(r?v+r*a:this.nextAudioTs+c)-q.pts;mt>Ne?(m=mt-Te,m<0?m=Te:w=!0,this.log(`It is approximately ${mt/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=Te}else m=Te}let ue=Math.round(q.pts-q.dts);if(N=Math.min(N,m),H=Math.max(H,m),$=Math.min($,ye),O=Math.max(O,ye),!s&&K===0&&ue>m){let Ce=Math.round(ue/I)*I;Ce-ue===1&&(this.log(`pad first CTS ${ue} -> ${Ce} of sn: ${n.sn}`),ue=Ce)}l.push(Tb(q.key,m,se,ue))}if(l.length){let K=Xo();if(K){if(K<70){let q=l[0].flags;q.dependsOn=2,q.isNonSync=0}}else if(oD()&&O-$<H-N&&I/H<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let q=p;for(let ce=0,se=l.length;ce<se;ce++){let ye=q+l[ce].duration,ue=q+l[ce].cts;if(ce<se-1){let Ce=ye+l[ce+1].cts;l[ce].duration=Ce-ue}else l[ce].duration=ce?l[ce-1].duration:I;l[ce].cts=0,q=ye}}}m=w||!m?I:m;let F=g+m;this.nextVideoTs=h=F-c,this.videoSampleDuration=m,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=m=n.duration*a,this.nextVideoTs=h=p+m-c):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let Z={data1:Ys.moof(n.sn,p,Qe(e,{samples:l})),data2:D,startPTS:(v-c)/a,endPTS:(b+m-c)/a,startDTS:(p-c)/a,endDTS:h/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Z}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return KC;case"ac3":return VC;default:return GC}}remuxAudio(e,t,s,r,n,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,d=o/l,u=this.getSamplesPerFrame(e),c=u*d,h=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,m=[],p=n!==void 0,g=e.samples,v=f?0:8,b=this.nextAudioTs||-1,E=h.baseTime*o/h.timescale,T=E+t*o;if(this.isAudioContiguous=s=s||g.length&&b>0&&(r&&Math.abs(T-(b+E))<9e3||Math.abs(Ai(g[0].pts,T)-(b+E))<20*c),g.forEach(function(F){F.pts=Ai(F.pts,T)}),!s||b<0){let F=g.length;if(g=g.filter(B=>B.pts>=0),F!==g.length&&this.warn(`Removed ${g.length-F} of ${F} samples (initPTS ${E} / ${o})`),!g.length)return;n===0?b=0:r&&!p?b=Math.max(0,T-E):b=g[0].pts-E}if(e.segmentCodec==="aac"){let F=this.config.maxAudioFramesDrift;for(let B=0,W=b+E;B<g.length;B++){let Z=g[B],K=Z.pts,q=K-W,ce=Math.abs(1e3*q/o);if(q<=-F*c&&p)B===0&&(this.warn(`Audio frame @ ${(K/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*q/o)} ms.`),this.nextAudioTs=b=K-E,W=K);else if(q>=F*c&&ce<HC&&p){let se=Math.round(q/c);for(W=K-se*c;W<0&&se&&c;)se--,W+=c;B===0&&(this.nextAudioTs=b=W-E),this.warn(`Injecting ${se} audio frames @ ${((W-E)/o).toFixed(3)}s due to ${Math.round(1e3*q/o)} ms gap.`);for(let ye=0;ye<se;ye++){let ue=Bp.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ue||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ue=Z.unit.subarray()),g.splice(B,0,{unit:ue,pts:W}),W+=c,B++}}Z.pts=W,W+=c}}let _=null,I=null,S,x=0,k=g.length;for(;k--;)x+=g[k].unit.byteLength;for(let F=0,B=g.length;F<B;F++){let W=g[F],Z=W.unit,K=W.pts;if(I!==null){let ce=m[F-1];ce.duration=Math.round((K-I)/d)}else if(s&&e.segmentCodec==="aac"&&(K=b+E),_=K,x>0){x+=v;try{S=new Uint8Array(x)}catch(ce){this.observer.emit(y.ERROR,y.ERROR,{type:re.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:ce,bytes:x,reason:`fail allocating audio mdat ${x}`});return}f||(At(S,0,x),At(S,4,me.mdat))}else return;S&&S.set(Z,v);let q=Z.byteLength;v+=q,m.push(Tb(!0,u,q,0)),I=K}let R=m.length;if(!R)return;let D=m[m.length-1];b=I-E,this.nextAudioTs=b+d*D.duration;let w=f?new Uint8Array(0):Ys.moof(e.sequenceNumber++,_/d,Qe({},e,{samples:m}));e.samples=[];let N=(_-E)/o,$=this.nextAudioTs/o,O={data1:w,data2:S,startPTS:N,endPTS:$,startDTS:N,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,O}};function Ai(i,e){let t;if(e===null)return i;for(e<i?t=-$p:t=$p;Math.abs(i-e)>4294967296;)i+=t;return i}function WC(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function l_(i,e,t,s){let r=i.samples.length;if(!r)return;let n=i.inputTimeScale;for(let o=0;o<r;o++){let l=i.samples[o];l.pts=Ai(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ai(l.dts-s.baseTime*n/s.timescale,e*n)/n}let a=i.samples;return i.samples=[],{samples:a}}function d_(i,e,t){let s=i.samples.length;if(!s)return;let r=i.inputTimeScale;for(let a=0;a<s;a++){let o=i.samples[a];o.pts=Ai(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);let n=i.samples;return i.samples=[],{samples:n}}var Hp=class extends si{constructor(e,t,s,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,s,r){this.audioCodec=t,this.videoCodec=s,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){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=s||gT(e);if(t)Yk(e,t);else{let d=a||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}a&&(r=_b(a,Je.AUDIO,this)),o&&(n=_b(o,Je.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,s,r,n,a,o,l,d,u,c){var h,f;let{initPTS:m,lastEndTime:p}=this,g={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Q(p)||(p=this.lastEndTime=n||0);let v=t.samples;if(!v.length)return g;let b=this.pendingInitSegment;b&&(this.pendingInitSegment=void 0,this.generateInitSegment(b,this.decryptdata,u));let E={initPTS:void 0,timescale:void 0,trackId:void 0},T=this.initData;if((h=T)!=null&&h.length||(this.generateInitSegment(v),T=this.initData),!((f=T)!=null&&f.length))return this.warn("Failed to generate initSegment."),g;if(d.iframe&&T.audio&&T.video){var _;let ie=(_=this.initTracks)==null||(_=_.audiovideo)==null?void 0:_.initSegment,xe=ie?Hk(ie):null;if(xe){var I;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(xe,this.decryptdata),(I=this.initData)!=null&&I.length&&(T=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(E.tracks=this.initTracks,g.initSegment=E,this.emitInitSegment=!1);let S=d.iframe,x=c&&(!S||c.includeSampleDetails)?c.tracks:Xk(v,T,d,this,S),k=T.audio?x[T.audio.id]:null,R=T.video?x[T.video.id]:null,D=!!T.audio,w=!!T.video,N="";D&&(N+="audio"),w&&(N+="video");let $=pu(R,1/0),H=pu(k,1/0),O=pu(R,0,!0),F=pu(k,0,!0),B=n,W=0;R&&k&&T.audio&&(H>O||$>F)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${$}-${O} a: ${H}-${F}}`,R,k);let Z=!!k&&(!R||!m&&H<$||!!m&&m.trackId===T.audio.id),K=Z?k:R;if(!K)return this.log(`No media samples found in ${l} ${d.level} ${d.part===-1?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${n}`),g;let q=v,ce,se;if(R&&R.sampleCount>=1&&T.video&&d.iframe){let{trun:ie,start:xe}=R,we=ie.length===1,pt=ie.length?we?ie[0].samples:ie[0].samples.concat(...ie.slice(1).map(gt=>gt.samples)):[];if(pt.length){let gt=ie[0],Ie=gt;for(let ti=ie.length;ti--;)if(ie[ti].samples.length){Ie=ie[ti];break}let Wt=Ie.lastSampleDurationOffset,{defaultSampleDurationOffset:Gs}=gt,Pt=Math.abs(d.duration-(O-$))>.05,qt=pt.length<R.sampleCount;if(!(Pt||qt||this.videoOnlyRemux||!we))W=O-$;else{let ti=qt?Ie.sampleOffset+Ie.samples.reduce((je,un)=>je+un.size,0):void 0,Bt=Pt?d.duration:O-$,ls=YC(pt,Bt*T.video.timescale,Wt,Gs),vt=Gk(v,T.video.id,pt.length,ti,ls);vt?(q=vt,se=qC(xe,pt)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),W=vt&&ls?Bt:O-$}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${ie.length})`),W=O-$}else W=Z?F-H:O-$;if(this.videoOnlyRemux&&q===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),g;let ye=K.timescale,ue=K.start-n*ye,Ce=Z?T.audio.id:T.video.id;if(B=K.start/ye,(a||!m)&&(jC(m,B,n,W)||ye!==m.timescale)){let ie=!1,xe=Z?"audio":"video";if(m){let we=n!==0?B/n:1+B/1;ie=B>=0&&Math.abs(1-we)<.001,this.log(`${xe} timestamps in track ${Ce} at playlist time: ${a?"":"~"}${n} maps to ${B} with initPTS: ${m.baseTime/m.timescale} (${ue/ye-m.baseTime/m.timescale}s diff) (${N}) drift estimate: ${we} ${ie?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}ie||(this.log(`Found initPTS in ${xe} track ${Ce} at playlist time: ${n} offset: ${B-n} (${ue}/${ye})`),m=null,E.initPTS=ue,E.timescale=ye,E.trackId=Ce)}m?(E.initPTS=m.baseTime,E.timescale=m.timescale,E.trackId=m.trackId):((!E.timescale||E.trackId===void 0||E.initPTS===void 0)&&(this.warn("Could not set initPTS"),E.initPTS=B,E.timescale=1,E.trackId=-1),this.initPTS=m={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId});let Te=B-m.baseTime/m.timescale,Ne=Te+W,mt=w&&(K==null?void 0:K.ptsMin)!==void 0?K.ptsMin/K.timescale-m.baseTime/m.timescale:Te,Ft=se!==void 0&&R?se/R.timescale-m.baseTime/m.timescale:w&&K!=null&&K.ptsMax?K.ptsMax/K.timescale-m.baseTime/m.timescale:Ne;W>0?this.lastEndTime=Ne:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let Zt=(T.audio?T.audio.encrypted:!1)||(T.video?T.video.encrypted:!1),Xe={data1:q,data2:ce,startPTS:mt,startDTS:Te,endPTS:Ft,endDTS:Ne,type:N,hasAudio:D,hasVideo:w,nb:1,dropped:0,encrypted:Zt};g.audio=D&&!w?Xe:void 0,g.video=w?Xe:void 0;let ei=this.isVideoContiguous,yi=R==null?void 0:R.sampleCount;if(yi){let ie=R.keyFrameIndex,xe=ie!==-1;Xe.nb=yi,Xe.dropped=ie===0||ei?0:xe?ie:yi,Xe.independent=xe,Xe.firstKeyFrame=ie,xe&&R.keyFrameStart&&(Xe.firstKeyFramePTS=(R.keyFrameStart-m.baseTime)/m.timescale),ei||(g.independent=xe),this.isVideoContiguous||(this.isVideoContiguous=xe),Xe.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ie}/${yi} dropped: ${Xe.dropped} start: ${Xe.firstKeyFramePTS||"NA"}`)}return g.initSegment=E,g.id3=l_(s,n,m,m),r.samples.length&&(g.text=d_(r,n,m)),g}};function pu(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function qC(i,e){let t=i,s=i;for(let r=0;r<e.length;r++){let{cts:n,duration:a}=e[r];s=Math.max(s,t+(n||0)+a),t+=a}return s}function YC(i,e,t,s){if(t!==void 0){let n=i[i.length-1],a=e;for(let o=0;o<i.length-1;o++)a-=i[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(s===void 0)return;let r=Math.round(e/i.length);for(let n=0;n<i.length;n++)i[n].duration=r;return{durationOffset:s,value:r}}function jC(i,e,t,s){if(i===null)return!0;let r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>=r}function _b(i,e,t){let s=i.codec;return s&&s.length>4?s:e===Je.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?wu(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var Tr;try{Tr=self.performance.now.bind(self.performance)}catch{Tr=Date.now}var Ru=[{demux:Pp,remux:Hp},{demux:zu,remux:ga},{demux:Cp,remux:ga},{demux:Mp,remux:ga}];Ru.splice(2,0,{demux:wp,remux:ga});var Zu=class{constructor(e,t,s,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=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){if(!this.observer)return gu(s);let n=s.transmuxing;n.executeStart=Tr();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:b,initSegmentData:E}=l,T=zC(a,t);if(T&&pa(T.method)){let x=this.getDecrypter(),k=Vg(T.method);return this.asyncResult=!0,this.decryptionPromise=x.decrypt(a,T.key.buffer,T.iv.buffer,k,s.decryptRange).then(R=>{let D=this.push(R,null,s);return this.decryptionPromise=null,D}),this.decryptionPromise}let _=this.needsProbing(u,c);if(_){let x=s.iframe&&E&&zu.probe(E,this.logger)?E:a,k=this.configureTransmuxer(x);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),n.executeEnd=Tr(),gu(s)}(u||c||m||_)&&this.resetInitSegment(E,p,g,b,t,s),(u||m||_)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let I=this.transmux(a,T,f,h,s);this.asyncResult=pl(I);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Tr(),I}flush(e){let t=e.transmuxing;t.executeStart=Tr();let{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(s){let c=s.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=Tr();let c=[gu(e)];return this.asyncResult?Promise.resolve(c):c}let u=l.flush(o,e);return pl(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){if(!this.remuxer)return;let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);let u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=Tr()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,n,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,s,r,n,a),l.resetInitSegment(e,t,s,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,s,r,n){let a;return(t==null?void 0:t.method)==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){let{demuxer:n,remuxer:a}=this;if(!n||!a)return gu(r);let o=n.demux(e,t,r,!1,!this.config.progressive),{audioTrack:l,videoTrack:d,id3Track:u,textTrack:c}=o;return{remuxResult:a.remux(l,d,u,c,t,s,!1,this.id,r,o.initData,o.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:r}=this;if(!s)return;let n;try{for(let c=0,h=Ru.length;c<h;c++){var a;if((a=Ru[c].demux)!=null&&a.probe(e,this.logger)){n=Ru[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,d=n.demux,u=n.remux;(!o||!(o instanceof d))&&(this.logger.log(`Using ${d.name}`),this.demuxer=new d(s,t,r,this.logger),this.probe=d.probe),(!l||!(l instanceof u))&&(this.logger.log(`Using ${u.name}`),this.remuxer=new u(s,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 ul(this.config)),e}};function zC(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var gu=i=>({remuxResult:{},chunkMeta:i});function pl(i){return"then"in i&&i.then instanceof Function}var Gp=class{constructor(e,t,s,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=s,this.duration=r,this.defaultInitPts=n||null}},Kp=class{constructor(e,t,s,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=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}},Ab=0,Ju=class{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ab++,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 d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.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(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=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:re.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new qg,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=Hy(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||fC()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=pC(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=mC());let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:rt(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Zu(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Zu(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Ab++;let t=this.hls.config,s=Hy(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:rt(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),gC(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,s,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,b=v?n.cc!==v.cc:!0,E=v?d.level!==v.level:!0,T=v?d.sn-v.sn:-1,_=this.part?d.part-this.part.index:-1,I=T===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),S=!E&&(T===1||T===0&&(_===1||I&&_<=0)),x=self.performance.now();(E||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(_||!S)&&(a.stats.parsing.start=x);let k=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),R=new Kp(b,S,l,E,p,k);if(!S||b||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id} playlist: ${d.level} id: ${d.id}
|
|
32
|
-
discontinuity: ${
|
|
33
|
-
trackSwitch: ${
|
|
31
|
+
${t.m3u8}`)}function KT(i,e,t=!0,s){let r=e.startSN+e.skippedSegments-i.startSN,n=i.fragments,a=r>=0,o=0;if(a&&r<n.length)o=n[r].start,s==null||s.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===i.endSN+1)o=i.fragmentEnd,s==null||s.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=i.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=i.fragmentStart,s==null||s.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return nC(e,o),o}function nC(i,e){if(e){let t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function VT(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){let s=i.fragments;if(s.length&&t*4>e){let n=s[s.length-1].duration*1e3;n>0&&n<t&&(t=n)}}else t/=2;return Math.round(t)}function WT(i,e,t){var s;if(!i)return null;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,((s=r)==null?void 0:s.sn)===e)?r:t&&e<i.startSN&&t.sn===e?t:null}function mb(i,e,t){return i?qT(i.partList,e,t):null}function qT(i,e,t){if(i)for(let s=i.length;s--;){let r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function YT(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function aC(i,e){return i!==e&&e?pb(i)!==pb(e):!1}function pb(i){return i.replace(/\?[^?]*$/,"")}function Jo(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function oC(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function gb(i,e){let t=i.start+e;i.setStart(t)}function jT(i,e){let t=e.fragments;for(let s=0,r=t.length;s<r;s++)gb(t[s],i);e.fragmentHint&&gb(e.fragmentHint,i),e.alignedSliding=!0}function Gu(i,e,t){i&&(lC(e,i,t),e.alignedSliding||dC(e,i,t),!e.alignedSliding&&!e.skippedSegments&&KT(i,e,!1,t))}function lC(i,e,t){if(!oC(e,i))return;let s=Math.min(e.endCC,i.endCC),r=Jo(e.fragments,s),n=Jo(i.fragments,s);if(!r||!n)return;let a=r.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),jT(a,i)}function dC(i,e,t){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;let s=i.fragments,r=e.fragments;if(!s.length||!r.length)return;let n,a,o=Math.min(e.endCC,i.endCC);e.startCC<o&&i.startCC<o&&(n=Jo(r,o),a=Jo(s,o)),(!n||!a)&&(n=r[Math.floor(r.length/2)]||r.filter(h=>!!h)[0],a=Jo(s,n.cc)||s[Math.floor(s.length/2)]);let l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;let u=(d-l)/1e3;if(Math.abs(u)>Math.max(60,i.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${i.totalduration})`);return}let c=u-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${c})`),jT(c,i)}function Ye(i,e,t){We(i,e,t),i.addEventListener(e,t)}function We(i,e,t){i.removeEventListener(e,t)}function Ku(i){let e="",t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}var U={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"},hl=class extends Fu{constructor(e,t,s,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=U.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:d,state:u}=this,c=l?l.currentTime:0,h=be.bufferInfo(d||l,c,a.maxBufferHole),f=h.len;if(this.log(`Media seeking to ${c}, state: ${u}, ${f?"in":"out of"} buffer`),this.state===U.ENDED)this.resetLoadingState();else if(o){let p=a.maxFragLookUpTolerance,g=o.start-p,v=o.start+o.duration+p;if(!f||v<h.start||g>h.end){let E=c<g,b=c>v;(E||b)&&(o.loader&&(b||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${E?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let p=this.lastCurrentTime;if(c>p&&(this.lastCurrentTime=c),!this.loadingParts){let g=Math.max(h.end,c),v=this.shouldLoadParts(this.getLevelDetails(),g);v&&(this.log(`LL-Part loading ON after seeking to ${c} with buffer @${g}`),this.loadingParts=v)}}let m=!be.isBuffered(l,c);(!this.hls.hasEnoughToStart||m)&&(this.log(`Setting ${m?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,m&&(this.startPosition=c)),f<1&&this.state===U.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 Nu(e.config),this.initFragmentLoader=new Nu(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ul(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===U.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=U.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.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 s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=be.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 u=l[l.length-1];return be.isBuffered(this.media,u.start+u.duration/2)}let d=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(d.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 s=this.media=this.mediaBuffer=t.media;Ye(s,"seeking",this.onMediaSeeking),Ye(s,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===U.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let s=!!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),We(r,"seeking",this.onMediaSeeking),We(r,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){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=U.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,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){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,s,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===U.FRAG_LOADING||!this.fragCurrent&&a===U.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=U.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(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===U.STOPPED||this.state===U.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:s}=this;if(s.getState(e)===ft.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))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===ft.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){let r=t.getPartialFragment(s.end);r&&(t.removeFragment(r),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.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,s=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:s};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(s=>{var r;let n=s.frag;if(!this.levels||!hp(n,(r=this.fragCurrent)==null?void 0:r.initSegment))throw new Di({type:ne.NETWORK_ERROR,details:P.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return s}).then(s=>{let{frag:r,payload:n}=s,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&pa(a.method)){let o=self.performance.now(),{decryptRange:l}=Uu(r,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Vg(a.method),l).catch(d=>{throw t.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),this.fragmentLoader.abort(),d}).then(d=>{let u=self.performance.now();return t.trigger(y.FRAG_DECRYPTED,{frag:r,part:null,payload:d,stats:{tstart:o,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}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&&Et(e)&&t&&!t.data){var s;return(t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===U.STOPPED||this.state===U.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var s,r;let n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.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:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!hp(e,t)}fragBufferedComplete(e,t){let s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Ku(be.getBuffered(s)):"(detached)"})`),Et(e)){var r;if(e.type!==te.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=U.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==ft.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=U.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let s=e.frag,{part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(d=>!d),{decryptRange:o}=Uu(s,r),l=new cl(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${r?" part: "+r.index:""} of ${this.fragInfo(s,!1,r)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){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=U.KEY_LOADING,n=this.keyLoader.load(e,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(y.KEY_LOADED,a),this.state===U.KEY_LOADING&&(this.state=U.IDLE),a}),this.hls.trigger(y.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,s=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(!zo(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(s=Math.max(e.start,s||0),this.loadingParts){let f=n.partList;if(f&&r){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);let m=this.getNextPart(f,e,s);if(m>-1){let p=f[m];if(e=this.fragCurrent=p.fragment,!zo(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,p)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(p,t.details))return Promise.resolve(null);let g=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${m}/${f.length-1}) of ${this.fragInfo(e,!1,p)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${s}${p.byteRange.length?` range:${p.byteRange.join("-")}`:""}`),this.nextLoadPosition=p.start+p.duration,this.state=U.FRAG_LOADING;let v,E=this.loadInitSegmentIfNeeded(e);if(g||E){let b=!!g;v=Promise.all([g,E]).then(([T])=>b&&(!T||this.fragContextChanged(T.frag))?null:this.doFragPartsLoad(e,p,t,r)).catch(T=>this.handleFragLoadError(T))}else v=this.doFragPartsLoad(e,p,t,r).catch(b=>this.handleFragLoadError(b));return this.hls.trigger(y.FRAG_LOADING,{frag:e,part:p,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} 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),d=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var u;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),l==null||l.catch(()=>null),d==null||d.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: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=U.FRAG_LOADING;let c=this.config.progressive&&e.type!==te.SUBTITLE,h;return c&&d?h=d.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),d,l]).then(([f])=>(!c&&r&&r(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:s}),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,s,r){return new Promise((n,a)=>{var o;let l=[],d=(o=s.details)==null?void 0:o.partList,u=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=mb(s.details,e.sn,c.index+1)||qT(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===P.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ne.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:ne.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==U.PARSING){!this.fragCurrent&&this.state!==U.STOPPED&&this.state!==U.ERROR&&(this.state=U.IDLE);return}let{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;let r=e.partList[0],n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n&&this.playhead>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=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,d=a>-1?mb(l,n,a):null,u=d?d.fragment:WT(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==U.PARSING)return;Et(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=Ci(a,o)),!l.length)return;let d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!be.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,r=be.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let r=this.playhead,a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){let n=be.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return be.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){let r=e.nextStart;if(r&&s.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<s.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t/2),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.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 s=t.fragments,r=s.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 d;l=this.getInitialLiveFragment(t);let h=this.config.startPosition,f=this.hls.startPosition,m=this.hls.liveSyncPosition,p=((d=l)==null?void 0:d.start)||0,g,v;if(f!==-1&&f>=a?(g=f,v=f===h?"config":"next load start"):m?(g=m,v="live edge"):(g=e,v="buffer pos"),g<p&&(g=p,v="live frag start"),g<a&&(g=a,v="playlist start"),this.startPosition!=g||this.nextLoadPosition!=g){let b=t.live&&!this.filterReplacedPrimary(l,t)?-1:g;this.log(`Setting startPosition to ${b} next load ${g} ${f===-1?"":`(from ${h}) `}based on ${v}. live edge: ${m} live frag start: ${p} playlist start: ${a} buffer pos: ${e}`),this.startPosition=b,this.nextLoadPosition=g}}}else e<=a&&(l=s[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);return!u&&l&&(u=PT(t,l.sn),u&&(this.nextLoadPosition=u.start)),u}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let s=this.fragmentTracker.getState(e);return!!(s===ft.OK||s===ft.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.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(Vu(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(Vu(this.config)&&("type"in e?e:e.fragment).type!==te.SUBTITLE){let s=this.hls.interstitialsManager,r=s==null?void 0:s.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(zT(e,s==null?void 0:s.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let l=0,d=e.length;l<d;l++){let u=e[l];if(a=a&&!u.independent,r>-1&&s<u.start)break;let c=u.loaded||u.gap;c?r=-1:(n||(u.independent||a)&&u.fragment===t)&&(r=l),n=c&&!u.gap}let o=e[r];return o&&o.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,r=null;if(s){if(e.hasProgramDateTime&&(r=wD(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!r){let n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=MT(e,s.cc,s.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,s){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=s,{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===ft.NOT_LOADED&&(n=null);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=Ea(n,a,e,p)}else h=a[a.length-1];if(h){let m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===ft.OK||p===ft.PARTIAL&&h.gap)&&(n=h),zo(h,n)&&(!c||u[0].fragment.sn>h.sn||!s.live)){let g=a[m+1];h.sn<o&&this.fragmentTracker.getState(g)!==ft.OK?h=g:h=null}}return h}alignPlaylists(e,t,s){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&&Q(n);if(a||!o&&!n){Gu(s,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 s=this.startPosition;s<t&&(s=-1);let r=this.timelineOffset;if(s===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&Q(a))s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){let o=this.hls.liveSyncPosition;s=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let s=(t=this.media)==null?void 0:t.currentTime;return Q(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==te.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&&Et(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!==U.FRAG_LOADING_WAITING_RETRY)&&(this.state=U.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}let{frag:s,part:r}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}let a=t.details===P.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);let o=t.errorAction;if(!o){this.state=U.ERROR;return}let{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===Gt.RetryRequest,m=h&&!o.resolved&&d&Ht.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,g=p==null?void 0:p.live;if(!f&&m&&Et(s)&&g&&s.sn<p.endSN&&!sT(t))this.resetFragmentErrors(e),r?r.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var v;let E=rl((v=t.response)==null?void 0:v.code),b=Ug(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+b,this.state=U.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${b}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==Gt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===Gt.SendAlternateToPenaltyBox?this.state=U.WAITING_LEVEL:this.state=U.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!rl(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=U.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===U.PARSING||this.state===U.PARSED){let t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),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 ${s} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,Number.POSITIVE_INFINITY,s===te.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===te.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==U.STOPPED&&(this.state=U.IDLE)}afterBufferFlushed(e,t){if(!e)return;let s=be.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===U.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==U.STOPPED&&(this.state=U.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,s,r){let n=s.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 m=f.endPTS-f.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${e.sn} ${h} duration reliably (${m})`),c||!1;let p=r.partial?0:GT(n,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:p,type:h,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var o,l,d,u;let c=((o=this.transmuxer)==null?void 0:o.error)===null,h=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((d=(u=this.levels)==null?void 0:u.length)!=null?d:0)>1;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,s),c){let m=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(m.message),this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:m,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=U.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,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN}-${(n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 s=(t=e.loader)==null?void 0:t.stats;if(!s)return!1;let r=s.loading.first>0,a=(s.total-s.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 s=0,{hls:r,media:n,config:a,levels:o,playlistType:l}=this,d=this.getLevelDetails();if(n&&!n.paused&&o){var u;let f=l===te.AUDIO?xT(e.audioCodec,128e3):e.maxBitrate,m=1+r.ttfbEstimate/1e3,p=r.bandwidthEstimate*a.abrBandWidthUpFactor,g=d&&(this.loadingParts?d.partTarget:d.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;s=m+f*g/p,e.details||(s+=m)}let c=this.playhead,h=!(d!=null&&d.live)||t.end-c>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:h}}scheduleTrackSwitch(e,t,s){let{media:r,playlistType:n}=this;if(!r||!e)return;let a=s?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let d=l.maxStartPTS?l.maxStartPTS:l.start,u=l.duration,c=Math.max(a.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>c)return;let f=n===te.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){let r=t===te.AUDIO;this.flushMainBuffer(0,s.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 U.KEY_LOADING:case U.FRAG_LOADING:case U.FRAG_LOADING_WAITING_RETRY:case U.PARSING:case U.PARSED:this.state=U.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(be.isBuffered(e,s)?t=this.getAppendedFrag(s):be.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!zo(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:s,config:r,playlistType:n}=this;if(t!=null&&t.readyState&&e&&s&&r){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;let l=n===te.AUDIO?s.nextAudioTrack:s.nextLoadLevel,d=e[l],{fetchdelay:u,okToFlushForwardBuffer:c}=this.calculateOptimalSwitchPoint(d,o);this.scheduleTrackSwitch(o,u,c)}this.tickImmediate()}};function zT(i,e,t){if(e)for(let s=e.length;s--;){let r=e[s].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace&&(i.start>=n&&i.end<=a||t>i.start&&i.end>n&&i.start<a))return!0}return!1}function Vu(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}var Wu=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=uC(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function uC(i,e){let t=new Uint8Array(e),s=0;for(let r=0;r<i.length;r++){let n=i[r];t.set(n,s),s+=n.length}return t}var Qm={exports:{}},vb;function cC(){return vb||(vb=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;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,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];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(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,E,b;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(b=1,E=new Array(v-1);b<v;b++)E[b-1]=arguments[b];g.fn.apply(g.context,E)}else{var T=g.length,_;for(b=0;b<T;b++)switch(g[b].once&&this.removeListener(d,g[b].fn,void 0,!0),v){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,u);break;case 3:g[b].fn.call(g[b].context,u,c);break;case 4:g[b].fn.call(g[b].context,u,c,h);break;default:if(!E)for(_=1,E=new Array(v-1);_<v;_++)E[_-1]=arguments[_];g[b].fn.apply(g[b].context,E)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!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!==u||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(d){var u;return d?(u=t?t+d:d,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(Qm)),Qm.exports}var hC=cC(),qg=ck(hC),fl="1.7.3",ya={};function fC(){return typeof __HLS_WORKER_BUNDLE__=="function"}function mC(){let i=ya[fl];if(i)return i.clientCount++,i;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 ya[fl]=r,r}function pC(i){let e=ya[i];if(e)return e.clientCount++,e;let t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return ya[i]=r,r}function gC(i){let e=ya[i||fl];if(e&&e.clientCount--===1){let{worker:s,objectURL:r}=e;delete ya[i||fl],r&&self.URL.revokeObjectURL(r),s.terminate()}}function vC(i,e,t,s){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 g=new Error(`invalid ADTS sampling index:${a}`);i.emit(y.ERROR,y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d=r[a],u=a;(o===5||o===29)&&(u-=3);let c,h=(u&14)>>1,f=(u&1)<<7|l<<3,m=0;if(o===1&&a>=6){m=5;let g=a-3;c=[m<<3|h,f|(g&14)>>1,(g&1)<<7|8,0]}else c=[o<<3|h,f];let p="mp4a.40."+(m||o);return $e.log(`manifest codec:${s}, parsed codec:${p}, channels:${l}, rate:${d} (ADTS object type:${o} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:d,channelCount:l,codec:p,parsedCodec:p,manifestCodec:s}}function QT(i,e){return i[e]===255&&(i[e+1]&246)===240}function XT(i,e){return i[e+1]&1?7:9}function Yg(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function EC(i,e){return e+5<i.length}function qu(i,e){return e+1<i.length&&QT(i,e)}function yC(i,e){return EC(i,e)&&QT(i,e)&&Yg(i,e)<=i.length-e}function bC(i,e){if(qu(i,e)){let t=XT(i,e);if(e+t>=i.length)return!1;let s=Yg(i,e);if(s<=t)return!1;let r=e+s;return r===i.length||qu(i,r)}return!1}function ZT(i,e,t,s,r){if(!i.samplerate){let n=vC(e,t,s,r);if(!n)return;Qe(i,n)}}function JT(i){return 1024*9e4/i}function TC(i,e){let t=XT(i,e);if(e+t<=i.length){let s=Yg(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function e_(i,e,t,s,r){let n=JT(i.samplerate),a=s+r*n,o=TC(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||i.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}var ii=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function ms(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var ml=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,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Ci(this.cachedData,e),this.cachedData=null);let s=nl(e,0),r=s?s.length:0,n,a=this._audioTrack,o=this._id3Track,l=s?Bg(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=_C(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ii.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else xk(e,r)?(s=nl(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ii.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){let u=e.slice(n);this.cachedData?this.cachedData=Ci(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:ms(),id3Track:o,textTrack:ms()}}demuxSampleAes(e,t,s){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:ms(),id3Track:this._id3Track,textTrack:ms()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},_C=(i,e,t)=>{if(Q(i))return i*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},AC=[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],SC=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],IC=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],RC=[0,1,1,4];function t_(i,e,t,s,r){if(t+24>e.length)return;let n=i_(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function i_(i,e){let t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=AC[l*14+r-1]*1e3,c=SC[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=IC[t][s],m=RC[s],p=f*8*m,g=Math.floor(f*d/c+a)*m,v=Xo();return!!v&&v<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function jg(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function s_(i,e){return e+1<i.length&&jg(i,e)}function LC(i,e){return jg(i,e)&&4<=i.length-e}function r_(i,e){if(e+1<i.length&&jg(i,e)){let s=i_(i,e),r=4;s!=null&&s.frameLength&&(r=s.frameLength);let n=e+r;return n===i.length||s_(i,n)}return!1}var Yu=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ul(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Rr.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){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,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){let a=TT(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,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(s>=n.length);s++){let a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}},Cp=class extends ml{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=nl(e,0),r=(s==null?void 0:s.length)||0;if(r_(e,r))return!1;for(let n=e.length;r<n;r++)if(bC(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return yC(e,t)}appendFrame(e,t,s){ZT(e,this.observer,t,s,e.manifestCodec);let r=e_(e,t,s,this.basePTS,this.frameIndex);if((r==null?void 0:r.missing)===0)return r}demuxSampleAes(e,t,s){let r=this.demux(e,s),n=this.sampleAes=new Yu(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(r.audioTrack.samples,0,()=>{a(r)})})}},n_=(i,e)=>{let t=0,s=5;e+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];let o=Math.min(s,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,s-=o}return t},wp=class extends ml{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){let r=a_(e,t,s,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=nl(e,0);if(!t)return!1;let s=t.length;if(e[s]===11&&e[s+1]===119&&Bg(t)!==void 0){if(n_(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function a_(i,e,t,s,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,u=[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+u>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,E=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),b=1536/o*9e4,T=s+r*b,_=e.subarray(t,t+u);return i.config=E,i.channelCount=p,i.samplerate=o,i.samples.push({unit:_,pts:T}),u}var Mp=class extends ml{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=nl(e,0),s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Bg(t)!==void 0&&n_(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(r_(e,s))return $e.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return LC(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return t_(e,t,s,this.basePTS,this.frameIndex)}},xC=/\/emsg[-/]ID3/i,Pp=class{constructor(e,t,s,r=$e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=r}resetTimeStamp(){}resetInitSegment(e,t,s,r){let n=this.videoTrack=ms("video",1),a=this.audioTrack=ms("audio",1),o=this.txtTrack=ms("text",1);if(this.id3Track=ms("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=gT(e);if(l.video){let{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){let{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=hT.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Kk(e,"moof")}demux(e,t,s){this.timeOffset=t;let r=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Ci(this.remainderData,e));let d=Jk(r);this.remainderData=d.remainder,n.samples=d.valid||new Uint8Array}else n.samples=r;let o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,s);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let s=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,s,t);return{videoTrack:r,audioTrack:ms(),id3Track:a,textTrack:ms(),initData:this.initData,sampleData:o}}parseFragment(e,t,s,r){let n=this.initData;if(n&&r){let{samples:a,sampleData:o}=Zk(s,e,n,this.logger,r.iframe);return t.samples=a,o}t.samples=eD(s,e)}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let r=Ee(e.samples,["emsg"]);r&&r.forEach(n=>{let a=tD(n);if(xC.test(a.schemeIdUri)){let o=Eb(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:ii.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||ii.misbklv;if(a.schemeIdUri.startsWith(o)){let l=Eb(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:ii.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function Eb(i,e){return Q(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}var kC=1,DC=2,qo=-1,ju=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,r=s.length;if(r){let n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let r=t.byteLength;if(r===0)return[];let n=e.naluState||0,a=n===qo?0:n,o=[],l=0,d=0,u=-1,c=0;for(n===qo&&(u=0,c=this.getNALuType(t,0),d=1);d<r;){let h=t.indexOf(kC,d);if(h===-1)break;d=h+1;let f=h;for(;f>0&&t[f-1]===0;)f--;if(!(h-f+(f===0?a:0)<DC)){if(u>=0)o.push({data:t.subarray(u,f),type:c});else{let p=this.getLastNalUnit(e.samples);p&&(f>0?p.data=Ci(p.data,t.subarray(0,f)):a>0&&(p.data=p.data.subarray(0,p.data.byteLength-a)),p.state=0)}if(d<r)u=d,c=this.getNALuType(t,d);else{l=qo,u=-1;break}}}if(l!==qo){let h=r;for(;h>0&&t[h-1]===0;)h--;l=r-h+(h===0?a:0)}if(u>=0)o.push({data:t.subarray(u),type:c,state:l});else if(o.length===0&&l!==qo){let h=this.getLastNalUnit(e.samples);h&&(h.data=Ci(h.data,t),h.state=l)}return e.naluState=l,o}},bn=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,s=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(s,s+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),s=this.word>>>32-t;if(e>32&&$e.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?s<<t|this.readBits(t):s}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)}},Op=class extends ju{parsePES(e,t,s,r,n){let a=n.iframe,o=this.parseNALu(e,s.data,r),l=this.VideoSample,d,u=!1;s.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(c=>{var h,f;switch(c.type){case 1:{if(a)break;let v=!1;d=!0;let E=c.data;if(u&&E.length>4){let b=this.readSliceType(E);(b===2||b===4||b===7||b===9)&&(v=!0)}if(v){var m;(m=l)!=null&&m.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=v;break}case 5:d=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;d=!0,al(c.data,1,s.pts,t.samples);break}case 7:{var p,g;d=!0,u=!0;let v=c.data,E=this.readSPS(v);if(!e.sps||e.width!==E.width||e.height!==E.height||((p=e.pixelRatio)==null?void 0:p[0])!==E.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[v];let b=v.subarray(1,4),T="avc1.";for(let _=0;_<3;_++){let I=b[_].toString(16);I.length<2&&(I="0"+I),T+=I}e.codec=T}break}case 8:d=!0,e.pps=[c.data];break;case 9:d=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:d=!0;break;default:d=!1;break}l&&d&&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 bn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){let t=new bn(e),s=0,r=0,n=0,a=0,o,l,d,u=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);u();let E=u();if(c(5),m(3),u(),g(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){let x=h();if(x===3&&m(1),g(),g(),m(1),f())for(l=x!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}g();let b=h();if(b===0)h();else if(b===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();g(),m(1);let T=h(),_=h(),I=c(1);I===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let S=[1,1];if(f()&&f())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-s*2-r*2),height:(2-I)*(_+1)*16-(I?2:4)*(n+a),pixelRatio:S}}},Np=class extends ju{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null;let d=u=>(a=this.VideoSample=this.createVideoSample(u,s.pts,s.dts),a);n.forEach((u,c)=>{var h,f;if(this.startsNewAccessUnit(a,e,u,c)){this.pushAccessUnit(a,e);let p=u.type>=16&&u.type<=23;a=d(p),l=!1}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=d(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var m;(m=a)!=null&&m.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=d(!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=d(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,al(u.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Qe(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 p=this.readSPS(u.data);e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.codec=p.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let g in p.params)e.params[g]=p.params[g]}this.pushParameterSet(e.sps,u.data,e.vps),a||(a=d(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let p=this.readPPS(u.data);for(let g in p)e.params[g]=p[g]}this.pushParameterSet(e.pps,u.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=d(!1));break;default:o=!1;break}a&&o&&a.units.push(u)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,r){if(!e)return!1;if(!t.audFound&&r===0)return!0;if(!e.frame)return!1;let{type:n,data:a}=s;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),s=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new bn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){let t=new bn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),E=[],b=[];for(let ie=0;ie<s;ie++)E.push(t.readBoolean()),b.push(t.readBoolean());if(s>0)for(let ie=s;ie<8;ie++)t.readBits(2);for(let ie=0;ie<s;ie++)E[ie]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),b[ie]&&t.readUByte();t.readUEG();let T=t.readUEG();T==3&&t.skipBits(1);let _=t.readUEG(),I=t.readUEG(),S=t.readBoolean(),x=0,k=0,R=0,D=0;S&&(x+=t.readUEG(),k+=t.readUEG(),R+=t.readUEG(),D+=t.readUEG());let w=t.readUEG(),N=t.readUEG(),$=t.readUEG(),H=t.readBoolean();for(let ie=H?0:s;ie<=s;ie++)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 xe=0;xe<4;xe++)for(let we=0;we<(xe===3?2:6);we++)if(!t.readBoolean())t.readUEG();else{let gt=Math.min(64,1<<4+(xe<<1));xe>1&&t.readEG();for(let Ie=0;Ie<gt;Ie++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let B=t.readUEG(),W=0;for(let ie=0;ie<B;ie++){let xe=!1;if(ie!==0&&(xe=t.readBoolean()),xe){ie===B&&t.readUEG(),t.readBoolean(),t.readUEG();let we=0;for(let pt=0;pt<=W;pt++){let gt=t.readBoolean(),Ie=!1;gt||(Ie=t.readBoolean()),(gt||Ie)&&we++}W=we}else{let we=t.readUEG(),pt=t.readUEG();W=we+pt;for(let gt=0;gt<we;gt++)t.readUEG(),t.readBoolean();for(let gt=0;gt<pt;gt++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let ie=t.readUEG();for(let xe=0;xe<ie;xe++){for(let we=0;we<$+4;we++)t.readBits(1);t.readBits(1)}}let K=0,q=1,ce=1,re=!0,ye=1,ue=0;t.readBoolean(),t.readBoolean();let Ce=!1;if(t.readBoolean()){if(t.readBoolean()){let Wt=t.readUByte(),Gs=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Pt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Wt>0&&Wt<16?(q=Gs[Wt-1],ce=Pt[Wt-1]):Wt===255&&(q=t.readBits(16),ce=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(),Ce=t.readBoolean(),Ce&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ye=t.readBits(32),ue=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Pt=t.readBoolean(),qt=t.readBoolean(),di=!1;(Pt||qt)&&(di=t.readBoolean(),di&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),di&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ti=0;ti<=s;ti++){re=t.readBoolean();let Bt=re||t.readBoolean(),ls=!1;Bt?t.readEG():ls=t.readBoolean();let vt=ls?1:t.readUEG()+1;if(Pt)for(let je=0;je<vt;je++)t.readUEG(),t.readUEG(),di&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(qt)for(let je=0;je<vt;je++)t.readUEG(),t.readUEG(),di&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Ne=_,mt=I;if(S){let ie=1,xe=1;T===1?ie=xe=2:T==2&&(ie=2),Ne=_-ie*k-ie*x,mt=I-xe*D-xe*R}let Ft=r?["A","B","C"][r]:"",Zt=o<<24|l<<16|d<<8|u,Xe=0;for(let ie=0;ie<32;ie++)Xe=(Xe|(Zt>>ie&1)<<31-ie)>>>0;let ei=Xe.toString(16);return a===1&&ei==="2"&&(ei="6"),{codecString:`hvc1.${Ft}${a}.${ei}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:K,chroma_format_idc:T,frame_rate:{fixed:re,fps:ue/ye}},width:Ne,height:mt,pixelRatio:[q,ce]}}readPPS(e){let t=new bn(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 ji(e).substring(3)===ji(t).substring(3)}},Dt=188,zu=class i{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){let s=i.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(Dt*5,t-Dt)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Dt)if(e[l]===71&&(t-l===Dt||e[l+Dt]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Dt*99,e.length-Dt)+1)),n||(n=Qu(e,l)===0),n&&o>1&&(a===0&&o>2||l+Dt>s))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:hT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=i.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Fp(this.logger):null,this._audioTrack=i.createTrack("audio",r),this._id3Track=i.createTrack("id3"),this._txtTrack=i.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,e&&this.demux(e,0,a,(n==null?void 0:n.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s,r=!1,n=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,d=this._audioTrack,u=this._id3Track,c=this._txtTrack,h=s.iframe,f=o.pid,m=o.pesData,p=d.pid,g=u.pid,v=this._klvPid,E=d.pesData,b=u.pesData,T=null,_=null,I=this.pmtParsed,S=this._pmtId,x=e.length;if(this.remainderData&&(e=Ci(this.remainderData,e),x=e.length,this.remainderData=null),x<Dt&&!n)return this.remainderData=e,{audioTrack:d,videoTrack:o,id3Track:u,textTrack:c};let k=Math.max(0,i.syncOffset(e));x-=(x-k)%Dt,x<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let R=0;for(let w=k;w<x;w+=Dt)if(e[w]===71){let N=!!(e[w+1]&64),$=Qu(e,w),H=(e[w+3]&48)>>4,O;if(H>1){if(O=w+5+e[w+4],O===w+Dt)continue}else O=w+4;switch($){case f:N&&(m&&!(l!=null&&l.isCorrupted)&&(a=pn(m,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,a,!1,s)),m={data:[],size:0},l==null||l.reset(f)),l==null||l.handlePacket(e.subarray(w)),m&&(m.data.push(e.subarray(O,w+Dt)),m.size+=w+Dt-O);break;case p:if(h)break;if(N){if(E&&(a=pn(E,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,a,s);break;case"mp3":this.parseMPEGPES(d,a);break;case"ac3":this.parseAC3PES(d,a);break}E={data:[],size:0}}E&&(E.data.push(e.subarray(O,w+Dt)),E.size+=w+Dt-O);break;case g:if(h)break;N&&(b&&(a=pn(b,this.logger))&&this.parseID3PES(u,a),b={data:[],size:0}),b&&(b.data.push(e.subarray(O,w+Dt)),b.size+=w+Dt-O);break;case v:if(h)break;N&&(T&&(a=pn(T,this.logger))&&this.parseKlvPES(u,a),T={data:[],size:0}),T&&(T.data.push(e.subarray(O,w+Dt)),T.size+=w+Dt-O);break;case 0:N&&(O+=e[O]+1),S=this._pmtId=CC(e,O);break;case S:{N&&(O+=e[O]+1);let F=wC(e,O,this.typeSupported,r,this.observer,this.logger,this.config,s);f=F.videoPid,f>0&&(o.pid=f,o.segmentCodec=F.segmentVideoCodec),p=F.audioPid,p>0&&(d.pid=p,d.segmentCodec=F.segmentAudioCodec),g=F.id3Pid,g>0&&(u.pid=g),v=F.klvPid,v>0&&(this._klvPid=v),_!==null&&!I&&(this.logger.warn(`MPEG-TS PMT found at ${w} after unknown PID '${_}'. Backtracking to sync byte @${k} to parse all TS packets.`),_=null,w=k-188),I=this.pmtParsed=!0;break}case 17:case 8191:break;default:_=$;break}}else R++;R>0&&Up(this.observer,new Error(`Found ${R} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=m,d.pesData=E,u.pesData=b;let D={audioTrack:d,videoTrack:o,id3Track:u,textTrack:c};return n&&this.extractRemainingSamples(D,s),D}flush(e,t){let{remainderData:s}=this;this.remainderData=null;let r;return s?r=this.demux(s,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:s,videoTrack:r,id3Track:n,textTrack:a}=e,o=r.pesData,l=s.pesData,d=n.pesData,u=this.videoIntegrityChecker,c;if(o&&!(u!=null&&u.isCorrupted)&&(c=pn(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=pn(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c,t);break;case"mp3":this.parseMPEGPES(s,c);break;case"ac3":this.parseAC3PES(s,c);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;d&&(c=pn(d,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=d}demuxSampleAes(e,t,s,r){let n=this.demux(e,s,r,!0,!this.config.progressive),a=this.sampleAes=new Yu(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Op:e==="hevc"&&(this.videoParser=new Np))}decrypt(e,t){return new Promise(s=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){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=Ci(n.sample.unit,a);else{let m=f-h;n.sample.unit.set(a.subarray(0,h),m),e.samples.push(n.sample),r=n.missing}}let o,l;for(o=r,l=a.length;o<l-1&&!qu(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",Up(this.observer,new Error(h),s,f,this.logger),!f)return}ZT(e,this.observer,a,o,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(n){let h=JT(e.samplerate);d=n.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let u=0,c;for(;o<l;)if(c=e_(e,a,o,d,u),o+=c.length,c.missing){this.aacOverFlow=c;break}else for(u++;o<l-1&&!qu(a,o);o++);}parseMPEGPES(e,t){let s=t.data,r=s.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(s_(s,a)){let l=t_(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=s.length,a=0,o=0,l;for(;o<n&&(l=a_(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=Qe({},t,{type:this._videoTrack?ii.emsg:ii.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;let r=(s=t.pts)!=null?s: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 d=n[a];a+=1;let u=0;if(d&128){let m=d&127;if(m===0||m>4||a+m>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let p=0;p<m;p++)u=u<<8|n[a+p];a+=m}else u=d;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let c=a+u,h=n.subarray(l,c),f={data:h,len:h.byteLength,pts:r,dts:(o=t.dts)!=null?o:r,type:ii.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=c}}};function Qu(i,e){return((i[e+1]&31)<<8)+i[e+2]}function CC(i,e){return(i[e+10]&31)<<8|i[e+11]}function wC(i,e,t,s,r,n,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(i[e+1]&15)<<8|i[e+2],u=e+3+d-4,c=(i[e+10]&15)<<8|i[e+11];for(e+=12+c;e<u;){let h=Qu(i,e),f=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Xm("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(!s){Xm("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(!s){Xm("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 m=e+5,p=f;for(;p>2;){switch(i[m]){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 v=i[m+1]+2;m+=v,p-=v}}break;case 194:case 135:return Up(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 Up(i,e,t,s,r){r.warn(`parsing error: ${e.message}`),i.emit(y.ERROR,y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:t,error:e,reason:e.message})}function Xm(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function pn(i,e){let t=0,s,r,n,a,o,l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ci(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;let u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[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=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;let h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var Fp=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=Qu(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let s=(e[3]&48)>>4;if(s===0)return;let r=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=r;let a=(s&1)!=0;if((s&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;let d=a?n+1&15:n;if(r!==d){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${d} 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}}},Bp=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}}},Xu,MC={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])},Zm=new Uint8Array([0,0,0,0,0,0,0,0]),PC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),OC=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),NC=new Uint8Array([0,0,0,0,0,0,0,0]),Yo=new Uint8Array([0,0,0,0,0,0,0,1]),yb=new Uint8Array([105,115,111,109]),UC=new Uint8Array([97,118,99,49]),FC=new Uint8Array([0,0,0,1]),Ys=class i{static box(e,...t){let s=8,r=t.length,n=r;for(;r--;)s+=t[r].byteLength;let a=new Uint8Array(s);for(At(a,0,s),At(a,4,e),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return i.box(me.hdlr,MC[e])}static mdat(e){return i.box(me.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(hs+1)),r=Math.floor(t%(hs+1));return i.box(me.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,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return i.box(me.mdia,i.mdhd(e.timescale||0,e.duration||0),i.hdlr(e.type),i.minf(e))}static mfhd(e){return i.box(me.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?i.box(me.minf,i.box(me.smhd,NC),i.DINF,i.stbl(e)):i.box(me.minf,i.box(me.vmhd,OC),i.DINF,i.stbl(e))}static moof(e,t,s){return i.box(me.moof,i.mfhd(e),i.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=i.trak(e[t]);return i.box.apply(null,[me.moov,i.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(i.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=i.trex(e[t]);return i.box.apply(null,[me.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(hs+1)),r=Math.floor(t%(hs+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,s>>24,s>>16&255,s>>8&255,s&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 i.box(me.mvhd,n)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return i.box(me.sdtp,s)}static stbl(e){return i.box(me.stbl,i.stsd(e),i.box(me.stts,Zm),i.box(me.stsc,Zm),i.box(me.stsz,PC),i.box(me.stco,Zm))}static avc1(e){let t=[],s=[],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,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));let o=i.box(me.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return i.box(me.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,d>>8&255,d&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,i.box(me.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(me.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){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 i.box(me.mp4a,i.audioStsd(e),i.box(me.esds,i.esds(e)))}static mp3(e){return i.box(me[".mp3"],i.audioStsd(e))}static ac3(e){return i.box(me["ac-3"],i.audioStsd(e),i.box(me.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return i.box(me.stsd,Yo,i.mp4a(e));if(t==="ac3"&&e.config)return i.box(me.stsd,Yo,i.ac3(e));if(t==="mp3"&&e.codec==="mp3")return i.box(me.stsd,Yo,i.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return i.box(me.stsd,Yo,i.avc1(e));if(t==="hevc"&&e.vps)return i.box(me.stsd,Yo,i.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,s=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(s/(hs+1)),o=Math.floor(s%(hs+1));return i.box(me.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 s=i.sdtp(e),r=e.id,n=Math.floor(t/(hs+1)),a=Math.floor(t%(hs+1));return i.box(me.traf,i.box(me.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),i.box(me.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])),i.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,i.box(me.trak,i.tkhd(e),i.mdia(e))}static trex(e){let t=e.id;return i.box(me.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 s=e.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n),o,l,d,u,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=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&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 i.box(me.trun,a)}static initSegment(e){let t=i.moov(e);return Ci(i.FTYP,t)}static hvc1(e){let t=e.params,s=[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),s.length]),a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}let d=i.box(me.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return i.box(me.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,u>>8&255,u&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]),d,i.box(me.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(me.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Xu=Ys;Ys.FTYP=Xu.box(me.ftyp,yb,FC,yb,UC);Ys.DINF=Xu.box(me.dinf,Xu.box(me.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var o_=9e4;function zg(i,e,t=1,s=!1){let r=i*e*t;return s?Math.round(r):r}function BC(i,e,t=1,s=!1){return zg(i,e,1/t,s)}function jo(i,e=!1){return zg(i,1e3,1/o_,e)}function $C(i,e=1){return zg(i,o_,1/e)}function bb(i){let{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}var HC=10*1e3,GC=1024,KC=1152,VC=1536,$p=8589934592;function Tb(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1,paddingValue:0}}}var ga=class extends si{constructor(e,t,s,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=s,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&&bb(t)} > ${e&&bb(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,s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=Ai(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l,d){let u,c,h,f,m,p,g=n,v=n,b=!d.iframe&&e.pid>-1,T=t.pid>-1,_=t.samples.length,I=e.samples.length>0,S=o&&_>0||_>1;if((!b||I)&&(!T||S)||this.ISGenerated||o){if(this.ISGenerated){var k,R,D,w;let O=this.videoTrackConfig;(O&&(t.width!==O.width||t.height!==O.height||((k=t.pixelRatio)==null?void 0:k[0])!==((R=O.pixelRatio)==null?void 0:R[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((w=O.pixelRatio)==null?void 0:w[1]))||!O&&S||this.nextAudioTs===null&&I)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));let N=this.isVideoContiguous,$=-1,H;if(S&&($=WC(t.samples),!N&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,$>0){this.warn(`Dropped ${$} out of ${_} video samples due to a missing keyframe`);let O=this.getVideoStartPts(t.samples);t.samples=t.samples.slice($),t.dropped+=$,v+=(t.samples[0].pts-O)/t.inputTimeScale,H=v}else $===-1&&(this.warn(`No keyframe found out of ${_} video samples`),p=!1);if(this.ISGenerated){if(I&&S&&n){let O=this.getVideoStartPts(t.samples),B=(Ai(e.samples[0].pts,O)-O)/t.inputTimeScale;g+=Math.max(0,B),v+=Math.max(0,-B)}if(I){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,g,this.isAudioContiguous,a,T||S||l===te.AUDIO?v:void 0,d),S){let O=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,v,N,O,d)}}else S&&(u=this.remuxVideo(t,v,N,0,d));u&&(u.firstKeyFrame=$,u.independent=$!==-1,u.firstKeyFramePTS=H)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(m=l_(s,n,this._initPTS,this._initDTS)),r.samples.length&&(f=d_(r,n,this._initPTS))),{audio:c,video:u,initSegment:h,independent:p,text:f,id3:m}}computeInitPts(e,t,s,r){let n=Math.round(s*t),a=Ai(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n;)a+=$p;return a-n}generateIS(e,t,s,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(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):Ys.initSegment([e]),metadata:{channelCount:e.channelCount}},u){p=e.id,m=e.inputTimeScale;let g=this.computeInitPts(n[0].pts,m,s,"audio");(!d||m!==d.timescale||s===0&&g<d.baseTime)&&(h=f=g)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ys.initSegment([t]),metadata:{width:t.width,height:t.height}},u){p=t.id,m=t.inputTimeScale;let g=this.getVideoStartPts(a),v=Ai(a[0].dts,g),E=this.computeInitPts(v,m,s,"video"),b=this.computeInitPts(g,m,s,"video");(!d||m!==d.timescale||Q(h)||s===0&&b<d.baseTime)&&(f=Math.min(f,E),h=Math.min(h,E))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u&&Q(h)?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} 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,s,r,n){let a=e.inputTimeScale,o=e.samples,l=[],d=o.length,u=this._initPTS,c=u.baseTime*a/u.timescale,h=this.nextVideoTs,f=8,m=this.videoSampleDuration,p,g,v=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,b=!1;if(!s||h===null){let K=c+t*a,q=o[0].pts-Ai(o[0].dts,o[0].pts);Xo()&&h!==null&&Math.abs(K-q-(h+c))<15e3?s=!0:h=K-q-c}let T=h+c;for(let K=0;K<d;K++){let q=o[K];q.pts=Ai(q.pts,T),q.dts=Ai(q.dts,T),q.dts<o[K>0?K-1:K].dts&&(b=!0)}b&&o.sort(function(K,q){let ce=K.dts-q.dts,re=K.pts-q.pts;return ce||re}),p=o[0].dts,g=o[o.length-1].dts;let _=g-p,I=_?Math.round(_/(d-1)):m||e.inputTimeScale/30;if(s){let K=p-T,q=K>I,ce=K<-1;if((q||ce)&&(q?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jo(K,!0)} ms (${K}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jo(-K,!0)} ms (${K}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ce||T>=o[0].pts||Xo())){p=T;let re=o[0].pts-K;if(q)o[0].dts=p,o[0].pts=re;else{let ye=!0;for(let ue=0;ue<o.length&&!(o[ue].dts>re&&ye);ue++){let Ce=o[ue].pts;if(o[ue].dts-=K,o[ue].pts-=K,ue<o.length-1){let Te=o[ue+1].pts,Ne=o[ue].pts,mt=Te<=Ne,Ft=Te<=Ce;ye=mt==Ft}}}this.log(`Video: Initial PTS/DTS adjusted: ${jo(re,!0)}/${jo(p,!0)}, delta: ${jo(K,!0)} ms`)}}p=Math.max(0,p);let S=0,x=0,k=p;for(let K=0;K<d;K++){let q=o[K],ce=q.units,re=ce.length,ye=0;for(let ue=0;ue<re;ue++)ye+=ce[ue].data.length;x+=ye,S+=re,q.length=ye,q.dts<k?(q.dts=k,k+=I/4|0||1):k=q.dts,v=Math.min(q.pts,v),E=Math.max(q.pts,E)}g=o[d-1].dts;let R=x+4*S+8,D;try{D=new Uint8Array(R)}catch(K){this.observer.emit(y.ERROR,y.ERROR,{type:ne.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:K,bytes:R,reason:`fail allocating video mdat ${R}`});return}At(D,0,R),At(D,4,me.mdat);let w=!1,N=Number.POSITIVE_INFINITY,$=Number.POSITIVE_INFINITY,H=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let K=0;K<d;K++){let q=o[K],ce=q.units,re=0;for(let Ce=0,Te=ce.length;Ce<Te;Ce++){let Ne=ce[Ce],mt=Ne.data,Ft=Ne.data.byteLength;At(D,f,Ft),f+=4,D.set(mt,f),f+=Ft,re+=4+Ft}let ye;if(K<d-1)m=o[K+1].dts-q.dts,ye=o[K+1].pts-q.pts;else{let Ce=this.config,Te=K>0?q.dts-o[K-1].dts:I;if(ye=K>0?q.pts-o[K-1].pts:I,Ce.stretchShortVideoTrack&&this.nextAudioTs!==null){let Ne=Math.floor(Ce.maxBufferHole*a),mt=(r?v+r*a:this.nextAudioTs+c)-q.pts;mt>Ne?(m=mt-Te,m<0?m=Te:w=!0,this.log(`It is approximately ${mt/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=Te}else m=Te}let ue=Math.round(q.pts-q.dts);if(N=Math.min(N,m),H=Math.max(H,m),$=Math.min($,ye),O=Math.max(O,ye),!s&&K===0&&ue>m){let Ce=Math.round(ue/I)*I;Ce-ue===1&&(this.log(`pad first CTS ${ue} -> ${Ce} of sn: ${n.sn}`),ue=Ce)}l.push(Tb(q.key,m,re,ue))}if(l.length){let K=Xo();if(K){if(K<70){let q=l[0].flags;q.dependsOn=2,q.isNonSync=0}}else if(oD()&&O-$<H-N&&I/H<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let q=p;for(let ce=0,re=l.length;ce<re;ce++){let ye=q+l[ce].duration,ue=q+l[ce].cts;if(ce<re-1){let Ce=ye+l[ce+1].cts;l[ce].duration=Ce-ue}else l[ce].duration=ce?l[ce-1].duration:I;l[ce].cts=0,q=ye}}}m=w||!m?I:m;let F=g+m;this.nextVideoTs=h=F-c,this.videoSampleDuration=m,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=m=n.duration*a,this.nextVideoTs=h=p+m-c):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let Z={data1:Ys.moof(n.sn,p,Qe(e,{samples:l})),data2:D,startPTS:(v-c)/a,endPTS:(E+m-c)/a,startDTS:(p-c)/a,endDTS:h/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Z}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return KC;case"ac3":return VC;default:return GC}}remuxAudio(e,t,s,r,n,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,d=o/l,u=this.getSamplesPerFrame(e),c=u*d,h=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,m=[],p=n!==void 0,g=e.samples,v=f?0:8,E=this.nextAudioTs||-1,b=h.baseTime*o/h.timescale,T=b+t*o;if(this.isAudioContiguous=s=s||g.length&&E>0&&(r&&Math.abs(T-(E+b))<9e3||Math.abs(Ai(g[0].pts,T)-(E+b))<20*c),g.forEach(function(F){F.pts=Ai(F.pts,T)}),!s||E<0){let F=g.length;if(g=g.filter(B=>B.pts>=0),F!==g.length&&this.warn(`Removed ${g.length-F} of ${F} samples (initPTS ${b} / ${o})`),!g.length)return;n===0?E=0:r&&!p?E=Math.max(0,T-b):E=g[0].pts-b}if(e.segmentCodec==="aac"){let F=this.config.maxAudioFramesDrift;for(let B=0,W=E+b;B<g.length;B++){let Z=g[B],K=Z.pts,q=K-W,ce=Math.abs(1e3*q/o);if(q<=-F*c&&p)B===0&&(this.warn(`Audio frame @ ${(K/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*q/o)} ms.`),this.nextAudioTs=E=K-b,W=K);else if(q>=F*c&&ce<HC&&p){let re=Math.round(q/c);for(W=K-re*c;W<0&&re&&c;)re--,W+=c;B===0&&(this.nextAudioTs=E=W-b),this.warn(`Injecting ${re} audio frames @ ${((W-b)/o).toFixed(3)}s due to ${Math.round(1e3*q/o)} ms gap.`);for(let ye=0;ye<re;ye++){let ue=Bp.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ue||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ue=Z.unit.subarray()),g.splice(B,0,{unit:ue,pts:W}),W+=c,B++}}Z.pts=W,W+=c}}let _=null,I=null,S,x=0,k=g.length;for(;k--;)x+=g[k].unit.byteLength;for(let F=0,B=g.length;F<B;F++){let W=g[F],Z=W.unit,K=W.pts;if(I!==null){let ce=m[F-1];ce.duration=Math.round((K-I)/d)}else if(s&&e.segmentCodec==="aac"&&(K=E+b),_=K,x>0){x+=v;try{S=new Uint8Array(x)}catch(ce){this.observer.emit(y.ERROR,y.ERROR,{type:ne.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:ce,bytes:x,reason:`fail allocating audio mdat ${x}`});return}f||(At(S,0,x),At(S,4,me.mdat))}else return;S&&S.set(Z,v);let q=Z.byteLength;v+=q,m.push(Tb(!0,u,q,0)),I=K}let R=m.length;if(!R)return;let D=m[m.length-1];E=I-b,this.nextAudioTs=E+d*D.duration;let w=f?new Uint8Array(0):Ys.moof(e.sequenceNumber++,_/d,Qe({},e,{samples:m}));e.samples=[];let N=(_-b)/o,$=this.nextAudioTs/o,O={data1:w,data2:S,startPTS:N,endPTS:$,startDTS:N,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,O}};function Ai(i,e){let t;if(e===null)return i;for(e<i?t=-$p:t=$p;Math.abs(i-e)>4294967296;)i+=t;return i}function WC(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function l_(i,e,t,s){let r=i.samples.length;if(!r)return;let n=i.inputTimeScale;for(let o=0;o<r;o++){let l=i.samples[o];l.pts=Ai(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ai(l.dts-s.baseTime*n/s.timescale,e*n)/n}let a=i.samples;return i.samples=[],{samples:a}}function d_(i,e,t){let s=i.samples.length;if(!s)return;let r=i.inputTimeScale;for(let a=0;a<s;a++){let o=i.samples[a];o.pts=Ai(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);let n=i.samples;return i.samples=[],{samples:n}}var Hp=class extends si{constructor(e,t,s,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,s,r){this.audioCodec=t,this.videoCodec=s,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){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=s||gT(e);if(t)Yk(e,t);else{let d=a||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}a&&(r=_b(a,Je.AUDIO,this)),o&&(n=_b(o,Je.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,s,r,n,a,o,l,d,u,c){var h,f;let{initPTS:m,lastEndTime:p}=this,g={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Q(p)||(p=this.lastEndTime=n||0);let v=t.samples;if(!v.length)return g;let E=this.pendingInitSegment;E&&(this.pendingInitSegment=void 0,this.generateInitSegment(E,this.decryptdata,u));let b={initPTS:void 0,timescale:void 0,trackId:void 0},T=this.initData;if((h=T)!=null&&h.length||(this.generateInitSegment(v),T=this.initData),!((f=T)!=null&&f.length))return this.warn("Failed to generate initSegment."),g;if(d.iframe&&T.audio&&T.video){var _;let ie=(_=this.initTracks)==null||(_=_.audiovideo)==null?void 0:_.initSegment,xe=ie?Hk(ie):null;if(xe){var I;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(xe,this.decryptdata),(I=this.initData)!=null&&I.length&&(T=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(b.tracks=this.initTracks,g.initSegment=b,this.emitInitSegment=!1);let S=d.iframe,x=c&&(!S||c.includeSampleDetails)?c.tracks:Xk(v,T,d,this,S),k=T.audio?x[T.audio.id]:null,R=T.video?x[T.video.id]:null,D=!!T.audio,w=!!T.video,N="";D&&(N+="audio"),w&&(N+="video");let $=pu(R,1/0),H=pu(k,1/0),O=pu(R,0,!0),F=pu(k,0,!0),B=n,W=0;R&&k&&T.audio&&(H>O||$>F)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${$}-${O} a: ${H}-${F}}`,R,k);let Z=!!k&&(!R||!m&&H<$||!!m&&m.trackId===T.audio.id),K=Z?k:R;if(!K)return this.log(`No media samples found in ${l} ${d.level} ${d.part===-1?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${n}`),g;let q=v,ce,re;if(R&&R.sampleCount>=1&&T.video&&d.iframe){let{trun:ie,start:xe}=R,we=ie.length===1,pt=ie.length?we?ie[0].samples:ie[0].samples.concat(...ie.slice(1).map(gt=>gt.samples)):[];if(pt.length){let gt=ie[0],Ie=gt;for(let ti=ie.length;ti--;)if(ie[ti].samples.length){Ie=ie[ti];break}let Wt=Ie.lastSampleDurationOffset,{defaultSampleDurationOffset:Gs}=gt,Pt=Math.abs(d.duration-(O-$))>.05,qt=pt.length<R.sampleCount;if(!(Pt||qt||this.videoOnlyRemux||!we))W=O-$;else{let ti=qt?Ie.sampleOffset+Ie.samples.reduce((je,un)=>je+un.size,0):void 0,Bt=Pt?d.duration:O-$,ls=YC(pt,Bt*T.video.timescale,Wt,Gs),vt=Gk(v,T.video.id,pt.length,ti,ls);vt?(q=vt,re=qC(xe,pt)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),W=vt&&ls?Bt:O-$}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${ie.length})`),W=O-$}else W=Z?F-H:O-$;if(this.videoOnlyRemux&&q===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),g;let ye=K.timescale,ue=K.start-n*ye,Ce=Z?T.audio.id:T.video.id;if(B=K.start/ye,(a||!m)&&(jC(m,B,n,W)||ye!==m.timescale)){let ie=!1,xe=Z?"audio":"video";if(m){let we=n!==0?B/n:1+B/1;ie=B>=0&&Math.abs(1-we)<.001,this.log(`${xe} timestamps in track ${Ce} at playlist time: ${a?"":"~"}${n} maps to ${B} with initPTS: ${m.baseTime/m.timescale} (${ue/ye-m.baseTime/m.timescale}s diff) (${N}) drift estimate: ${we} ${ie?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}ie||(this.log(`Found initPTS in ${xe} track ${Ce} at playlist time: ${n} offset: ${B-n} (${ue}/${ye})`),m=null,b.initPTS=ue,b.timescale=ye,b.trackId=Ce)}m?(b.initPTS=m.baseTime,b.timescale=m.timescale,b.trackId=m.trackId):((!b.timescale||b.trackId===void 0||b.initPTS===void 0)&&(this.warn("Could not set initPTS"),b.initPTS=B,b.timescale=1,b.trackId=-1),this.initPTS=m={baseTime:b.initPTS,timescale:b.timescale,trackId:b.trackId});let Te=B-m.baseTime/m.timescale,Ne=Te+W,mt=w&&(K==null?void 0:K.ptsMin)!==void 0?K.ptsMin/K.timescale-m.baseTime/m.timescale:Te,Ft=re!==void 0&&R?re/R.timescale-m.baseTime/m.timescale:w&&K!=null&&K.ptsMax?K.ptsMax/K.timescale-m.baseTime/m.timescale:Ne;W>0?this.lastEndTime=Ne:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let Zt=(T.audio?T.audio.encrypted:!1)||(T.video?T.video.encrypted:!1),Xe={data1:q,data2:ce,startPTS:mt,startDTS:Te,endPTS:Ft,endDTS:Ne,type:N,hasAudio:D,hasVideo:w,nb:1,dropped:0,encrypted:Zt};g.audio=D&&!w?Xe:void 0,g.video=w?Xe:void 0;let ei=this.isVideoContiguous,yi=R==null?void 0:R.sampleCount;if(yi){let ie=R.keyFrameIndex,xe=ie!==-1;Xe.nb=yi,Xe.dropped=ie===0||ei?0:xe?ie:yi,Xe.independent=xe,Xe.firstKeyFrame=ie,xe&&R.keyFrameStart&&(Xe.firstKeyFramePTS=(R.keyFrameStart-m.baseTime)/m.timescale),ei||(g.independent=xe),this.isVideoContiguous||(this.isVideoContiguous=xe),Xe.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ie}/${yi} dropped: ${Xe.dropped} start: ${Xe.firstKeyFramePTS||"NA"}`)}return g.initSegment=b,g.id3=l_(s,n,m,m),r.samples.length&&(g.text=d_(r,n,m)),g}};function pu(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function qC(i,e){let t=i,s=i;for(let r=0;r<e.length;r++){let{cts:n,duration:a}=e[r];s=Math.max(s,t+(n||0)+a),t+=a}return s}function YC(i,e,t,s){if(t!==void 0){let n=i[i.length-1],a=e;for(let o=0;o<i.length-1;o++)a-=i[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(s===void 0)return;let r=Math.round(e/i.length);for(let n=0;n<i.length;n++)i[n].duration=r;return{durationOffset:s,value:r}}function jC(i,e,t,s){if(i===null)return!0;let r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>=r}function _b(i,e,t){let s=i.codec;return s&&s.length>4?s:e===Je.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?wu(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var Tr;try{Tr=self.performance.now.bind(self.performance)}catch{Tr=Date.now}var Ru=[{demux:Pp,remux:Hp},{demux:zu,remux:ga},{demux:Cp,remux:ga},{demux:Mp,remux:ga}];Ru.splice(2,0,{demux:wp,remux:ga});var Zu=class{constructor(e,t,s,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=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){if(!this.observer)return gu(s);let n=s.transmuxing;n.executeStart=Tr();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:E,initSegmentData:b}=l,T=zC(a,t);if(T&&pa(T.method)){let x=this.getDecrypter(),k=Vg(T.method);return this.asyncResult=!0,this.decryptionPromise=x.decrypt(a,T.key.buffer,T.iv.buffer,k,s.decryptRange).then(R=>{let D=this.push(R,null,s);return this.decryptionPromise=null,D}),this.decryptionPromise}let _=this.needsProbing(u,c);if(_){let x=s.iframe&&b&&zu.probe(b,this.logger)?b:a,k=this.configureTransmuxer(x);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),n.executeEnd=Tr(),gu(s)}(u||c||m||_)&&this.resetInitSegment(b,p,g,E,t,s),(u||m||_)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let I=this.transmux(a,T,f,h,s);this.asyncResult=pl(I);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Tr(),I}flush(e){let t=e.transmuxing;t.executeStart=Tr();let{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(s){let c=s.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=Tr();let c=[gu(e)];return this.asyncResult?Promise.resolve(c):c}let u=l.flush(o,e);return pl(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){if(!this.remuxer)return;let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);let u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=Tr()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,n,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,s,r,n,a),l.resetInitSegment(e,t,s,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,s,r,n){let a;return(t==null?void 0:t.method)==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){let{demuxer:n,remuxer:a}=this;if(!n||!a)return gu(r);let o=n.demux(e,t,r,!1,!this.config.progressive),{audioTrack:l,videoTrack:d,id3Track:u,textTrack:c}=o;return{remuxResult:a.remux(l,d,u,c,t,s,!1,this.id,r,o.initData,o.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:r}=this;if(!s)return;let n;try{for(let c=0,h=Ru.length;c<h;c++){var a;if((a=Ru[c].demux)!=null&&a.probe(e,this.logger)){n=Ru[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,d=n.demux,u=n.remux;(!o||!(o instanceof d))&&(this.logger.log(`Using ${d.name}`),this.demuxer=new d(s,t,r,this.logger),this.probe=d.probe),(!l||!(l instanceof u))&&(this.logger.log(`Using ${u.name}`),this.remuxer=new u(s,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 ul(this.config)),e}};function zC(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var gu=i=>({remuxResult:{},chunkMeta:i});function pl(i){return"then"in i&&i.then instanceof Function}var Gp=class{constructor(e,t,s,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=s,this.duration=r,this.defaultInitPts=n||null}},Kp=class{constructor(e,t,s,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=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}},Ab=0,Ju=class{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ab++,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 d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.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(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=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:ne.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new qg,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=Hy(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||fC()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=pC(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=mC());let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:rt(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Zu(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Zu(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Ab++;let t=this.hls.config,s=Hy(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:rt(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),gC(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,s,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,E=v?n.cc!==v.cc:!0,b=v?d.level!==v.level:!0,T=v?d.sn-v.sn:-1,_=this.part?d.part-this.part.index:-1,I=T===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),S=!b&&(T===1||T===0&&(_===1||I&&_<=0)),x=self.performance.now();(b||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(_||!S)&&(a.stats.parsing.start=x);let k=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),R=new Kp(E,S,l,b,p,k);if(!S||E||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id} playlist: ${d.level} id: ${d.id}
|
|
32
|
+
discontinuity: ${E}
|
|
33
|
+
trackSwitch: ${b}
|
|
34
34
|
contiguous: ${S}
|
|
35
35
|
accurateTimeOffset: ${l}
|
|
36
36
|
timeOffset: ${p}
|
|
37
|
-
initSegmentChange: ${k}`);let D=new Gp(s,r,t,o,u);this.configureTransmuxer(D)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:R},e instanceof ArrayBuffer?[e]:[]);else if(m){let D=m.push(e,g,d,R);pl(D)?D.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(D)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let r=s.flush(e);pl(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,s){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Sb=100,Vp=class extends hl{constructor(e,t,s){super(e,t,s,"audio-stream-controller",te.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(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,t){let{frag:s,id:r,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(r===te.MAIN){let d=s.cc,u=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${d} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===U.WAITING_INIT_PTS){let c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==d)&&this.syncWithAnchor(s,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==d?(u.abortRequests(),this.syncWithAnchor(s,u)):this.state===U.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 s;let r=((s=this.mainFragLoading)==null?void 0:s.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=MT(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===U.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=U.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Sb),s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=U.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 U.IDLE:this.doTickIdle();break;case U.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=U.WAITING_INIT_PTS}break}case U.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case U.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=U.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:s,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=U.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:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;let o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=U.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Je.AUDIO));let u=this.getFwdBufferInfo();if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=U.ENDED;return}let c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:u.end;if(this.switchingTrack&&r){let E=p;l.PTSKnown&&E<m&&E>=this.timelineOffset&&(u.end>m||u.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${E} -> ${m} + 0.05`),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,u,te.MAIN,h)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(u,h,v))return;let b=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&b&&Et(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(b)===ft.OK&&(this.mainFragLoading=b=null),b&&Et(b))){if(v.start>b.end){let T=this.fragmentTracker.getFragAtPos(g,te.MAIN);T&&T.end>b.end&&(b=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>b.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(s=>new Tn(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==U.STOPPED&&(this.setInterval(Sb),this.state=U.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;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 d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==U.STOPPED&&(this.state=U.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 u=r[a],c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(Gu(d,n,this),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===U.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=U.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=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 ${s.sn} of level ${s.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Ju(this.hls,te.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,v=g!==-1,b=new cl(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v,s.duration);h.push(n,m,c,"",s,r,u.totalduration,!1,b,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new Wu,complete:!1};p.push(new Uint8Array(n)),this.state!==U.STOPPED&&(this.state=U.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===te.MAIN&&Et(t.frag)&&(this.mainFragLoading=t,this.state===U.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:r}=t;if(s.type!==te.AUDIO){!this.audioOnly&&s.type===te.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Et(s)){let n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(s,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,te.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let s=this.fragPlaying,r=e==null?void 0:e.level;return(!s||s.level!==r)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.AUDIO,t);break;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Re.AUDIO_TRACK&&(this.state=U.IDLE);break;case P.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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===U.ENDED&&(this.state=U.IDLE);let s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,t),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l),p!=null&&p.tracks&&this.resetTransmuxer();return}if(this.state=U.PARSING,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:g}=this,v=g.nextAudioTrackBufferFlushForwardOffset,b=Math.max(this.getLoadPosition()+v,l.start);super.flushMainBuffer(b,Number.POSITIVE_INFINITY,te.AUDIO)}if(p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){let{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=h;d&&(d.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),l.setElementaryStreamInfo(Je.AUDIO,g,v,b,E),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let g=Qe({id:s,frag:l,details:c},m);r.trigger(y.FRAG_PARSING_METADATA,g)}if(f){let g=Qe({id:s,frag:l,details:c},f);r.trigger(y.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==U.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=te.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(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===ft.NOT_LOADED||r===ft.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=U.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Gu(a,t.details,this)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;yn({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,En)||(Ou(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(y.AUDIO_TRACK_SWITCHED,ae({},e))}get nextAudioTrack(){return this.nextTrackId}},gl=class extends si{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,s){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(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),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 u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}let d=s&&Gy(s);return new Pu(o,l>=0?l:void 0,d)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){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 d=this.hls.config.timelineOffset;if(d!==r.appliedTimelineOffset){let c=Math.max(d||0,0);r.appliedTimelineOffset=c,a.forEach(h=>{h==null||h.setStart(h.playlistOffset+c)})}if(r.live||s!=null&&s.live){var u;let c="levelInfo"in t?t.levelInfo:t.track;r.reloaded(s);let h=(u=a[a.length-1])==null?void 0:u.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let _=new Error(`${h} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(_);let{networkDetails:I,context:S}=t;this.hls.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:P.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:_,reason:_.message,level:t.level,parent:h,context:S,networkDetails:I,stats:n});return}if(s){tC(s,r,this);let _=r.playlistParsingError;if(_){this.warn(_);let I=this.hls;if(!I.config.ignorePlaylistParsingErrors){let{networkDetails:S}=t;I.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:_,reason:_.message,level:t.level,parent:h,networkDetails:S,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let f=this.hls.mainForwardBufferInfo,m=f?f.end-f.len:0,p=(r.edge-m)*1e3,g=VT(r,p);r.requestScheduled+g<o?r.requestScheduled=o:r.requestScheduled<=o&&(r.requestScheduled+=g);let v=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?"UPDATED":`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!r.live)return;let b,E,T;if(r.canBlockReload&&r.advanced){let _=this.hls.config.lowLatencyMode,I=r.lastPartSn,S=r.endSN,x=r.lastPartIndex,k=x!==-1,R=I===S;k?R?(E=S+1,T=_?0:x):(E=I,T=_?x+1:r.maxPartIndex):E=S+1;let D=r.age,w=D+r.ageHeader,N=Math.min(w-r.partTarget,r.targetduration*1.5);if(N>0){if(w>r.targetduration*3)this.log(`Playlist last advanced ${D.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,T=void 0;else if(s!=null&&s.tuneInGoal&&w-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${N} with playlist age: ${r.age}`),N=0;else{let $=Math.floor(N/r.targetduration);if(E+=$,T!==void 0){let H=Math.round(N%r.targetduration/r.partTarget);T+=H}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${D.toFixed(2)}s goal: ${N} skip sn ${$} to part ${T}`)}r.tuneInGoal=N}if(b=this.getDeliveryDirectives(r,t.deliveryDirectives,E,T),_||!R){r.requestScheduled=o,this.loadingPlaylist(c,b);return}}else(r.canBlockReload||r.canSkipUntil)&&(b=this.getDeliveryDirectives(r,t.deliveryDirectives,E,T));b&&E!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(g-l*2,g/2)),this.scheduleLoading(c,b,r)}else this.clearTimer()}scheduleLoading(e,t,s){let r=s||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,s,r){let n=Gy(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=Iu.No),new Pu(s,r,n)}checkRetry(e){let t=e.details,s=Du(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Gt.RetryRequest||!r.resolved&&n===Gt.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var u;let c=rl((u=e.response)==null?void 0:u.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let h=Ug(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(),rl(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function u_(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!vl(i[t].attrs,e[t].attrs))return!1;return!0}function vl(i,e,t){let s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}var Wp=class extends gl{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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} 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 ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>dl(h.groupId,s));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=ps(l,o,En);if(h>-1)n=o[h];else{let f=ps(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,u);let c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);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:re.MEDIA_ERROR,details:P.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Re.AUDIO_TRACK&&t.context.id===this.trackId&&dl(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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let r=this.currentTrack;if(r&&yn(e,r,En))return r;let n=ps(e,this.tracksInGroup,En);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=CD(e,t.levels,s,a,En);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=ps(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e,t=!0){let s=this.tracksInGroup;if(e<0||e>=s.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,n=s[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(y.AUDIO_TRACK_SWITCHING,ae(ae({},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 s=0;s<t.length;s++){let r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||yn(e,r,En)))return s}if(e){let{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let u=t[d];if(yn({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,En))return d}for(let d=0;d<t.length;d++){let u=t[d];if(vl(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let u=t[d];if(vl(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ou(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=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 ${s} "${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:s,groupId:r,deliveryDirectives:t||null,track:e})}},qp=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;s==="async-blocker"||s==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):s==="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 s;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.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>":`
|
|
37
|
+
initSegmentChange: ${k}`);let D=new Gp(s,r,t,o,u);this.configureTransmuxer(D)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:R},e instanceof ArrayBuffer?[e]:[]);else if(m){let D=m.push(e,g,d,R);pl(D)?D.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(D)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let r=s.flush(e);pl(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,s){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Sb=100,Vp=class extends hl{constructor(e,t,s){super(e,t,s,"audio-stream-controller",te.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(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,t){let{frag:s,id:r,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(r===te.MAIN){let d=s.cc,u=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${d} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===U.WAITING_INIT_PTS){let c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==d)&&this.syncWithAnchor(s,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==d?(u.abortRequests(),this.syncWithAnchor(s,u)):this.state===U.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 s;let r=((s=this.mainFragLoading)==null?void 0:s.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=MT(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===U.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=U.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Sb),s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=U.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 U.IDLE:this.doTickIdle();break;case U.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=U.WAITING_INIT_PTS}break}case U.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case U.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=U.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:s,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=U.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:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;let o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=U.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Je.AUDIO));let u=this.getFwdBufferInfo();if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=U.ENDED;return}let c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:u.end;if(this.switchingTrack&&r){let b=p;l.PTSKnown&&b<m&&b>=this.timelineOffset&&(u.end>m||u.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${b} -> ${m} + 0.05`),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,u,te.MAIN,h)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(u,h,v))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&Et(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===ft.OK&&(this.mainFragLoading=E=null),E&&Et(E))){if(v.start>E.end){let T=this.fragmentTracker.getFragAtPos(g,te.MAIN);T&&T.end>E.end&&(E=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>E.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(s=>new Tn(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==U.STOPPED&&(this.setInterval(Sb),this.state=U.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;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 d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==U.STOPPED&&(this.state=U.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 u=r[a],c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(Gu(d,n,this),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===U.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=U.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=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 ${s.sn} of level ${s.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Ju(this.hls,te.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,v=g!==-1,E=new cl(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v,s.duration);h.push(n,m,c,"",s,r,u.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new Wu,complete:!1};p.push(new Uint8Array(n)),this.state!==U.STOPPED&&(this.state=U.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===te.MAIN&&Et(t.frag)&&(this.mainFragLoading=t,this.state===U.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:r}=t;if(s.type!==te.AUDIO){!this.audioOnly&&s.type===te.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Et(s)){let n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(s,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,te.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let s=this.fragPlaying,r=e==null?void 0:e.level;return(!s||s.level!==r)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.AUDIO,t);break;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Re.AUDIO_TRACK&&(this.state=U.IDLE);break;case P.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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===U.ENDED&&(this.state=U.IDLE);let s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,t),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l),p!=null&&p.tracks&&this.resetTransmuxer();return}if(this.state=U.PARSING,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:g}=this,v=g.nextAudioTrackBufferFlushForwardOffset,E=Math.max(this.getLoadPosition()+v,l.start);super.flushMainBuffer(E,Number.POSITIVE_INFINITY,te.AUDIO)}if(p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){let{startPTS:g,endPTS:v,startDTS:E,endDTS:b}=h;d&&(d.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:v,startDTS:E,endDTS:b}),l.setElementaryStreamInfo(Je.AUDIO,g,v,E,b),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let g=Qe({id:s,frag:l,details:c},m);r.trigger(y.FRAG_PARSING_METADATA,g)}if(f){let g=Qe({id:s,frag:l,details:c},f);r.trigger(y.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==U.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=te.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(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===ft.NOT_LOADED||r===ft.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=U.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Gu(a,t.details,this)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;yn({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,En)||(Ou(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(y.AUDIO_TRACK_SWITCHED,ae({},e))}get nextAudioTrack(){return this.nextTrackId}},gl=class extends si{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,s){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(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),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 u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}let d=s&&Gy(s);return new Pu(o,l>=0?l:void 0,d)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){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 d=this.hls.config.timelineOffset;if(d!==r.appliedTimelineOffset){let c=Math.max(d||0,0);r.appliedTimelineOffset=c,a.forEach(h=>{h==null||h.setStart(h.playlistOffset+c)})}if(r.live||s!=null&&s.live){var u;let c="levelInfo"in t?t.levelInfo:t.track;r.reloaded(s);let h=(u=a[a.length-1])==null?void 0:u.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let _=new Error(`${h} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(_);let{networkDetails:I,context:S}=t;this.hls.trigger(y.ERROR,{type:ne.NETWORK_ERROR,details:P.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:_,reason:_.message,level:t.level,parent:h,context:S,networkDetails:I,stats:n});return}if(s){tC(s,r,this);let _=r.playlistParsingError;if(_){this.warn(_);let I=this.hls;if(!I.config.ignorePlaylistParsingErrors){let{networkDetails:S}=t;I.trigger(y.ERROR,{type:ne.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:_,reason:_.message,level:t.level,parent:h,networkDetails:S,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let f=this.hls.mainForwardBufferInfo,m=f?f.end-f.len:0,p=(r.edge-m)*1e3,g=VT(r,p);r.requestScheduled+g<o?r.requestScheduled=o:r.requestScheduled<=o&&(r.requestScheduled+=g);let v=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?"UPDATED":`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!r.live)return;let E,b,T;if(r.canBlockReload&&r.advanced){let _=this.hls.config.lowLatencyMode,I=r.lastPartSn,S=r.endSN,x=r.lastPartIndex,k=x!==-1,R=I===S;k?R?(b=S+1,T=_?0:x):(b=I,T=_?x+1:r.maxPartIndex):b=S+1;let D=r.age,w=D+r.ageHeader,N=Math.min(w-r.partTarget,r.targetduration*1.5);if(N>0){if(w>r.targetduration*3)this.log(`Playlist last advanced ${D.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,T=void 0;else if(s!=null&&s.tuneInGoal&&w-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${N} with playlist age: ${r.age}`),N=0;else{let $=Math.floor(N/r.targetduration);if(b+=$,T!==void 0){let H=Math.round(N%r.targetduration/r.partTarget);T+=H}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${D.toFixed(2)}s goal: ${N} skip sn ${$} to part ${T}`)}r.tuneInGoal=N}if(E=this.getDeliveryDirectives(r,t.deliveryDirectives,b,T),_||!R){r.requestScheduled=o,this.loadingPlaylist(c,E);return}}else(r.canBlockReload||r.canSkipUntil)&&(E=this.getDeliveryDirectives(r,t.deliveryDirectives,b,T));E&&b!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(g-l*2,g/2)),this.scheduleLoading(c,E,r)}else this.clearTimer()}scheduleLoading(e,t,s){let r=s||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,s,r){let n=Gy(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=Iu.No),new Pu(s,r,n)}checkRetry(e){let t=e.details,s=Du(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Gt.RetryRequest||!r.resolved&&n===Gt.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var u;let c=rl((u=e.response)==null?void 0:u.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let h=Ug(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(),rl(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function u_(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!vl(i[t].attrs,e[t].attrs))return!1;return!0}function vl(i,e,t){let s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}var Wp=class extends gl{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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} 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 ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>dl(h.groupId,s));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=ps(l,o,En);if(h>-1)n=o[h];else{let f=ps(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,u);let c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);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:ne.MEDIA_ERROR,details:P.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Re.AUDIO_TRACK&&t.context.id===this.trackId&&dl(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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let r=this.currentTrack;if(r&&yn(e,r,En))return r;let n=ps(e,this.tracksInGroup,En);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=CD(e,t.levels,s,a,En);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=ps(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e,t=!0){let s=this.tracksInGroup;if(e<0||e>=s.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,n=s[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(y.AUDIO_TRACK_SWITCHING,ae(ae({},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 s=0;s<t.length;s++){let r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||yn(e,r,En)))return s}if(e){let{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let u=t[d];if(yn({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,En))return d}for(let d=0;d<t.length;d++){let u=t[d];if(vl(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let u=t[d];if(vl(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ou(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=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 ${s} "${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:s,groupId:r,deliveryDirectives:t||null,track:e})}},qp=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;s==="async-blocker"||s==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):s==="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 s;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.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,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],r=s==null?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},Ib=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,c_="HlsJsTrackRemovedError",QC=.25,XC=.001,Yp=class extends Error{constructor(e){super(e),this.name=c_}},jp=class extends si{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=s=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),!(!r||!n)&&(We(n,"sourceopen",this._onMediaSourceOpen),We(r,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let s=this.media.error,{appendError:r,appendErrors:n}=this,a=!1;!r&&s&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${Lb(a,s)}`);this.warn(o),this.hls.trigger(y.ERROR,Qe({fatal:a},r,{type:
|
|
40
|
+
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],r=s==null?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},Ib=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,c_="HlsJsTrackRemovedError",QC=.25,XC=.001,Yp=class extends Error{constructor(e){super(e),this.name=c_}},jp=class extends si{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=s=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),!(!r||!n)&&(We(n,"sourceopen",this._onMediaSourceOpen),We(r,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let s=this.media.error,{appendError:r,appendErrors:n}=this,a=!1;!r&&s&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${Lb(a,s)}`);this.warn(o),this.hls.trigger(y.ERROR,Qe({fatal:a},r,{type:ne.MEDIA_ERROR,details:P.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:r}=this;s!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${s})`)},this._onMediaError=()=>{let{media:s}=this;if(s){var r,n;this.log(`Media error (code: ${(r=s.error)==null?void 0:r.code}): ${(n=s.error)==null?void 0:n.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=_k(Ir(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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){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_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this),e.off(y.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};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?Qe(s,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(s[a]=Qe({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let r=Ir(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=s.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");let l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,Rb(s),ZC(s,o),s.load()}catch{s.src=o}else s.src=o}Ye(s,"emptied",this._onMediaEmptied),Ye(s,"error",this._onMediaError),this.appendSource&&Ye(s,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),Ye(e,"sourceopen",this._onMediaSourceOpen),Ye(e,"sourceended",this._onMediaSourceEnded),Ye(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ye(e,"startstreaming",this._onStartStreaming),Ye(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=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
41
|
required tracks: ${rt(s,(l,d)=>l==="initSegment"?void 0:d)};
|
|
42
|
-
transfer tracks: ${rt(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!nT(r,s)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,u=Math.max(l,(d==null?void 0:d.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{let d=l,u=r[d];if(u){let c=u.buffer;if(c){let h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){let g=be.getBuffered(c);h.detectEvictedFragments(d,g,f,null,null,!0)}let m=Jm(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),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 s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)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 d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}We(n,"sourceopen",this._onMediaSourceOpen),We(n,"sourceended",this._onMediaSourceEnded),We(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(We(n,"startstreaming",this._onStartStreaming),We(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(We(r,"emptied",this._onMediaEmptied),We(r,"error",this._onMediaError),We(r,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&Rb(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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Jm(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 qp(this.tracks)}onBufferCodecs(e,t){var s;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 d,u;let c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c,b=r[l],E=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],T=E!=null&&E.buffer?E:b,_=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),I=T==null?void 0:T.levelCodec;b||(b=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});let S=Su(_,I),x=S==null?void 0:S.replace(Ib,"$1"),k=Su(f,m),R=(u=k)==null?void 0:u.replace(Ib,"$1");k&&S&&x!==R&&(l.slice(0,5)==="audio"&&(k=wu(k,this.appendSource)),this.log(`switching codec ${_} to ${k}`),k!==(b.pendingCodec||b.codec)&&(b.pendingCodec=k),b.container=p,this.appendChangeType(l,p,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let r=`${t};codecs=${s}`,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=s,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 s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,te.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>r||be.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,r)||((l=this.fragmentTracker.getAppendedFrag(r,te.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:s}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],h=Et(o)&&!l&&!o.gap&&!d.partial&&!d.iframe,f=null,m=!1,{sn:p,cc:g}=o,v=self.performance.now();c.start=v;let b=o.stats.buffering,E=l?l.stats.buffering:null;b.start===0&&(b.start=v),(E==null?void 0:E.start)===0&&(E.start=v);let T=s.audio,_=!1;n==="audio"&&(T==null?void 0:T.container)==="audio/mpeg"&&(_=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let I=s.video,S=I==null?void 0:I.buffer;if(S&&p!=="initSegment"&&u!==void 0){let R=T==null?void 0:T.buffer,D=l||o;if(n==="audio"&&a!=="main"&&!(I.ending||I.ended)&&R&&be.getBuffered(R).length){let N=D.start+D.duration*.05,$=be.getBuffered(S),H=this.currentOp("video");!$.length&&!H?this.blockAudio(D):!be.isBuffered(S,N)&&this.lastVideoAppendEnd<N&&this.blockAudio(D)}else if(n==="video"){let w=D.end,N=this.lastVideoAppendEnd-w;this.lastVideoAppendEnd=w,N<0||N>D.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let x=(l||o).start,k={label:`append-${n}`,execute:()=>{var R;c.executeStart=self.performance.now();let D=(R=this.tracks[n])==null?void 0:R.buffer;D&&(h&&(f=be.timeRangesToArray(be.getBuffered(D)),m=kb(ep(f,o),o)),_?this.updateTimestampOffset(D,x,.1,n,p,g):u!==void 0&&Q(u)&&this.updateTimestampOffset(D,u,1e-6,n,p,g)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);let R=self.performance.now();c.executeEnd=c.end=R,b.first===0&&(b.first=R),(E==null?void 0:E.first)===0&&(E.first=R);let D={};if(this.sourceBuffers.forEach(([w,N])=>{w&&(D[w]=be.getBuffered(N))}),h){let w=this.getFragmentAppendProgress(o),N=D[n];if(N&&f){let $=be.timeRangesToArray(N),H=ep($,o);w.progressed||(w.progressed=H-ep(f,o)>XC);let O=m&&kb(H,o);w.fullyBuffered[n]=(w.fullyBuffered[n]===void 0||w.fullyBuffered[n])&&O}}this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:a,timeRanges:D})},onError:R=>{var D;this.clearBufferAppendTimeoutId(this.tracks[n]);let w=R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R;if(w&&!this._quotaEvictionPending[n]){let O=this.getBackBufferEvictionTarget(n,r.byteLength,o.type);if(O>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${p} - evicting back buffer to ${O.toFixed(3)}s and retrying`);let F=this.getFlushOp(n,0,O),B=this.getClearEvictionPendingOp(n);this.insertNext([F,k,B],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${p} - no back buffer available to evict`)}h&&(this.getFragmentAppendProgress(o).errored=!0);let N={type:re.MEDIA_ERROR,parent:a,details:P.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:R,err:R,fatal:!1},$=(D=this.media)==null?void 0:D.error;if(R.name===c_&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))N.errorAction=Zo(!0);else{var H;w&&(N.details=P.BUFFER_FULL_ERROR);let O=++this.appendErrors[n],F=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${O}/${F+1} times to append segment in "${n}" sourceBuffer with error: ${R.message}`),O>=F&&(N.fatal=!w);let B=(H=this.mediaSource)==null?void 0:H.readyState;(B==="ended"||B==="closed"||$)&&(this.warn(`MediaSource readyState "${B}" during SourceBuffer${Lb(N.fatal,$)}`),N.details=P.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=N,this.hls.trigger(y.ERROR,N),w&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${p}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${g} offset: ${u} bytes: ${r.byteLength}`),this.append(k,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,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var r;let n=(r=this.tracks[e])==null?void 0:r.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${n?Ku(be.getBuffered(n)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:s,startOffset:r,endOffset:n}=t;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:s,part:r,chunkMeta:n}=t,a=[],o=r?r.elementaryStreams:s.elementaryStreams;o[Je.AUDIOVIDEO]?a.push("audiovideo"):(o[Je.AUDIO]&&a.push("audio"),o[Je.VIDEO]&&a.push("video"));let l=()=>{let d=self.performance.now();s.stats.buffering.end=d,r&&(r.stats.buffering.end=d);let u=r?r.stats:s.stats;this.checkAppendProgress(s,r,n,a),this.hls&&(this.hls.trigger(y.FRAG_BUFFERED,{frag:s,part:r,stats:u,id:s.type,chunkMeta:n}),!r&&s.gap&&u.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${u.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${r?`part: ${r.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(d=>{this.warn(`Fragment buffered callback ${d.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:d}=this,u=(r=this.appendError)==null?void 0:r.sourceBufferName;Object.keys(l).forEach(c=>{l[c]&&(d[c]=0,c===u&&(this.appendError=void 0),c==="audio"||c==="video"?(d.audiovideo=0,u==="audiovideo"&&(this.appendError=void 0)):(d.audio=0,d.video=0,u!=="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 s;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=((s=this.overrides)==null?void 0:s.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(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===P.BUFFER_APPEND_ERROR&&t.frag){var s;let r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;Q(r)&&r!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,s,t):0}getFragmentAppendProgress(e){var t;let s=xb(e),r=this.fragmentAppendProgress[s];return((t=r)==null?void 0:t.stats)!==e.stats&&(r={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=r),r}checkAppendProgress(e,t,s,r){if(t||!Et(e)||e.gap||s.iframe||s.partial)return;let n=xb(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 d=r.length>0&&r.every(f=>(l==null?void 0:l.fullyBuffered[f])===!0);if(l!=null&&l.progressed||d){delete this.appendsWithoutProgress[n];return}if(!l&&r.length===0)return;let u=(this.appendsWithoutProgress[n]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${u} time${u>1?"s":""} without buffered range growth`),c.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}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,s,r){let{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=n.config,d=o.currentTime,u=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let c=-1/0;if(Q(t)&&t>=0){let h=Math.max(t,u);c=Math.floor(d/u)*u-h}if(s){let h=this.getLoopBackBufferFlushEnd(s,r!=null?r:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(d,u,c),Q(e)&&e>0){let h=Math.max(l.maxBufferLength,e),f=Math.max(h,u),m=Math.floor(d/u)*u+f;this.flushFrontBuffer(d,u,m)}}getLoopBackBufferFlushEnd(e,t){var s;let{media:r}=this;if(((s=this.hls)==null?void 0:s.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)-QC;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:s,audiovideo:r}=e.elementaryStreams,n=e.start;return r?n=Math.min(n,r.startDTS):(t&&(n=Math.min(n,t.startDTS)),s&&(n=Math.min(n,s.startDTS))),n}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let d=be.getBuffered(n);if(d.length>0&&s>d.start(0)){var a,o,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});let u=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(u!=null&&u.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(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=be.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;let a=this.media.duration,o=Q(s.duration)?s.duration:0;return r>o&&r>a||!Q(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){let r=this.mediaSource;!r||!this.media||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${rt(s)}`),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,s])=>{if(t){let r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(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:re.MEDIA_ERROR,details:P.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)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),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${rt(o)}`);try{let u=s.addSourceBuffer(d),c=Jm(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,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 s=e.supplemental,r=e.codec;s&&(t==="video"||t==="audiovideo")&&ol(s,"video")&&(r=fD(r,s));let n=Su(r,e.levelCodec);return n?t.slice(0,5)==="audio"?wu(n,this.appendSource):n:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${Ku(o)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;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(),(s=this.tracks[e])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var s;let r=(s=this.mediaSource)==null?void 0:s.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${r}`);this.error(`${n.message}`,t),this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,s,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){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=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,u=Math.max(0,t);if(u>=d){var c;(c=this.currentOp(e))==null||c.onComplete(),this.shiftAndExecuteNext(e);return}let h=Math.min(s,l,d);if(h>u&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${u},${h}] from the ${e} SourceBuffer`),o.remove(u,h);else throw new Error(`Cannot remove ${h<=u?`invalid range (${u} >= ${h}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let s=this.tracks[t],r=s==null?void 0:s.buffer;if(!r)throw new Yp(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){let n=this.calculateAppendTimeoutTime(r);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,n),n)}r.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}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=NT;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(this.media===null)return s;let r=be.bufferInfo(e,this.media.currentTime,0);return r.len?(s=Math.max(r.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}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:s}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=s.bind(this,e);r.listeners.push({event:t,listener:a}),Ye(n,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(r=>{We(s,r.event,r.listener)}),t.listeners.length=0)}};function Rb(i){let e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function ZC(i,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Jm(i){return i==="audio"?1:0}function Lb(i,e){return`${i?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function xb(i){return`${i.type}_${i.sn}_${i.level}`}function ep(i,e){let{start:t,end:s}=e,r=0;for(let n=0;n<i.length;n++){let a=i[n];if(a.start>=s)break;let o=Math.max(t,a.start),l=Math.min(s,a.end);l>o&&(r+=l-o)}return r}function kb(i,e){return e.duration-i<=.05}var El=class i{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(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&&(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){if(!this.hls)return;let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){let s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,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)&&(Q(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.observer||(this.clientRect=null),i.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var s;let r=(s=t[0])==null?void 0:s.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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){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,s);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}},ci=class zp{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof zp?s:new zp(s))),this.value=e,this.params=t}},JC="Dict";function ew(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function tw(i,e,t,s){return new Error(`failed to ${i} "${ew(e)}" as ${t}`,{cause:s})}var Db="Bare Item",iw="Boolean",sw="Byte Sequence",rw="Decimal",nw="Integer";function aw(i){return i<-999999999999999||999999999999999<i}var ow="String",lw=/[\x00-\x1f\x7f]+/,h_=class{constructor(i){this.description=i}},dw="Token",uw="Key";function gs(i,e,t){return tw("serialize",i,e,t)}function cw(i){if(typeof i!="boolean")throw gs(i,iw);return i?"?1":"?0"}function hw(i){if(ArrayBuffer.isView(i)===!1)throw gs(i,sw);return`:${Ak(i)}:`}function f_(i){if(aw(i))throw gs(i,nw);return i.toString()}function fw(i){return`@${f_(i.getTime()/1e3)}`}function mw(i){let e=aT(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw gs(i,rw);let t=e.toString();return t.includes(".")?t:`${t}.0`}function pw(i){if(lw.test(i))throw gs(i,ow);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gw(i){return i.description||i.toString().slice(7,-1)}function Cb(i){let e=gw(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw gs(e,dw);return e}function Qp(i){switch(typeof i){case"number":if(!Q(i))throw gs(i,Db);return Number.isInteger(i)?f_(i):mw(i);case"string":return pw(i);case"symbol":return Cb(i);case"boolean":return cw(i);case"object":if(i instanceof Date)return fw(i);if(i instanceof Uint8Array)return hw(i);if(i instanceof h_)return Cb(i);default:throw gs(i,Db)}}function Xp(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw gs(i,uw);return i}function Qg(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Xp(e)}`:`;${Xp(e)}=${Qp(t)}`).join("")}function m_(i){return i instanceof ci?`${Qp(i.value)}${Qg(i.params)}`:Qp(i)}function vw(i){return`(${i.value.map(m_).join(" ")})${Qg(i.params)}`}function Ew(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw gs(i,JC);let t=i instanceof Map?i.entries():Object.entries(i),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ci||(n=new ci(n));let a=Xp(r);return n.value===!0?a+=Qg(n.params):(a+="=",Array.isArray(n.value)?a+=vw(n):a+=m_(n)),a}).join(`,${s}`)}function p_(i,e){return Ew(i,e)}var yw=["url"],bw=["version","eventTargets","sid","transmissionMode"],Tw=["customData","headers"],wb=i=>i instanceof ci?new ci(Math.round(i.value),i.params):Math.round(i),tp=i=>Array.isArray(i)?i.map(wb):wb(i),Zp=(i,e)=>Array.isArray(i)?i.map(t=>Zp(t,e)):i instanceof ci&&typeof i.value=="string"?new ci(Zp(i.value,e),i.params):(e.baseUrl&&(i=Lk(i,Rk(e.baseUrl))),e.version===1?encodeURIComponent(i):i),Mb=i=>i instanceof ci?new ci(Math.round(i.value/100)*100,i.params):Math.round(i/100)*100,vu=i=>Array.isArray(i)?i.map(Mb):Mb(i),_w=(i,e)=>{let t=i;return e.version>=2&&(i instanceof ci&&typeof i.value=="string"?t=new ci([i]):typeof i=="string"&&(t=[i])),Zp(t,e)},Aw={br:tp,d:tp,bl:vu,dl:vu,mtp:vu,nor:_w,rtp:vu,tb:tp},yl=2,g_="bc",Sw="ps",v_="pr",Iw="e",Pb="t",Rw="c",E_="b",Xg="rr",y_="ce",Eu={BITRATE_CHANGE:g_,ERROR:Iw,RESPONSE_RECEIVED:Xg,CUSTOM_EVENT:y_},b_=new Map([[Sw,"sta"],[v_,"pr"],[Rw,"cid"],[E_,"bg"],[g_,"br"]]),Zg="event",Jg="request",T_=["cen","e","h","ts"],__=["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"],Lw=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function e0(i){return Lw.test(i)}var xw=new Set(__);function A_(i){return xw.has(i)||e0(i)}var S_=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],kw=new Set(S_);function I_(i){return kw.has(i)}var Dw=new Set(T_);function Cw(i){return A_(i)||I_(i)||Dw.has(i)}var ww=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),hc=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Mw=new Set(hc);function Pw(i){return Mw.has(i)||e0(i)}var Ow=new Set(["ot","sf","st","e","sta"]);function Nw(i){return Ow.has(i)}function Uw(i){return typeof i=="number"?Q(i):i!=null&&i!==""&&i!==!1}var Fw={[Zg]:Cw,[Jg]:A_};function R_(i,e){if(Array.isArray(i)){let t;return e&&(t=i.find(s=>{var r;return((r=s.params)==null?void 0:r.ot)===e})),t||(t=i[0]),R_(t)}return i instanceof ci?i.value:i}function Bw(i){let e={};for(let[s,r]of Object.entries(i)){if(r==null){e[s]=r;continue}if(s==="nor"){let n=(Array.isArray(r)?r:[r])[0];if(n instanceof ci){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else ww.has(s)?e[s]=R_(r,i.ot):e[s]=r}return e}function L_(i,e={}){let t={};if(i==null||typeof i!="object")return t;let s=e.version||i.v||yl,r=e.reportingMode||Jg,n=s===1?Bw(i):i,a=s===1?Pw:Fw[r],o=Object.keys(n).filter(a);n.e&&n.e!==Xg&&(o=o.filter(f=>!I_(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let d=r===Zg;if(d){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===y_&&o.push("cen");let m=f?b_.get(f):void 0;m&&n[m]!=null&&!o.includes(m)&&o.push(m)}if(o.length===0)return t;s>1&&!o.includes("v")&&o.push("v");let u={version:s,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(let f of o){var c,h;let m=n[f],p=(c=(h=e.formatters)==null?void 0:h[f])!=null?c:Aw[f];if(typeof p=="function"&&(m=p(m,u)),f==="v"){if(s===1)continue;m=s}if(f==="pr"&&m===1&&!(d&&n.e===v_))continue;d&&f==="ts"&&!Q(m)&&(m=Date.now());let g=d&&m===!1&&f==="bg"&&n.e===E_;!Uw(m)&&!g||(Nw(f)&&typeof m=="string"&&(m=new h_(m)),t[f]=m)}return t}var qs="CMCD-Object",ui="CMCD-Request",ca="CMCD-Session",Vi="CMCD-Status",$w={REQUEST:ui},Hw={ab:qs,br:qs,d:qs,lab:qs,lb:qs,ot:qs,tab:qs,tb:qs,tpb:qs,bl:ui,cs:ui,dfa:ui,dl:ui,ltc:ui,mtp:ui,nor:ui,nrr:ui,pb:ui,sn:ui,sta:ui,su:ui,tbl:ui,cid:ca,msd:ca,sf:ca,sid:ca,st:ca,v:ca,bg:Vi,bs:Vi,bsa:Vi,bsd:Vi,bsda:Vi,cdn:Vi,ec:Vi,nr:Vi,pr:Vi,pt:Vi,rtp:Vi};function Gw(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])==null||s.forEach(r=>e[r]=t),e},{})}function Kw(i,e){let t={};if(!i)return t;let s=Object.keys(i),r=e?Gw(e):{};for(let a of s){var n;let o=Hw[a]||r[a]||$w.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=i[a]}return t}function Vw(i,e){let t={},s=Kw(i,e);for(let[r,n]of Object.entries(s)){let a=p_(n,{whitespace:!1});a&&(t[r]=a)}return t}var Ob="CMCD";function x_(i){return p_(i,{whitespace:!1})}function Ww(i,e={}){return i?x_(L_(i,e)):""}var qw=30,Jp=[...hc,...__,...S_,...T_].filter((i,e,t)=>t.indexOf(i)===e),Yw="application/cmcd",jw=1,Yt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Wi={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},t0="query",k_="headers";function Nb(i,e,t){var s;let r=new Set((s=e.enabledKeys)!=null?s:[]);return{version:e.version||yl,reportingMode:i,filter:n=>r.has(n),baseUrl:t}}function zw(i,e){if(i===e)return!0;if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++){let s=i[t],r=e[t];if(s===r)continue;if(typeof s=="number"||typeof r=="number"||s.value!==r.value)return!1;let n=s.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 Qw=Object.is,Xw=i=>i,D_=Array.from(b_,([i,e])=>e==="br"?{event:i,field:e,equal:(t,s)=>t===void 0||s===void 0?t===s:zw(t,s),snapshot:t=>t.slice()}:{event:i,field:e,equal:Qw,snapshot:Xw}),Zw=new Map(D_.map(i=>[i.event,i]));function Jw(i){let{url:e}=i,t=dc(i,yw);return fetch(e,t)}function eM(i){let{version:e=yl,eventTargets:t=[],sid:s=oT(),transmissionMode:r=t0}=i,n=dc(i,bw);return ae(ae({},n),{},{version:e,transmissionMode:r,sid:s,eventTargets:t.reduce((a,o)=>{var l,d,u;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||yl,enabledKeys:((d=o.enabledKeys)==null?void 0:d.slice())||[],url:o.url,events:o.events.slice(),interval:(u=o.interval)!=null?u:qw,batchSize:o.batchSize||1}),a},[])})}var tM=class{constructor(i,e=Jw){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=eM(i),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((i,e)=>{if(this.disarmInterval(i),e.interval===0||!e.events.includes(Pb))return;let t=()=>{this.recordTargetEvent(i,e,Pb),this.processEventTargets()};i.intervalId=setInterval(t,e.interval*1e3),t()})}stop(i=!1){i&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(i){i.sid&&i.sid!==this.data.sid&&this.resetSession(),i.msd&&!isNaN(i.msd)&&(this.msd=i.msd),this.data=ae(ae(ae({},this.data),i),{},{msd:void 0});for(let e of D_)e.field in i&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(i,e={}){let t=Zw.get(i);if(t){let s=t.field,r=e[s];r!==void 0&&Qe(this.data,{[s]:r});let n=this.data[s];if(n===void 0||t.equal(n,this.lastEmitted[s]))return;Qe(this.lastEmitted,{[s]:t.snapshot(n)})}this.eventTargets.forEach((s,r)=>{this.recordTargetEvent(s,r,i,e)}),this.processEventTargets()}recordTargetEvent(i,e,t,s={}){var r;if(!e.events.includes(t))return;let n=ae(ae(ae({},this.data),s),{},{e:t,ts:(r=s.ts)!=null?r:Date.now(),sn:i.sn++});!isNaN(this.msd)&&!i.msdSent&&(n.msd=this.msd,i.msdSent=!0),i.queue.push(n)}recordResponseReceived(i,e={}){var t,s,r;let{request:n}=i,a=(t=e.url)!=null?t:n==null?void 0:n.url;if(!a)return;let o=new URL(a);o.searchParams.delete(Ob);let l={url:o.toString(),rc:i.status},d=i.resourceTiming;d&&(d.startTime!=null&&(l.ts=Math.round(this.timeOrigin+d.startTime),d.responseStart!=null&&(l.ttfb=Math.round(d.responseStart-d.startTime))),d.duration!=null&&(l.ttlb=Math.round(d.duration)));let u=(s=(r=n.customData)==null?void 0:r.cmcd)!=null?s:{};this.recordEvent(Xg,ae(ae(ae({},u),l),e))}applyRequestReport(i){var e;return(e=this.createRequestReport(i))!=null?e:i}isRequestReportingEnabled(){var i;return!!((i=this.config.enabledKeys)!=null&&i.length)}createRequestReport(i,e){var t;let{customData:s={},headers:r={}}=i,n=dc(i,Tw),a=ae(ae({},n),{},{headers:ae({},r),customData:ae(ae({},s),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=ae(ae(ae({},this.data),e),{},{sn:this.requestTarget.sn++}),d=Nb(Jg,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let u=a.customData.cmcd=L_(l,d);switch(this.config.transmissionMode){case t0:let c=x_(u);c&&(o.searchParams.set(Ob,c),a.url=o.toString());break;case k_:Qe(a.headers,Vw(u,d.customHeaderMap));break}return a}processEventTargets(i=!1){let e=!1;this.eventTargets.forEach((t,s)=>{let{queue:r}=t;if(!r.length||r.length<s.batchSize&&!i)return;let n=i?r.length:s.batchSize,a=r.splice(0,n);this.sendEventReport(s,a).catch(()=>{t.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(i,e){let t=Nb(Zg,i),{status:s}=await this.requester({url:i.url,method:"POST",headers:{"Content-Type":Yw},body:e.map(r=>Ww(r,t)).join(`
|
|
42
|
+
transfer tracks: ${rt(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!nT(r,s)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,u=Math.max(l,(d==null?void 0:d.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{let d=l,u=r[d];if(u){let c=u.buffer;if(c){let h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){let g=be.getBuffered(c);h.detectEvictedFragments(d,g,f,null,null,!0)}let m=Jm(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),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 s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)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 d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}We(n,"sourceopen",this._onMediaSourceOpen),We(n,"sourceended",this._onMediaSourceEnded),We(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(We(n,"startstreaming",this._onStartStreaming),We(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(We(r,"emptied",this._onMediaEmptied),We(r,"error",this._onMediaError),We(r,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&Rb(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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Jm(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 qp(this.tracks)}onBufferCodecs(e,t){var s;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 d,u;let c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c,E=r[l],b=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],T=b!=null&&b.buffer?b:E,_=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),I=T==null?void 0:T.levelCodec;E||(E=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});let S=Su(_,I),x=S==null?void 0:S.replace(Ib,"$1"),k=Su(f,m),R=(u=k)==null?void 0:u.replace(Ib,"$1");k&&S&&x!==R&&(l.slice(0,5)==="audio"&&(k=wu(k,this.appendSource)),this.log(`switching codec ${_} to ${k}`),k!==(E.pendingCodec||E.codec)&&(E.pendingCodec=k),E.container=p,this.appendChangeType(l,p,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let r=`${t};codecs=${s}`,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=s,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 s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,te.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>r||be.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,r)||((l=this.fragmentTracker.getAppendedFrag(r,te.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:s}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],h=Et(o)&&!l&&!o.gap&&!d.partial&&!d.iframe,f=null,m=!1,{sn:p,cc:g}=o,v=self.performance.now();c.start=v;let E=o.stats.buffering,b=l?l.stats.buffering:null;E.start===0&&(E.start=v),(b==null?void 0:b.start)===0&&(b.start=v);let T=s.audio,_=!1;n==="audio"&&(T==null?void 0:T.container)==="audio/mpeg"&&(_=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let I=s.video,S=I==null?void 0:I.buffer;if(S&&p!=="initSegment"&&u!==void 0){let R=T==null?void 0:T.buffer,D=l||o;if(n==="audio"&&a!=="main"&&!(I.ending||I.ended)&&R&&be.getBuffered(R).length){let N=D.start+D.duration*.05,$=be.getBuffered(S),H=this.currentOp("video");!$.length&&!H?this.blockAudio(D):!be.isBuffered(S,N)&&this.lastVideoAppendEnd<N&&this.blockAudio(D)}else if(n==="video"){let w=D.end,N=this.lastVideoAppendEnd-w;this.lastVideoAppendEnd=w,N<0||N>D.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let x=(l||o).start,k={label:`append-${n}`,execute:()=>{var R;c.executeStart=self.performance.now();let D=(R=this.tracks[n])==null?void 0:R.buffer;D&&(h&&(f=be.timeRangesToArray(be.getBuffered(D)),m=kb(ep(f,o),o)),_?this.updateTimestampOffset(D,x,.1,n,p,g):u!==void 0&&Q(u)&&this.updateTimestampOffset(D,u,1e-6,n,p,g)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);let R=self.performance.now();c.executeEnd=c.end=R,E.first===0&&(E.first=R),(b==null?void 0:b.first)===0&&(b.first=R);let D={};if(this.sourceBuffers.forEach(([w,N])=>{w&&(D[w]=be.getBuffered(N))}),h){let w=this.getFragmentAppendProgress(o),N=D[n];if(N&&f){let $=be.timeRangesToArray(N),H=ep($,o);w.progressed||(w.progressed=H-ep(f,o)>XC);let O=m&&kb(H,o);w.fullyBuffered[n]=(w.fullyBuffered[n]===void 0||w.fullyBuffered[n])&&O}}this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:a,timeRanges:D})},onError:R=>{var D;this.clearBufferAppendTimeoutId(this.tracks[n]);let w=R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R;if(w&&!this._quotaEvictionPending[n]){let O=this.getBackBufferEvictionTarget(n,r.byteLength,o.type);if(O>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${p} - evicting back buffer to ${O.toFixed(3)}s and retrying`);let F=this.getFlushOp(n,0,O),B=this.getClearEvictionPendingOp(n);this.insertNext([F,k,B],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${p} - no back buffer available to evict`)}h&&(this.getFragmentAppendProgress(o).errored=!0);let N={type:ne.MEDIA_ERROR,parent:a,details:P.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:R,err:R,fatal:!1},$=(D=this.media)==null?void 0:D.error;if(R.name===c_&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))N.errorAction=Zo(!0);else{var H;w&&(N.details=P.BUFFER_FULL_ERROR);let O=++this.appendErrors[n],F=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${O}/${F+1} times to append segment in "${n}" sourceBuffer with error: ${R.message}`),O>=F&&(N.fatal=!w);let B=(H=this.mediaSource)==null?void 0:H.readyState;(B==="ended"||B==="closed"||$)&&(this.warn(`MediaSource readyState "${B}" during SourceBuffer${Lb(N.fatal,$)}`),N.details=P.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=N,this.hls.trigger(y.ERROR,N),w&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${p}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${g} offset: ${u} bytes: ${r.byteLength}`),this.append(k,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,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var r;let n=(r=this.tracks[e])==null?void 0:r.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${n?Ku(be.getBuffered(n)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:s,startOffset:r,endOffset:n}=t;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:s,part:r,chunkMeta:n}=t,a=[],o=r?r.elementaryStreams:s.elementaryStreams;o[Je.AUDIOVIDEO]?a.push("audiovideo"):(o[Je.AUDIO]&&a.push("audio"),o[Je.VIDEO]&&a.push("video"));let l=()=>{let d=self.performance.now();s.stats.buffering.end=d,r&&(r.stats.buffering.end=d);let u=r?r.stats:s.stats;this.checkAppendProgress(s,r,n,a),this.hls&&(this.hls.trigger(y.FRAG_BUFFERED,{frag:s,part:r,stats:u,id:s.type,chunkMeta:n}),!r&&s.gap&&u.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${u.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${r?`part: ${r.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(d=>{this.warn(`Fragment buffered callback ${d.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:d}=this,u=(r=this.appendError)==null?void 0:r.sourceBufferName;Object.keys(l).forEach(c=>{l[c]&&(d[c]=0,c===u&&(this.appendError=void 0),c==="audio"||c==="video"?(d.audiovideo=0,u==="audiovideo"&&(this.appendError=void 0)):(d.audio=0,d.video=0,u!=="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 s;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=((s=this.overrides)==null?void 0:s.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(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===P.BUFFER_APPEND_ERROR&&t.frag){var s;let r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;Q(r)&&r!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,s,t):0}getFragmentAppendProgress(e){var t;let s=xb(e),r=this.fragmentAppendProgress[s];return((t=r)==null?void 0:t.stats)!==e.stats&&(r={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=r),r}checkAppendProgress(e,t,s,r){if(t||!Et(e)||e.gap||s.iframe||s.partial)return;let n=xb(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 d=r.length>0&&r.every(f=>(l==null?void 0:l.fullyBuffered[f])===!0);if(l!=null&&l.progressed||d){delete this.appendsWithoutProgress[n];return}if(!l&&r.length===0)return;let u=(this.appendsWithoutProgress[n]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${u} time${u>1?"s":""} without buffered range growth`),c.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}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,s,r){let{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=n.config,d=o.currentTime,u=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let c=-1/0;if(Q(t)&&t>=0){let h=Math.max(t,u);c=Math.floor(d/u)*u-h}if(s){let h=this.getLoopBackBufferFlushEnd(s,r!=null?r:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(d,u,c),Q(e)&&e>0){let h=Math.max(l.maxBufferLength,e),f=Math.max(h,u),m=Math.floor(d/u)*u+f;this.flushFrontBuffer(d,u,m)}}getLoopBackBufferFlushEnd(e,t){var s;let{media:r}=this;if(((s=this.hls)==null?void 0:s.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)-QC;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:s,audiovideo:r}=e.elementaryStreams,n=e.start;return r?n=Math.min(n,r.startDTS):(t&&(n=Math.min(n,t.startDTS)),s&&(n=Math.min(n,s.startDTS))),n}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let d=be.getBuffered(n);if(d.length>0&&s>d.start(0)){var a,o,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});let u=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(u!=null&&u.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(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=be.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;let a=this.media.duration,o=Q(s.duration)?s.duration:0;return r>o&&r>a||!Q(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){let r=this.mediaSource;!r||!this.media||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${rt(s)}`),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,s])=>{if(t){let r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(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:ne.MEDIA_ERROR,details:P.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)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),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${rt(o)}`);try{let u=s.addSourceBuffer(d),c=Jm(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,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 s=e.supplemental,r=e.codec;s&&(t==="video"||t==="audiovideo")&&ol(s,"video")&&(r=fD(r,s));let n=Su(r,e.levelCodec);return n?t.slice(0,5)==="audio"?wu(n,this.appendSource):n:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${Ku(o)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;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(),(s=this.tracks[e])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var s;let r=(s=this.mediaSource)==null?void 0:s.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${r}`);this.error(`${n.message}`,t),this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,s,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){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=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,u=Math.max(0,t);if(u>=d){var c;(c=this.currentOp(e))==null||c.onComplete(),this.shiftAndExecuteNext(e);return}let h=Math.min(s,l,d);if(h>u&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${u},${h}] from the ${e} SourceBuffer`),o.remove(u,h);else throw new Error(`Cannot remove ${h<=u?`invalid range (${u} >= ${h}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let s=this.tracks[t],r=s==null?void 0:s.buffer;if(!r)throw new Yp(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){let n=this.calculateAppendTimeoutTime(r);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,n),n)}r.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}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=NT;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(this.media===null)return s;let r=be.bufferInfo(e,this.media.currentTime,0);return r.len?(s=Math.max(r.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}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:s}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=s.bind(this,e);r.listeners.push({event:t,listener:a}),Ye(n,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(r=>{We(s,r.event,r.listener)}),t.listeners.length=0)}};function Rb(i){let e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function ZC(i,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Jm(i){return i==="audio"?1:0}function Lb(i,e){return`${i?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function xb(i){return`${i.type}_${i.sn}_${i.level}`}function ep(i,e){let{start:t,end:s}=e,r=0;for(let n=0;n<i.length;n++){let a=i[n];if(a.start>=s)break;let o=Math.max(t,a.start),l=Math.min(s,a.end);l>o&&(r+=l-o)}return r}function kb(i,e){return e.duration-i<=.05}var El=class i{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(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&&(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){if(!this.hls)return;let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){let s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,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)&&(Q(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.observer||(this.clientRect=null),i.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var s;let r=(s=t[0])==null?void 0:s.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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){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,s);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}},ci=class zp{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof zp?s:new zp(s))),this.value=e,this.params=t}},JC="Dict";function ew(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function tw(i,e,t,s){return new Error(`failed to ${i} "${ew(e)}" as ${t}`,{cause:s})}var Db="Bare Item",iw="Boolean",sw="Byte Sequence",rw="Decimal",nw="Integer";function aw(i){return i<-999999999999999||999999999999999<i}var ow="String",lw=/[\x00-\x1f\x7f]+/,h_=class{constructor(i){this.description=i}},dw="Token",uw="Key";function gs(i,e,t){return tw("serialize",i,e,t)}function cw(i){if(typeof i!="boolean")throw gs(i,iw);return i?"?1":"?0"}function hw(i){if(ArrayBuffer.isView(i)===!1)throw gs(i,sw);return`:${Ak(i)}:`}function f_(i){if(aw(i))throw gs(i,nw);return i.toString()}function fw(i){return`@${f_(i.getTime()/1e3)}`}function mw(i){let e=aT(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw gs(i,rw);let t=e.toString();return t.includes(".")?t:`${t}.0`}function pw(i){if(lw.test(i))throw gs(i,ow);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gw(i){return i.description||i.toString().slice(7,-1)}function Cb(i){let e=gw(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw gs(e,dw);return e}function Qp(i){switch(typeof i){case"number":if(!Q(i))throw gs(i,Db);return Number.isInteger(i)?f_(i):mw(i);case"string":return pw(i);case"symbol":return Cb(i);case"boolean":return cw(i);case"object":if(i instanceof Date)return fw(i);if(i instanceof Uint8Array)return hw(i);if(i instanceof h_)return Cb(i);default:throw gs(i,Db)}}function Xp(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw gs(i,uw);return i}function Qg(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Xp(e)}`:`;${Xp(e)}=${Qp(t)}`).join("")}function m_(i){return i instanceof ci?`${Qp(i.value)}${Qg(i.params)}`:Qp(i)}function vw(i){return`(${i.value.map(m_).join(" ")})${Qg(i.params)}`}function Ew(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw gs(i,JC);let t=i instanceof Map?i.entries():Object.entries(i),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ci||(n=new ci(n));let a=Xp(r);return n.value===!0?a+=Qg(n.params):(a+="=",Array.isArray(n.value)?a+=vw(n):a+=m_(n)),a}).join(`,${s}`)}function p_(i,e){return Ew(i,e)}var yw=["url"],bw=["version","eventTargets","sid","transmissionMode"],Tw=["customData","headers"],wb=i=>i instanceof ci?new ci(Math.round(i.value),i.params):Math.round(i),tp=i=>Array.isArray(i)?i.map(wb):wb(i),Zp=(i,e)=>Array.isArray(i)?i.map(t=>Zp(t,e)):i instanceof ci&&typeof i.value=="string"?new ci(Zp(i.value,e),i.params):(e.baseUrl&&(i=Lk(i,Rk(e.baseUrl))),e.version===1?encodeURIComponent(i):i),Mb=i=>i instanceof ci?new ci(Math.round(i.value/100)*100,i.params):Math.round(i/100)*100,vu=i=>Array.isArray(i)?i.map(Mb):Mb(i),_w=(i,e)=>{let t=i;return e.version>=2&&(i instanceof ci&&typeof i.value=="string"?t=new ci([i]):typeof i=="string"&&(t=[i])),Zp(t,e)},Aw={br:tp,d:tp,bl:vu,dl:vu,mtp:vu,nor:_w,rtp:vu,tb:tp},yl=2,g_="bc",Sw="ps",v_="pr",Iw="e",Pb="t",Rw="c",E_="b",Xg="rr",y_="ce",Eu={BITRATE_CHANGE:g_,ERROR:Iw,RESPONSE_RECEIVED:Xg,CUSTOM_EVENT:y_},b_=new Map([[Sw,"sta"],[v_,"pr"],[Rw,"cid"],[E_,"bg"],[g_,"br"]]),Zg="event",Jg="request",T_=["cen","e","h","ts"],__=["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"],Lw=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function e0(i){return Lw.test(i)}var xw=new Set(__);function A_(i){return xw.has(i)||e0(i)}var S_=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],kw=new Set(S_);function I_(i){return kw.has(i)}var Dw=new Set(T_);function Cw(i){return A_(i)||I_(i)||Dw.has(i)}var ww=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),hc=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Mw=new Set(hc);function Pw(i){return Mw.has(i)||e0(i)}var Ow=new Set(["ot","sf","st","e","sta"]);function Nw(i){return Ow.has(i)}function Uw(i){return typeof i=="number"?Q(i):i!=null&&i!==""&&i!==!1}var Fw={[Zg]:Cw,[Jg]:A_};function R_(i,e){if(Array.isArray(i)){let t;return e&&(t=i.find(s=>{var r;return((r=s.params)==null?void 0:r.ot)===e})),t||(t=i[0]),R_(t)}return i instanceof ci?i.value:i}function Bw(i){let e={};for(let[s,r]of Object.entries(i)){if(r==null){e[s]=r;continue}if(s==="nor"){let n=(Array.isArray(r)?r:[r])[0];if(n instanceof ci){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else ww.has(s)?e[s]=R_(r,i.ot):e[s]=r}return e}function L_(i,e={}){let t={};if(i==null||typeof i!="object")return t;let s=e.version||i.v||yl,r=e.reportingMode||Jg,n=s===1?Bw(i):i,a=s===1?Pw:Fw[r],o=Object.keys(n).filter(a);n.e&&n.e!==Xg&&(o=o.filter(f=>!I_(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let d=r===Zg;if(d){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===y_&&o.push("cen");let m=f?b_.get(f):void 0;m&&n[m]!=null&&!o.includes(m)&&o.push(m)}if(o.length===0)return t;s>1&&!o.includes("v")&&o.push("v");let u={version:s,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(let f of o){var c,h;let m=n[f],p=(c=(h=e.formatters)==null?void 0:h[f])!=null?c:Aw[f];if(typeof p=="function"&&(m=p(m,u)),f==="v"){if(s===1)continue;m=s}if(f==="pr"&&m===1&&!(d&&n.e===v_))continue;d&&f==="ts"&&!Q(m)&&(m=Date.now());let g=d&&m===!1&&f==="bg"&&n.e===E_;!Uw(m)&&!g||(Nw(f)&&typeof m=="string"&&(m=new h_(m)),t[f]=m)}return t}var qs="CMCD-Object",ui="CMCD-Request",ca="CMCD-Session",Vi="CMCD-Status",$w={REQUEST:ui},Hw={ab:qs,br:qs,d:qs,lab:qs,lb:qs,ot:qs,tab:qs,tb:qs,tpb:qs,bl:ui,cs:ui,dfa:ui,dl:ui,ltc:ui,mtp:ui,nor:ui,nrr:ui,pb:ui,sn:ui,sta:ui,su:ui,tbl:ui,cid:ca,msd:ca,sf:ca,sid:ca,st:ca,v:ca,bg:Vi,bs:Vi,bsa:Vi,bsd:Vi,bsda:Vi,cdn:Vi,ec:Vi,nr:Vi,pr:Vi,pt:Vi,rtp:Vi};function Gw(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])==null||s.forEach(r=>e[r]=t),e},{})}function Kw(i,e){let t={};if(!i)return t;let s=Object.keys(i),r=e?Gw(e):{};for(let a of s){var n;let o=Hw[a]||r[a]||$w.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=i[a]}return t}function Vw(i,e){let t={},s=Kw(i,e);for(let[r,n]of Object.entries(s)){let a=p_(n,{whitespace:!1});a&&(t[r]=a)}return t}var Ob="CMCD";function x_(i){return p_(i,{whitespace:!1})}function Ww(i,e={}){return i?x_(L_(i,e)):""}var qw=30,Jp=[...hc,...__,...S_,...T_].filter((i,e,t)=>t.indexOf(i)===e),Yw="application/cmcd",jw=1,Yt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Wi={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},t0="query",k_="headers";function Nb(i,e,t){var s;let r=new Set((s=e.enabledKeys)!=null?s:[]);return{version:e.version||yl,reportingMode:i,filter:n=>r.has(n),baseUrl:t}}function zw(i,e){if(i===e)return!0;if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++){let s=i[t],r=e[t];if(s===r)continue;if(typeof s=="number"||typeof r=="number"||s.value!==r.value)return!1;let n=s.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 Qw=Object.is,Xw=i=>i,D_=Array.from(b_,([i,e])=>e==="br"?{event:i,field:e,equal:(t,s)=>t===void 0||s===void 0?t===s:zw(t,s),snapshot:t=>t.slice()}:{event:i,field:e,equal:Qw,snapshot:Xw}),Zw=new Map(D_.map(i=>[i.event,i]));function Jw(i){let{url:e}=i,t=dc(i,yw);return fetch(e,t)}function eM(i){let{version:e=yl,eventTargets:t=[],sid:s=oT(),transmissionMode:r=t0}=i,n=dc(i,bw);return ae(ae({},n),{},{version:e,transmissionMode:r,sid:s,eventTargets:t.reduce((a,o)=>{var l,d,u;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||yl,enabledKeys:((d=o.enabledKeys)==null?void 0:d.slice())||[],url:o.url,events:o.events.slice(),interval:(u=o.interval)!=null?u:qw,batchSize:o.batchSize||1}),a},[])})}var tM=class{constructor(i,e=Jw){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=eM(i),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((i,e)=>{if(this.disarmInterval(i),e.interval===0||!e.events.includes(Pb))return;let t=()=>{this.recordTargetEvent(i,e,Pb),this.processEventTargets()};i.intervalId=setInterval(t,e.interval*1e3),t()})}stop(i=!1){i&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(i){i.sid&&i.sid!==this.data.sid&&this.resetSession(),i.msd&&!isNaN(i.msd)&&(this.msd=i.msd),this.data=ae(ae(ae({},this.data),i),{},{msd:void 0});for(let e of D_)e.field in i&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(i,e={}){let t=Zw.get(i);if(t){let s=t.field,r=e[s];r!==void 0&&Qe(this.data,{[s]:r});let n=this.data[s];if(n===void 0||t.equal(n,this.lastEmitted[s]))return;Qe(this.lastEmitted,{[s]:t.snapshot(n)})}this.eventTargets.forEach((s,r)=>{this.recordTargetEvent(s,r,i,e)}),this.processEventTargets()}recordTargetEvent(i,e,t,s={}){var r;if(!e.events.includes(t))return;let n=ae(ae(ae({},this.data),s),{},{e:t,ts:(r=s.ts)!=null?r:Date.now(),sn:i.sn++});!isNaN(this.msd)&&!i.msdSent&&(n.msd=this.msd,i.msdSent=!0),i.queue.push(n)}recordResponseReceived(i,e={}){var t,s,r;let{request:n}=i,a=(t=e.url)!=null?t:n==null?void 0:n.url;if(!a)return;let o=new URL(a);o.searchParams.delete(Ob);let l={url:o.toString(),rc:i.status},d=i.resourceTiming;d&&(d.startTime!=null&&(l.ts=Math.round(this.timeOrigin+d.startTime),d.responseStart!=null&&(l.ttfb=Math.round(d.responseStart-d.startTime))),d.duration!=null&&(l.ttlb=Math.round(d.duration)));let u=(s=(r=n.customData)==null?void 0:r.cmcd)!=null?s:{};this.recordEvent(Xg,ae(ae(ae({},u),l),e))}applyRequestReport(i){var e;return(e=this.createRequestReport(i))!=null?e:i}isRequestReportingEnabled(){var i;return!!((i=this.config.enabledKeys)!=null&&i.length)}createRequestReport(i,e){var t;let{customData:s={},headers:r={}}=i,n=dc(i,Tw),a=ae(ae({},n),{},{headers:ae({},r),customData:ae(ae({},s),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=ae(ae(ae({},this.data),e),{},{sn:this.requestTarget.sn++}),d=Nb(Jg,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let u=a.customData.cmcd=L_(l,d);switch(this.config.transmissionMode){case t0:let c=x_(u);c&&(o.searchParams.set(Ob,c),a.url=o.toString());break;case k_:Qe(a.headers,Vw(u,d.customHeaderMap));break}return a}processEventTargets(i=!1){let e=!1;this.eventTargets.forEach((t,s)=>{let{queue:r}=t;if(!r.length||r.length<s.batchSize&&!i)return;let n=i?r.length:s.batchSize,a=r.splice(0,n);this.sendEventReport(s,a).catch(()=>{t.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(i,e){let t=Nb(Zg,i),{status:s}=await this.requester({url:i.url,method:"POST",headers:{"Content-Type":Yw},body:e.map(r=>Ww(r,t)).join(`
|
|
43
43
|
`)+`
|
|
44
|
-
`});if(s===410)this.disposeEventTarget(i);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(i){clearInterval(i.intervalId),i.intervalId=void 0}disposeEventTarget(i){let e=this.eventTargets.get(i);e&&(this.disarmInterval(e),this.eventTargets.delete(i))}resetSession(){this.eventTargets.forEach(i=>i.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},iM={HLS:"h"},ip={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function sM(i,e){return new ci(i,e)}new Set(hc);new Set(Jp);var rM=["includeKeys"];function Ub(i){return Object.keys(i).every(e0)}var eg=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(Wi.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Wi.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Wi.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Wi.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Wi.SEEKING)},this.onSeeked=()=>{var r;this.initialized&&(r=this.media)!=null&&r.paused&&this.setPlayerState(Wi.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Yt.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,d=this.hls.levels[o.level],u=this.getObjectType(o,d),c={d:(l||o).duration*1e3,ot:u};if(u===Yt.VIDEO||u===Yt.AUDIO||u===Yt.MUXED||u==null&&(o.type==="main"||o.type==="audio")){var n;let f=d.bitrate/1e3;c.br=[f];let{cmcd:m}=this.config,p=(n=m==null?void 0:m.rtpSafetyFactor)!=null?n:5;if(c.rtp=Math.round(f*p/100)*100,u===Yt.MUXED||u==null&&o.type==="main"){let b=this.getTopBandwidth()/1e3;Q(b)&&(c.tb=[b]);let E=this.getLowestBandwidth()/1e3;Q(E)&&(c.lb=[E])}let g=this.getBufferLength(o);if(Q(g)){var a;c.bl=[g];let b=((a=this.media)==null?void 0:a.playbackRate)||1;c.dl=Math.round(g/b/100)*100}this.playheadLevel&&(c.pb=[this.playheadLevel.bitrate/1e3]);let v=this.hls.maxAutoLevel;if(v>=0){let b=this.hls.levels[v];b&&(c.tpb=[b.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=[sM(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,d=l==null||(o=l.eventTargets)==null?void 0:o.some(u=>{var c;return(c=u.events)==null?void 0:c.includes(Eu.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!d))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(u){this.hls.logger.warn("Could not record fragment response CMCD data.",u)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:s}=this.config;if(s==null)return;let r=s.version||jw;if(this.reporter=new tM({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:r,transmissionMode:s.useHeaders===!0?k_:t0,enabledKeys:(e=s.includeKeys)!=null?e:[...r>=yl?Jp:hc],eventTargets:((t=s.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=dc(n,rM);return ae(ae({},o),{},{enabledKeys:a!=null?a:Jp})})},s.loader),this.reporter.update({sf:iM.HLS,sta:this.playerState}),s.reporterCallback){let n=this.reporter,a={updateCustomData:o=>{Ub(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{Ub(l)&&n.recordEvent(Eu.CUSTOM_EVENT,ae({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(y.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 s=this.media=t.media;this.setPlayerState(this.media.autoplay?Wi.STARTING:Wi.PRELOADING),Ye(s,"waiting",this.onWaiting),Ye(s,"play",this.onPlay),Ye(s,"playing",this.onPlaying),Ye(s,"pause",this.onPause),Ye(s,"seeking",this.onSeeking),Ye(s,"seeked",this.onSeeked),Ye(s,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(We(e,"waiting",this.onWaiting),We(e,"play",this.onPlay),We(e,"playing",this.onPlaying),We(e,"pause",this.onPause),We(e,"seeking",this.onSeeking),We(e,"seeked",this.onSeeked),We(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Wi.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(Wi.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Wi.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Eu.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;let r={br:[t.bitrate/1e3]},n=(s=t.details)==null?void 0:s.fragments[0];n&&(r.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Eu.BITRATE_CHANGE,r)}onLevelSwitched(e,t){let s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}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?ip.LOW_LATENCY:ip.LIVE:ip.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});let r=t.ot===Yt.INIT||t.ot===Yt.VIDEO||t.ot===Yt.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 s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;let{index:s,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===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){let{type:s}=e;if(s==="subtitle")return Yt.TIMED_TEXT;if(e.sn==="initSegment")return Yt.INIT;if(s==="audio")return Yt.AUDIO;if(s==="main"){if(e.hasStreams){let r=e.elementaryStreams;if(r.audiovideo)return Yt.MUXED;if(r.video)return Yt.VIDEO;if(r.audio)return Yt.AUDIO}if(t){let{audioCodec:r,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(r&&n)return Yt.MUXED;if(r)return Yt.AUDIO}if(n)return Yt.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,s=t.maxAutoLevel,r=s>-1?s+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,s=t.maxAutoLevel,r=s>-1?s+1:t.levels.length;return t.levels.slice(0,r).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),Q(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 s=e||t;return s?s.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let s=this.getEventBufferLength();Q(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(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,s=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:d}=l;this.loader.load(a,o,ae(ae({},l),{},{onSuccess:(u,c,h,f)=>{d(u,c,h,f),s(a.url,u,c)}}))}}}},nM=3e5,tg=class extends si{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if((s==null?void 0:s.action)===Gt.SendAlternateToPenaltyBox&&s.flags&Ht.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,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),s.resolved=this.pathwayId!==a,!s.resolved&&(t.details!==P.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: ${rt(n)} penalized: ${rt(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>nM&&delete s[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in s)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,YT(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Re.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Re.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(u=>{let c=new ht(u.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let m=C_(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Tn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),Fb(this.audioTracks,s,l,a),Fb(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(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 u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Ar(r,"_HLS_pathway",this.pathwayId),Ar(r,"_HLS_throughput",""+u)}let n={type:Re.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},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=u.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 b={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,b),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.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:(u,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,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Fb(i,e,t,s){i&&Object.keys(e).forEach(r=>{let n=i.filter(a=>a.groupId===r).map(a=>{let o=Qe({},a);return o.details=void 0,o.attrs=new ht(o.attrs),o.url=o.attrs.URI=C_(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function C_(i,e,t,s){if(e){let{[t]:o}=s;if(o){let l=o[e];if(l)return l}}let{HOST:r,PARAMS:n}=s,a=new self.URL(i);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(o=>{o&&Ar(a,o,n[o])}),a.href}var ig=class{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new qg,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}},_i=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}},ec=class i extends si{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=i.CDMCleanupPromise?[i.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{let{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.log(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Wo(this.config));let o=a.map(Ym).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=mu(a),d=this.activeLevelKeys();if(l===dt.FAIRPLAY&&s==="sinf")try{let m=ji(new Uint8Array(r)),p=$g(JSON.parse(m).sinf),g=ET(p);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(g.subarray(8,24))}catch(m){this.warn(`${n} Failed to parse sinf: ${m}`);return}else if(l===dt.PLAYREADY)o=Wg(new Uint8Array(r));else if(l===dt.WIDEVINE){let m=_T(r).filter(p=>p.systemId===BT.WIDEVINE);if(m.length){var u;let p=m[0];o=(u=p.kids)!=null&&u.length?p.kids[0]:null}}let c;if(o){let m=Ct(o);for(let p=0;p<d.length;p++){let g=d[p];if(g.keyId&&($u(o,g.keyId)||g.uri.replace(/-/g,"").indexOf(m)!==-1)){g.pssh||(g.scheme=s,g.pssh=new Uint8Array(r),g.keyId=o,_n.setKeyIdForUri(g.uri,o)),c=this.getSessionForKey(g,"encrypted-event-key-match");break}}}if(!c){if(d.length){var h,f;return(h=d[0]).scheme||(h.scheme=s),(f=d[0]).pssh||(f.pssh=new Uint8Array(r)),this.getSessionForKey(d[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ct(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(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof _i?o(c):o(new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return $T===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;let n=WD(e,t,s,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: ${rt(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.throwIfDestroyed(),this.log(`Access for key-system "${d.keySystem}" obtained`);let u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.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,s,r){let{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${Ct(s.keyId||[])} keyUri: ${s.uri} for "${r}"`;for(let d=0;d<n.length;d++){let u=n[d];if(!u.initialized&&u.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),u}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:r},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Ct(t.keyId||[])}
|
|
45
|
-
} (data length: ${s.byteLength})`),r.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ym(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let s=Ym(t);if(!s)throw new Error(`Unable to find format for key-system "${t}"`);return s})}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=Wo(this.config),s=e.map(mu).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}loadClear(e,t,s){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&&(!Et(e)||!Et(a)||e.sn<a.sn)||!s&&r==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=mu(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Wo(this.config);if(r.length)return this.getKeySystemAccess(r)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let r=sp(e,t[s]);if(r)return r}}loadKey(e){let t=e.decryptdata,s=this.getKeyStatus(t);if(s==="internal-error"){let o=Bb(s,t);return o.data.frag=e,this.error(`${o.message} (${Ct(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[Ct(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,s){let r=this.getSessionForKey(e,t);return r.catch(n=>this.handleError(n,s)),r.then(n=>e)}getSessionForKey(e,t){let s=this.findContextForKey(e);if(s!==void 0)return Promise.resolve(s);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 s=t.length;s--;){let r=t[s];if(sp(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:r})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let a=this.mediaKeySessions[n];if(sp(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(s,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,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,s){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${s} keyId: ${lM(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 _i){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ct(s.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=mu(e.keyFormat),s=t?[t]:Wo(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=Wo(this.config)),e.length===0)throw new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${rt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(s=>s.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 s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(s).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}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}filterInitData(e,t,s,r,n){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let d=o.call(this.hls,s,r,Qe({},e,{decryptdata:t,reason:n}),n);if(!d)throw new Error("Invalid response from configured generateRequest filter");t.scheme=d.initDataType?d.initDataType:"cenc";let u=d.initData?d.initData:null;return t.pssh=u?new Uint8Array(u):null,d}catch(d){var l;if(this.warn(d.message),(l=this.hls)!=null&&l.config.debug)throw d}return{initDataType:s,initData:r}}generateRequestWithPreferredKeySession(e,t,s,r,n){let a=this.getUsableKeyPromise(e,t,n);if(a)return a;let o=this.filterInitData(e,t,s,r,n);if(o&&(r=o.initData?o.initData:null,s=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,d=new ig;e.keyRequests[l]=d;let u=h=>{let f=e.mediaKeysSession;if(!f){let g=new Error("invalid state");d.errored=g;return}let{messageType:m,message:p}=h;d.status=m,this.log(`"${m}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,t,p).catch(g=>{d.errored=g,d.hasListeners||this.handleError(g),this.removeSession(e)}):m==="license-release"?e.keySystem===dt.FAIRPLAY&&this.updateKeySession(e,t,kp("acknowledged")).then(()=>this.removeSession(e)).catch(g=>this.handleError(g)):this.warn(`unhandled media key message type "${m}"`)};return d.onmessage=u,Ye(e.mediaKeysSession,"message",u),this.generateRequest(e,t,s,r,n,!1)}generateRequest(e,t,s,r,n,a){if(a){let f=this.filterInitData(e,t,s,r,n);f&&(r=f.initData?f.initData:r,s=f.initDataType)}let o=t.uri,l=e.keyRequests[o],d=Ct(t.keyId||[]),u=f=>{let m;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?m=Bb(f,t):f==="expired"?m=new Error(`key expired (keyId: ${d})`):f==="released"?m=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${d})`),m&&(l.errored=m,l.hasListeners||this.handleError(m))},c=f=>{if(!e.mediaKeysSession){let _=new Error("invalid state");l.errored=_;return}let p=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(p).some(_=>p[_]!=="status-pending"))return;let v=this.activeLevelKeys();for(let _=0;_<v.length;_++){let I=Ct(v[_].keyId||[]);if(p[I]==="expired"){var b;this.log(`Expired key ${rt(p)} in key-session "${(b=e.mediaKeysSession)==null?void 0:b.sessionId}"`),this.renewKeySession(t,e).catch(S=>this.handleError(S));break}}let E=p[d];if(E)u(E);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[d]||(T[d]=self.setTimeout(()=>{var I;if(!e.mediaKeysSession)return;let S=this.getKeyStatus(t);if(S&&S!=="status-pending"){var x;return this.log(`No status for keyId ${d} in key-session "${(x=e.mediaKeysSession)==null?void 0:x.sessionId}". Using session key-status ${S} from other session.`),u(S)}this.log(`key status for ${d} in key-session "${(I=e.mediaKeysSession)==null?void 0:I.sessionId}" timed out after 1000ms`),E="internal-error",u(E)},1e3)),this.log(`No status for keyId ${d} (${rt(p)}).`)}};l.onkeystatuseschange=c,Ye(e.mediaKeysSession,"keystatuseschange",c);let h=l.useable;return this.log(`Generating key-session request for "${n}" keyId: ${d} URI: ${o} (init data type: ${s} length: ${r.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,r).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${d} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>h).catch(f=>{var m;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let p=(m=f.data)==null?void 0:m.details;return(p===P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||p===P.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(g=>e.keyStatuses[g]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){let t={},s=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===dt.PLAYREADY&&a.length===16){let l=Ct(a);t[l]=r,UT(a)}let o=Ct(a);this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${s}"`),t[o]=r}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,r=new s(t),n=oM(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:Re.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:ae({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new _i({type:re.KEY_SYSTEM_ERROR,details:P.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,u,c)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(r=>this.updateKeySession(e,t,new Uint8Array(r)).catch(n=>{throw new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){let s=ji(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];let f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=r.querySelector("Challenge"),d=l==null?void 0:l.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return kp(atob(d))}setupLicenseXHR(e,t,s,r,n){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,ae(ae({},s),{},{decryptdata:r}),n))).catch(o=>{if(!s.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,ae(ae({},s),{},{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,s){return new Promise((r,n)=>{let a=aM(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,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(d.readyState===4)if(d.status===200){o.requestErrors=[];let u=d.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);let c=this.config.licenseResponseCallback;if(c)try{u=c.call(this.hls,d,a,ae(ae({},e),{},{decryptdata:t}))}catch(h){this.error(h)}r(u)}else{let u=l.errorRetry,c=u?u.maxNumRetry:0;if(o.requestErrors.push({status:d.status,message:d.statusText}),o.requestErrors.length>c||d.status>=400&&d.status<500)n(new _i({type:re.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:d,response:{url:a,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${a}). Status: ${d.status} (${d.statusText})`));else{let h=c-o.requestErrors.length;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t,s).then(r,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=d,this.setupLicenseXHR(d,a,e,t,s).then(({xhr:u,licenseChallenge:c})=>{e.keySystem==dt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(u,c)),u.send(c)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,Ye(s,"encrypted",this.onMediaEncrypted),Ye(s,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(We(e,"encrypted",this.onMediaEncrypted),We(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 s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,_n.clearKeyUriToKeyIdMap();let n=r.length;i.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:P.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:re.OTHER_ERROR,details:P.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 s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),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 s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);let{keyStatusTimeouts:r}=e;r&&Object.keys(r).forEach(o=>self.clearTimeout(r[o]));let{drmSystemOptions:n}=this.config;return(YD(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(y.ERROR,{type:re.OTHER_ERROR,details:P.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(y.ERROR,{type:re.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};ec.CDMCleanupPromise=void 0;function aM(i,e){let{drmSystems:t,widevineLicenseUrl:s}=e,r=t==null?void 0:t[i];if(r)return r.licenseUrl;if(i===dt.WIDEVINE&&s)return s}function oM(i,e){let{drmSystems:t}=e,s=t==null?void 0:t[i];if(s)return s.serverCertificateUrl}function lM(i){if(i.keyFormat===jt.FAIRPLAY)return i.uri;if(i.keyId===null)throw new Error("keyId is null");return Ct(i.keyId)}function sp(i,e){let t=i.keyId,s=e.mediaKeysSession;if(t&&s){let r=e.mediaKeysSession.keyStatuses;if(r.size)return r.has(t)?r.get(t):e.keyStatuses[Ct(t)]}}function Bb(i,e){let t=i==="output-restricted",s=t?P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:P.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new _i({type:re.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}var sg=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 s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,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)}},i0=function(){if(Hu!=null&&Hu.VTTCue)return self.VTTCue;let i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return t(i,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let u=arguments[d];for(let c in u)o[c]=u[c]}return o}function a(o,l,d){let u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=d,v=null,b="",E=!0,T="auto",_="start",I=50,S="middle",x=50,k="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return h},set:function(R){h=""+R}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return f},set:function(R){f=!!R}})),Object.defineProperty(u,"startTime",n({},c,{get:function(){return m},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");m=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},c,{get:function(){return p},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");p=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},c,{get:function(){return g},set:function(R){g=""+R,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return v},set:function(R){v=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return b},set:function(R){let D=s(R);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");b=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return E},set:function(R){E=!!R,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return T},set:function(R){if(typeof R!="number"&&R!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return _},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");_=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return I},set:function(R){if(R<0||R>100)throw new Error("Position must be between 0 and 100.");I=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return S},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"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(u,"align",n({},c,{get:function(){return k},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");k=D,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),rg=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function w_(i){function e(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=i.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 ng=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function M_(i,e,t,s){let r=s?i.split(s):[i];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 ag=new i0(0,0,""),yu=ag.align==="middle"?"middle":"center";function dM(i,e,t){let s=i;function r(){let o=w_(i);if(o===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new ng;M_(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case"vertical":d.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",!1),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",yu,"end"]);break;case"position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",yu,"end","line-left","line-right","auto"]);break;case"size":d.percent(h,f);break;case"align":d.alt(h,f,["start",yu,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&ag.line===-1&&(u=-1),l.line=u,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",yu);let c=d.get("position","auto");c==="auto"&&ag.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),a(),e.endTime=r(),a(),n(i,e)}function P_(i){return i.replace(/<br(?: \/)?>/gi,`
|
|
44
|
+
`});if(s===410)this.disposeEventTarget(i);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(i){clearInterval(i.intervalId),i.intervalId=void 0}disposeEventTarget(i){let e=this.eventTargets.get(i);e&&(this.disarmInterval(e),this.eventTargets.delete(i))}resetSession(){this.eventTargets.forEach(i=>i.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},iM={HLS:"h"},ip={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function sM(i,e){return new ci(i,e)}new Set(hc);new Set(Jp);var rM=["includeKeys"];function Ub(i){return Object.keys(i).every(e0)}var eg=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(Wi.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Wi.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Wi.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Wi.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Wi.SEEKING)},this.onSeeked=()=>{var r;this.initialized&&(r=this.media)!=null&&r.paused&&this.setPlayerState(Wi.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Yt.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,d=this.hls.levels[o.level],u=this.getObjectType(o,d),c={d:(l||o).duration*1e3,ot:u};if(u===Yt.VIDEO||u===Yt.AUDIO||u===Yt.MUXED||u==null&&(o.type==="main"||o.type==="audio")){var n;let f=d.bitrate/1e3;c.br=[f];let{cmcd:m}=this.config,p=(n=m==null?void 0:m.rtpSafetyFactor)!=null?n:5;if(c.rtp=Math.round(f*p/100)*100,u===Yt.MUXED||u==null&&o.type==="main"){let E=this.getTopBandwidth()/1e3;Q(E)&&(c.tb=[E]);let b=this.getLowestBandwidth()/1e3;Q(b)&&(c.lb=[b])}let g=this.getBufferLength(o);if(Q(g)){var a;c.bl=[g];let E=((a=this.media)==null?void 0:a.playbackRate)||1;c.dl=Math.round(g/E/100)*100}this.playheadLevel&&(c.pb=[this.playheadLevel.bitrate/1e3]);let v=this.hls.maxAutoLevel;if(v>=0){let E=this.hls.levels[v];E&&(c.tpb=[E.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=[sM(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,d=l==null||(o=l.eventTargets)==null?void 0:o.some(u=>{var c;return(c=u.events)==null?void 0:c.includes(Eu.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!d))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(u){this.hls.logger.warn("Could not record fragment response CMCD data.",u)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:s}=this.config;if(s==null)return;let r=s.version||jw;if(this.reporter=new tM({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:r,transmissionMode:s.useHeaders===!0?k_:t0,enabledKeys:(e=s.includeKeys)!=null?e:[...r>=yl?Jp:hc],eventTargets:((t=s.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=dc(n,rM);return ae(ae({},o),{},{enabledKeys:a!=null?a:Jp})})},s.loader),this.reporter.update({sf:iM.HLS,sta:this.playerState}),s.reporterCallback){let n=this.reporter,a={updateCustomData:o=>{Ub(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{Ub(l)&&n.recordEvent(Eu.CUSTOM_EVENT,ae({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(y.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 s=this.media=t.media;this.setPlayerState(this.media.autoplay?Wi.STARTING:Wi.PRELOADING),Ye(s,"waiting",this.onWaiting),Ye(s,"play",this.onPlay),Ye(s,"playing",this.onPlaying),Ye(s,"pause",this.onPause),Ye(s,"seeking",this.onSeeking),Ye(s,"seeked",this.onSeeked),Ye(s,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(We(e,"waiting",this.onWaiting),We(e,"play",this.onPlay),We(e,"playing",this.onPlaying),We(e,"pause",this.onPause),We(e,"seeking",this.onSeeking),We(e,"seeked",this.onSeeked),We(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Wi.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(Wi.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Wi.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Eu.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;let r={br:[t.bitrate/1e3]},n=(s=t.details)==null?void 0:s.fragments[0];n&&(r.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Eu.BITRATE_CHANGE,r)}onLevelSwitched(e,t){let s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}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?ip.LOW_LATENCY:ip.LIVE:ip.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});let r=t.ot===Yt.INIT||t.ot===Yt.VIDEO||t.ot===Yt.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 s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;let{index:s,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===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){let{type:s}=e;if(s==="subtitle")return Yt.TIMED_TEXT;if(e.sn==="initSegment")return Yt.INIT;if(s==="audio")return Yt.AUDIO;if(s==="main"){if(e.hasStreams){let r=e.elementaryStreams;if(r.audiovideo)return Yt.MUXED;if(r.video)return Yt.VIDEO;if(r.audio)return Yt.AUDIO}if(t){let{audioCodec:r,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(r&&n)return Yt.MUXED;if(r)return Yt.AUDIO}if(n)return Yt.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,s=t.maxAutoLevel,r=s>-1?s+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,s=t.maxAutoLevel,r=s>-1?s+1:t.levels.length;return t.levels.slice(0,r).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),Q(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 s=e||t;return s?s.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let s=this.getEventBufferLength();Q(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(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,s=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:d}=l;this.loader.load(a,o,ae(ae({},l),{},{onSuccess:(u,c,h,f)=>{d(u,c,h,f),s(a.url,u,c)}}))}}}},nM=3e5,tg=class extends si{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if((s==null?void 0:s.action)===Gt.SendAlternateToPenaltyBox&&s.flags&Ht.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,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),s.resolved=this.pathwayId!==a,!s.resolved&&(t.details!==P.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: ${rt(n)} penalized: ${rt(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>nM&&delete s[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in s)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,YT(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Re.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Re.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(u=>{let c=new ht(u.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let m=C_(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Tn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),Fb(this.audioTracks,s,l,a),Fb(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(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 u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Ar(r,"_HLS_pathway",this.pathwayId),Ar(r,"_HLS_throughput",""+u)}let n={type:Re.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},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=u.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 E={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.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:(u,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,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Fb(i,e,t,s){i&&Object.keys(e).forEach(r=>{let n=i.filter(a=>a.groupId===r).map(a=>{let o=Qe({},a);return o.details=void 0,o.attrs=new ht(o.attrs),o.url=o.attrs.URI=C_(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function C_(i,e,t,s){if(e){let{[t]:o}=s;if(o){let l=o[e];if(l)return l}}let{HOST:r,PARAMS:n}=s,a=new self.URL(i);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(o=>{o&&Ar(a,o,n[o])}),a.href}var ig=class{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new qg,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}},_i=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}},ec=class i extends si{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=i.CDMCleanupPromise?[i.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{let{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.log(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Wo(this.config));let o=a.map(Ym).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=mu(a),d=this.activeLevelKeys();if(l===dt.FAIRPLAY&&s==="sinf")try{let m=ji(new Uint8Array(r)),p=$g(JSON.parse(m).sinf),g=ET(p);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(g.subarray(8,24))}catch(m){this.warn(`${n} Failed to parse sinf: ${m}`);return}else if(l===dt.PLAYREADY)o=Wg(new Uint8Array(r));else if(l===dt.WIDEVINE){let m=_T(r).filter(p=>p.systemId===BT.WIDEVINE);if(m.length){var u;let p=m[0];o=(u=p.kids)!=null&&u.length?p.kids[0]:null}}let c;if(o){let m=Ct(o);for(let p=0;p<d.length;p++){let g=d[p];if(g.keyId&&($u(o,g.keyId)||g.uri.replace(/-/g,"").indexOf(m)!==-1)){g.pssh||(g.scheme=s,g.pssh=new Uint8Array(r),g.keyId=o,_n.setKeyIdForUri(g.uri,o)),c=this.getSessionForKey(g,"encrypted-event-key-match");break}}}if(!c){if(d.length){var h,f;return(h=d[0]).scheme||(h.scheme=s),(f=d[0]).pssh||(f.pssh=new Uint8Array(r)),this.getSessionForKey(d[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ct(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(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof _i?o(c):o(new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return $T===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;let n=WD(e,t,s,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: ${rt(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.throwIfDestroyed(),this.log(`Access for key-system "${d.keySystem}" obtained`);let u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.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,s,r){let{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${Ct(s.keyId||[])} keyUri: ${s.uri} for "${r}"`;for(let d=0;d<n.length;d++){let u=n[d];if(!u.initialized&&u.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),u}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:r},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Ct(t.keyId||[])}
|
|
45
|
+
} (data length: ${s.byteLength})`),r.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ym(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let s=Ym(t);if(!s)throw new Error(`Unable to find format for key-system "${t}"`);return s})}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=Wo(this.config),s=e.map(mu).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}loadClear(e,t,s){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&&(!Et(e)||!Et(a)||e.sn<a.sn)||!s&&r==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=mu(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Wo(this.config);if(r.length)return this.getKeySystemAccess(r)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let r=sp(e,t[s]);if(r)return r}}loadKey(e){let t=e.decryptdata,s=this.getKeyStatus(t);if(s==="internal-error"){let o=Bb(s,t);return o.data.frag=e,this.error(`${o.message} (${Ct(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[Ct(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,s){let r=this.getSessionForKey(e,t);return r.catch(n=>this.handleError(n,s)),r.then(n=>e)}getSessionForKey(e,t){let s=this.findContextForKey(e);if(s!==void 0)return Promise.resolve(s);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 s=t.length;s--;){let r=t[s];if(sp(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:r})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let a=this.mediaKeySessions[n];if(sp(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(s,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,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,s){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${s} keyId: ${lM(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 _i){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ct(s.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=mu(e.keyFormat),s=t?[t]:Wo(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=Wo(this.config)),e.length===0)throw new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${rt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(s=>s.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 s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(s).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}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}filterInitData(e,t,s,r,n){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let d=o.call(this.hls,s,r,Qe({},e,{decryptdata:t,reason:n}),n);if(!d)throw new Error("Invalid response from configured generateRequest filter");t.scheme=d.initDataType?d.initDataType:"cenc";let u=d.initData?d.initData:null;return t.pssh=u?new Uint8Array(u):null,d}catch(d){var l;if(this.warn(d.message),(l=this.hls)!=null&&l.config.debug)throw d}return{initDataType:s,initData:r}}generateRequestWithPreferredKeySession(e,t,s,r,n){let a=this.getUsableKeyPromise(e,t,n);if(a)return a;let o=this.filterInitData(e,t,s,r,n);if(o&&(r=o.initData?o.initData:null,s=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,d=new ig;e.keyRequests[l]=d;let u=h=>{let f=e.mediaKeysSession;if(!f){let g=new Error("invalid state");d.errored=g;return}let{messageType:m,message:p}=h;d.status=m,this.log(`"${m}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,t,p).catch(g=>{d.errored=g,d.hasListeners||this.handleError(g),this.removeSession(e)}):m==="license-release"?e.keySystem===dt.FAIRPLAY&&this.updateKeySession(e,t,kp("acknowledged")).then(()=>this.removeSession(e)).catch(g=>this.handleError(g)):this.warn(`unhandled media key message type "${m}"`)};return d.onmessage=u,Ye(e.mediaKeysSession,"message",u),this.generateRequest(e,t,s,r,n,!1)}generateRequest(e,t,s,r,n,a){if(a){let f=this.filterInitData(e,t,s,r,n);f&&(r=f.initData?f.initData:r,s=f.initDataType)}let o=t.uri,l=e.keyRequests[o],d=Ct(t.keyId||[]),u=f=>{let m;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?m=Bb(f,t):f==="expired"?m=new Error(`key expired (keyId: ${d})`):f==="released"?m=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${d})`),m&&(l.errored=m,l.hasListeners||this.handleError(m))},c=f=>{if(!e.mediaKeysSession){let _=new Error("invalid state");l.errored=_;return}let p=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(p).some(_=>p[_]!=="status-pending"))return;let v=this.activeLevelKeys();for(let _=0;_<v.length;_++){let I=Ct(v[_].keyId||[]);if(p[I]==="expired"){var E;this.log(`Expired key ${rt(p)} in key-session "${(E=e.mediaKeysSession)==null?void 0:E.sessionId}"`),this.renewKeySession(t,e).catch(S=>this.handleError(S));break}}let b=p[d];if(b)u(b);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[d]||(T[d]=self.setTimeout(()=>{var I;if(!e.mediaKeysSession)return;let S=this.getKeyStatus(t);if(S&&S!=="status-pending"){var x;return this.log(`No status for keyId ${d} in key-session "${(x=e.mediaKeysSession)==null?void 0:x.sessionId}". Using session key-status ${S} from other session.`),u(S)}this.log(`key status for ${d} in key-session "${(I=e.mediaKeysSession)==null?void 0:I.sessionId}" timed out after 1000ms`),b="internal-error",u(b)},1e3)),this.log(`No status for keyId ${d} (${rt(p)}).`)}};l.onkeystatuseschange=c,Ye(e.mediaKeysSession,"keystatuseschange",c);let h=l.useable;return this.log(`Generating key-session request for "${n}" keyId: ${d} URI: ${o} (init data type: ${s} length: ${r.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,r).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${d} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>h).catch(f=>{var m;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let p=(m=f.data)==null?void 0:m.details;return(p===P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||p===P.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(g=>e.keyStatuses[g]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){let t={},s=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===dt.PLAYREADY&&a.length===16){let l=Ct(a);t[l]=r,UT(a)}let o=Ct(a);this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${s}"`),t[o]=r}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,r=new s(t),n=oM(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:Re.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:ae({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new _i({type:ne.KEY_SYSTEM_ERROR,details:P.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,u,c)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(r=>this.updateKeySession(e,t,new Uint8Array(r)).catch(n=>{throw new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){let s=ji(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];let f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=r.querySelector("Challenge"),d=l==null?void 0:l.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return kp(atob(d))}setupLicenseXHR(e,t,s,r,n){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,ae(ae({},s),{},{decryptdata:r}),n))).catch(o=>{if(!s.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,ae(ae({},s),{},{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,s){return new Promise((r,n)=>{let a=aM(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,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(d.readyState===4)if(d.status===200){o.requestErrors=[];let u=d.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);let c=this.config.licenseResponseCallback;if(c)try{u=c.call(this.hls,d,a,ae(ae({},e),{},{decryptdata:t}))}catch(h){this.error(h)}r(u)}else{let u=l.errorRetry,c=u?u.maxNumRetry:0;if(o.requestErrors.push({status:d.status,message:d.statusText}),o.requestErrors.length>c||d.status>=400&&d.status<500)n(new _i({type:ne.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:d,response:{url:a,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${a}). Status: ${d.status} (${d.statusText})`));else{let h=c-o.requestErrors.length;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t,s).then(r,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=d,this.setupLicenseXHR(d,a,e,t,s).then(({xhr:u,licenseChallenge:c})=>{e.keySystem==dt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(u,c)),u.send(c)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,Ye(s,"encrypted",this.onMediaEncrypted),Ye(s,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(We(e,"encrypted",this.onMediaEncrypted),We(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 s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,_n.clearKeyUriToKeyIdMap();let n=r.length;i.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:ne.OTHER_ERROR,details:P.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:ne.OTHER_ERROR,details:P.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 s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),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 s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);let{keyStatusTimeouts:r}=e;r&&Object.keys(r).forEach(o=>self.clearTimeout(r[o]));let{drmSystemOptions:n}=this.config;return(YD(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(y.ERROR,{type:ne.OTHER_ERROR,details:P.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(y.ERROR,{type:ne.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};ec.CDMCleanupPromise=void 0;function aM(i,e){let{drmSystems:t,widevineLicenseUrl:s}=e,r=t==null?void 0:t[i];if(r)return r.licenseUrl;if(i===dt.WIDEVINE&&s)return s}function oM(i,e){let{drmSystems:t}=e,s=t==null?void 0:t[i];if(s)return s.serverCertificateUrl}function lM(i){if(i.keyFormat===jt.FAIRPLAY)return i.uri;if(i.keyId===null)throw new Error("keyId is null");return Ct(i.keyId)}function sp(i,e){let t=i.keyId,s=e.mediaKeysSession;if(t&&s){let r=e.mediaKeysSession.keyStatuses;if(r.size)return r.has(t)?r.get(t):e.keyStatuses[Ct(t)]}}function Bb(i,e){let t=i==="output-restricted",s=t?P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:P.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new _i({type:ne.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}var sg=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 s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,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)}},i0=function(){if(Hu!=null&&Hu.VTTCue)return self.VTTCue;let i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return t(i,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let u=arguments[d];for(let c in u)o[c]=u[c]}return o}function a(o,l,d){let u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=d,v=null,E="",b=!0,T="auto",_="start",I=50,S="middle",x=50,k="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return h},set:function(R){h=""+R}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return f},set:function(R){f=!!R}})),Object.defineProperty(u,"startTime",n({},c,{get:function(){return m},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");m=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},c,{get:function(){return p},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");p=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},c,{get:function(){return g},set:function(R){g=""+R,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return v},set:function(R){v=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return E},set:function(R){let D=s(R);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return b},set:function(R){b=!!R,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return T},set:function(R){if(typeof R!="number"&&R!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return _},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");_=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return I},set:function(R){if(R<0||R>100)throw new Error("Position must be between 0 and 100.");I=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return S},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"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(u,"align",n({},c,{get:function(){return k},set:function(R){let D=r(R);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");k=D,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),rg=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function w_(i){function e(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=i.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 ng=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function M_(i,e,t,s){let r=s?i.split(s):[i];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 ag=new i0(0,0,""),yu=ag.align==="middle"?"middle":"center";function dM(i,e,t){let s=i;function r(){let o=w_(i);if(o===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new ng;M_(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case"vertical":d.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",!1),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",yu,"end"]);break;case"position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",yu,"end","line-left","line-right","auto"]);break;case"size":d.percent(h,f);break;case"align":d.alt(h,f,["start",yu,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&ag.line===-1&&(u=-1),l.line=u,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",yu);let c=d.get("position","auto");c==="auto"&&ag.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),a(),e.endTime=r(),a(),n(i,e)}function P_(i){return i.replace(/<br(?: \/)?>/gi,`
|
|
46
46
|
`)}var og=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new rg,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 s(){let n=t.buffer,a=0;for(n=P_(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
48
|
`&&++a,t.buffer=n.slice(a),o}function r(n){M_(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();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=s(),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 i0(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{dM(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+=`
|
|
@@ -50,14 +50,14 @@ transfer tracks: ${rt(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!nT(r,s)){t.media
|
|
|
50
50
|
|
|
51
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 el(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}var uM=/\r\n|\n\r|\n|\r/g,$b="Missing initPTS for VTT ",cM=function(e){let t=parseInt(e.slice(-3)),s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Q(t)||!Q(s)||!Q(r)||!Q(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*r,t+=60*60*1e3*n,t};function s0(i,e,t){return el(i.toString())+el(e.toString())+el(t)}function hM(i,e,t,s,r,n,a){let o=new og,l=Si(new Uint8Array(i)).trim().replace(uM,`
|
|
52
52
|
`).split(`
|
|
53
|
-
`),d=[],u=e?$C(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,m=!1,p,g=!0;o.oncue=function(v){let
|
|
54
|
-
`)}),o.flush()}var lg="stpp.ttml.im1t",O_=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,N_=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,fM={left:"start",center:"center",right:"end",start:"start",end:"end"};function Hb(i,e,t,s){let r=Ee(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>Si(o)),a=BC(e.baseTime,1,e.timescale);try{n.forEach(o=>t(mM(o,a)))}catch(o){s(o)}}function mM(i,e){let r=new DOMParser().parseFromString(i,"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=Gb(rp(r,"styling","style")),d=Gb(rp(r,"layout","region")),u=rp(r,"body","[begin]");return[].map.call(u,c=>{let h=U_(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=ap(c.getAttribute("begin"),a),m=ap(c.getAttribute("dur"),a),p=ap(c.getAttribute("end"),a);if(f===null)throw Kb(c);if(p===null){if(m===null)throw Kb(c);p=f+m}let g=new i0(f-e,p-e,h);g.id=s0(g.startTime,g.endTime,g.text);let v=d[c.getAttribute("region")],
|
|
55
|
-
`:(n=s.childNodes)!=null&&n.length?U_(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function pM(i,e,t){let s="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=np(e,s,l)||np(i,s,l)||np(r,s,l);return d&&(o[l]=d),o},{})}function np(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Kb(i){return new Error(`Could not parse ttml timestamp ${i}`)}function ap(i,e){if(!i)return null;let t=w_(i);return t===null&&(O_.test(i)?t=gM(i,e):N_.test(i)&&(t=vM(i,e))),t}function gM(i,e){let t=O_.exec(i),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function vM(i,e){let t=N_.exec(i),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}function r0(i,e,t,s="",r="disabled"){let n=i.ownerDocument.createElement("track");return n.kind=e,n.label=t,s&&(n.srclang=s),n.src="data:,WEBVTT",n.track.mode=r,i.appendChild(n),n}function EM(i){return i.forced&&dD()?"forced":i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function dg(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){$e.debug(`[texttrack-utils]: ${s}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){$e.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function ug(i,e,t,s){let r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){let n=bM(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function yM(i,e){if(e<=i[0].startTime)return 0;let t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function bM(i,e,t){let s=[],r=yM(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){let o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}var cg=class extends gl{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,s=!1;if(this.currentTrack){var r;let o=(r=this.currentTrack.trackNode)==null?void 0:r.track.mode;o==="showing"?(t=this.trackId,s=!0):o==="hidden"&&(t=this.trackId)}if(!s)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(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)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=r0(this.media,EM(s),s.name,s.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 s=t.media;this.media=s;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} 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 ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=s;let a=[];if(this.tracks.forEach(u=>{(u.textCodec===lg?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(u.groupId)>-1?(u.id=a.length,a.push(u)):u.trackNode&&(u.trackNode.remove(),u.trackNode=void 0))}),a.length===this.tracksInGroup.length){let u=!1;for(let c=0;c<a.length;c++)if(a[c]!==this.tracksInGroup[c]){u=!0;break}if(!u)return}a.length&&this.selectDefaultTrack&&!a.some(u=>u.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 u=ps(o,a);if(u>-1)n=a[u];else{let c=ps(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||yn(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(vl(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(vl(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Re.SUBTITLE_TRACK&&t.context.id===this.trackId&&dl(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 s=this.currentTrack;if(s&&yn(e,s))return s;let r=ps(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),n}else{if(s)return null;{let n=ps(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 s=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 ${s} "${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:s,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 s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",r=t.trackNode.track;r.mode!==s&&(r.mode=s)}})}setSubtitleTrack(e,t=!1){let s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,n=s[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){r&&this.hls.trigger(y.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:d,type:u,url:c}=n;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:u,url:c});let h=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(h)}},Lu=2,TM=100,hg=class extends Fu{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),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(TM),this.mediaSource=t.mediaSource;let s=this.media=t.media;Ye(s,"playing",this.onMediaPlaying),Ye(s,"waiting",this.onMediaWaiting),Ye(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(We(s,"playing",this.onMediaPlaying),We(s,"waiting",this.onMediaWaiting),We(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}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 s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=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&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.skipRetry=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(!be.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let c=be.bufferInfo(a,e,0),h=this.fragmentTracker;h&&this.hls&&qb(c,e,h,this.hls);let f=c.nextStart||0;if(o&&h&&this.hls){let I=Vb(this.hls.inFlightFragments,e),S=c.len>Lu,x=!f||I||f-e>Lu&&!h.getPartialFragment(e);if(S||x)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&h){if(!(c.len>0)&&!f)return;let S=Math.max(f,c.start||0)-e,k=!!(m!=null&&m.live)?m.targetduration*2:Lu,R=Qo(e,h);if(S>0&&(S<=k||R)){a.paused||this._trySkipBufferHole(R);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,b=this.stalled;if(b===null)if(v>0&&g-v<p)b=this.stalled=v;else{this.stalled=g;return}let E=g-b;if(!o&&(E>=p||v&&this.moved)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.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;if(a.currentTime!==e){let I=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${I} > ${e}`);return}}let _=be.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(_,E,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){let n=be.bufferedInfo(be.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=be.timeRangesToArray(r),o=be.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=be.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=Qo(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=be.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=Qo(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<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 s=this.fragmentTracker,r=e.nextStart;if(s&&r){let n=s.getFragAtPos(t,te.MAIN),a=s.getFragAtPos(r,te.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${rt(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:s,hls:r}=this,n=r==null?void 0:r.config;if(!s||!t||!n)return 0;let a=s.currentTime,o=be.bufferInfo(s,a,0);qb(o,a,t,r);let l=a<o.start?o.start:o.nextStart;if(l){let u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let v=!1;if(a===0){let b=t.getAppendedFrag(0,te.MAIN);b&&l<b.end&&(v=!0)}if(!v&&e){var d;if(!((d=r.loadLevelObj)!=null&&d.details)||Vb(r.inFlightFragments,l))return 0;let E=!1,T=e.end;for(;T<l;){let _=Qo(T,t),I=_?_.duration:0;if(I>0)T+=I;else{E=!0;break}}if(E)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:m}=n,p=++this.skipRetry>f,g=Math.max(l,a)+m;if(p||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${g}`),this.moved=!0,s.currentTime=g),!(e!=null&&e.gap)||p){let v=new Error(p?`Playhead still not moving after seeking over buffer hole from ${a} to ${g} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${g}`),b={type:re.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:p,error:v,reason:v.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?b.part=e:b.frag=e),r.trigger(y.ERROR,b)}return g}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!s||!n)return 0;let a=s.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),s.currentTime=o,t.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.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:re.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Vb(i,e){let t=Wb(i.main);if(t&&t.start<=e)return t;let s=Wb(i.audio);return s&&s.start<=e?s:null}function Wb(i){if(!i)return null;switch(i.state){case U.IDLE:case U.STOPPED:case U.ENDED:case U.ERROR:return null}return i.frag}function Qo(i,e){return e.getAppendedFrag(i,te.MAIN)||e.getPartialFragment(i)}function qb(i,e,t,s){let r=s.latestLevelDetails,n=Qo(e,t);if(Vu(s.config)&&!i.nextStart&&r&&n&&s.interstitialsManager){let a="type"in n?n:n.fragment,o=PT(r,a.sn);(o==null?void 0:o.level)===a.level&&zT(o,s.interstitialsManager.playerQueue,e)&&(i.nextStart=o.start)}}var _M=.25;function fg(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function op(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,rt(r?ae({type:r},s):s))}return n}var bu=(()=>{let i=fg();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),mg=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){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 r0(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=fg();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===ii.emsg&&!s||!r)continue;let d=dT(n[o].data),u=n[o].pts,c=u+n[o].duration;c>bu&&(c=bu),c-u<=0&&(c=u+_M);for(let f=0;f<d.length;f++){let m=d[f];if(!uT(m)){this.updateId3CueEnds(u,l);let p=op(a,u,c,m,l);p&&this.id3Track.track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let r=(s=this.id3Track)==null?void 0:s.track.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===bu&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===ii.audioId3&&l:r==="video"?d=u=>u.type===ii.emsg&&o:d=u=>u.type===ii.audioId3&&l||u.type===ii.emsg&&o,ug(n.track,t,s,d)}}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:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=fg();if(s&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=op(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.track.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>u.indexOf(g)===-1);for(let g=p.length;g--;){var f;let v=p[g],b=(f=c[v])==null?void 0:f.cues;delete c[v],b&&Object.keys(b).forEach(E=>{let T=b[E];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){let g=u[p],v=d[g],b=v.startTime,E=c[g],T=(E==null?void 0:E.cues)||{},_=(E==null?void 0:E.durationKnown)||!1,I=bu,{duration:S,endDate:x}=v;if(x&&S!==null)I=b+S,_=!0;else if(v.endOnNext&&!_){let R=u.reduce((D,w)=>{if(w!==v.id){let N=d[w];if(N.class===v.class&&N.startDate>v.startDate&&(!D||v.startDate<D.startDate))return N}return D},null);R&&(I=R.startTime,_=!0)}let k=Object.keys(v.attr);for(let R=0;R<k.length;R++){let D=k[R];if(!GD(D))continue;let w=T[D];if(w)_&&!(E!=null&&E.durationKnown)?w.endTime=I:Math.abs(w.startTime-b)>.01&&(w.startTime=b,w.endTime=I);else if(o){let N=v.attr[D];KD(D)&&(N=cT(N));let H=op(o,b,I,{key:D,data:N},ii.dateRange);H&&(H.id=g,this.id3Track.track.addCue(H),T[D]=H,a&&(D==="X-ASSET-LIST"||D==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:v,durationKnown:_}}}}};function F_(){return self.SourceBuffer||self.WebKitSourceBuffer}function B_(){if(!Ir())return!1;let e=F_();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function AM(){if(!B_())return!1;let i=Ir();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(ll(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(ll(e,"audio"))))}function SM(){var i;let e=F_();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var cs={DISABLED:0,SWITCHING:1,SWITCHED:2},IM=100,tc=class extends hl{constructor(e,t,s){super(e,t,s,"stream-controller",te.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=cs.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||!Q(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,te.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(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:s,hls:r}=this;if(this.stopLoad(),this.setInterval(IM),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}s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=U.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=U.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case U.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=U.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=U.IDLE;break}break}case U.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===U.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:s,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(!(s!=null&&s[n]))return;let a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,p),this.state=U.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 d=a.details;if(!d||this.state===U.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=U.WAITING_LEVEL,this.startFragRequested=!1;return}let u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=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,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==ft.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?Je.AUDIO:Je.VIDEO,v=(g===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g)}f=this.getNextFragmentLoopLoading(f,d,o,te.MAIN,c)}f&&(this.exceedsMaxBuffer(o,c,f)||this.loadFragment(f,a,h))}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);r===ft.NOT_LOADED||r===ft.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,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==cs.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===cs.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let s=this.fragPlaying;if(s){let r=s.level;this.hls.trigger(y.FRAG_CHANGED,{frag:s,previousFrag:e}),(e==null?void 0:e.level)!==r&&this.hls.trigger(y.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===cs.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;Ye(s,"playing",this.onMediaPlaying),Ye(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(We(s,"playing",this.onMediaPlaying),We(s,"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(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=cs.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!SM(),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:s}=this;if(!s||this.state!==U.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=U.WAITING_LEVEL)}onLevelLoaded(e,t){var s;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 d=t.levelInfo,u=this.fragCurrent;u&&(this.state===U.FRAG_LOADING||this.state===U.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===U.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=U.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,m)=>{if(m>=o.startCC)return!0;delete this.initPTS[m]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)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&&s.duration>r&&(n<r||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.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 d;let c=be.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}let{nextStart:f}=be.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ju(this.hls,te.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,{decryptRange:g,byteRange:v}=Uu(s,r,this.iframesOnly),b=new cl(s.level,s.sn,s.stats.chunkCount,v?v.end-v.start:n.byteLength,m,p,s.duration,this.iframesOnly,g),E=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,b,E)}onAudioTrackSwitching(e,t){let s=this.hls,r=this.altAudio!==cs.DISABLED;if(Ou(t.url,s))this.altAudio=cs.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=cs.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=Ou(t.url,this.hls);if(s){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=s?cs.SWITCHED:cs.DISABLED,this.tick()}onBufferCreated(e,t){let s=t.tracks,r,n,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=s[o];d&&(this.videoBuffer=d.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:s,part:r}=t,n=s.type===te.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===U.PARSED&&(this.state=U.IDLE);return}let l=!1;if(Et(s)&&(l=!!s.gap&&!s.tagList.some(d=>d[0]==="GAP")),this.fragBufferedComplete(s,r),l){var a;s.stats.retry++;let d=(a=this.levels)==null?void 0:a[s.level];d&&d.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&be.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.MAIN,t);break;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Re.LEVEL&&(this.state=U.IDLE);break;case P.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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case P.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 P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=U.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Je.AUDIO||!this.altAudio){let s=(t===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,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,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&s&&(s+=r);let n=this.getLevelDetails(),a=be.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_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(s=>{let{hls:r}=this,n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=U.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,s),n.bitrateTest=!1}).catch(s=>{this.state===U.STOPPED||this.state===U.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=U.PARSING,f){let g=f.tracks;if(g){let T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,T,n),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}let v=f.initPTS,b=f.timescale,E=this.initPTS[o.cc];if(Q(v)&&(!E||E.baseTime!==v||E.timescale!==b)){let T=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:b,trackId:T};let _=this.initPTS.slice(0);s.trigger(y.INIT_PTS_FOUND,{timestampOffsets:_,frag:o,id:t,initPTS:v,timescale:b,trackId:T})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,b=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:E,endPTS:T,startDTS:_,endDTS:I}=u;if(l)l.elementaryStreams[u.type]={startPTS:E,endPTS:T,startDTS:_,endDTS:I};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){let S=this.getMainFwdBufferInfo(),x=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,k=u.firstKeyFramePTS?u.firstKeyFramePTS:E;if(!v&&x<k-this.config.maxBufferHole&&!b){this.backtrack(o);return}else b&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,I,!0)}else v&&E-(m.appliedTimelineOffset||0)>Lu&&(o.gap=!0);o.setElementaryStreamInfo(u.type,E,T,_,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||b)}else if(v||b)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=p;l&&(l.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),o.setElementaryStreamInfo(Je.AUDIO,g,v,b,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};s.trigger(y.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};s.trigger(y.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${Et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==U.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=Su(n.codec,d);if(u==="mp4a"&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&!lD()&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&uD()&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=te.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=te.MAIN;let d=a.codec;if((d==null?void 0:d.length)===4)switch(d){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||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),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(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,te.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=U.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 Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let s=this.getLevelDetails(),r=this.currentFrag||(s?Ea(null,s.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}},ic=class extends tc{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:s}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}this.state===U.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(y.BUFFERED_TO_END,this.onBufferedToEnd);let n=this.media;s&&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 s;let r=(s=this.getLevelDetails())==null?void 0:s.edge,n=r!==void 0?r:t.duration;if(e>=n&&(e=n-.01),be.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,te.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&s.length>1;){let n=s.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.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:s,payload:r}=e;this.cacheFragmentData&&!s&&r!=null&&r.byteLength&&!t.data&&Et(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if((r===ft.NOT_LOADED||r===ft.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,s)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let s=e.decryptdata;return(s==null?void 0:s.keyFormat)!=="identity"||!!s.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 s=e.stats=new il;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=U.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(y.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:s,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=U.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!r),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Ku(be.getBuffered(this.media)):"none"}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let s=this.media;if(s){let r=be.bufferInfo(s,e,0),n=r.len?r.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,te.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(y.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(y.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,s){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,te.MAIN);return!!(t!=null&&t.endList)}},pg=class extends ic{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 s=(t=this._img)==null?void 0:t.src;s&&self.URL.revokeObjectURL(s),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 U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}if(this.state===U.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===U.IDLE){let s=this.getBufferedAt(e);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{let s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){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 u=this.hls.levels[e.level];u!=null&&u.fragmentError&&(u.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(y.FRAG_BUFFERED,{frag:e,part:t,stats:h,id:e.type,chunkMeta:s})},n.onerror=()=>{this.handleError("Image decode error",e,t,s)};let l=n.src;l&&self.URL.revokeObjectURL(l);let d=new Blob([r],{type:"image/jpeg"});n.src=self.URL.createObjectURL(d)}else this.state=U.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,r){if(!this.hls)return;let n=new Error(e);this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:s,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,s,r){super.bufferFragmentData(e,t,s,r,!0);let n=Ee(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,s,r);return}let a=t;this.cacheSet(a,n[0]),this.updateImage(a,s,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 s=this.getAppendedFrag(t);if(s&&!zo(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},RM=10,LM="Image I-Frame player does not accept HTMLMediaElements",Yb={seekOnAppend:!0},Tu,lp,gg=class extends si{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,Tu||(Tu=xM(t)),lp||(lp=kM(Tu)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MANIFEST_LOADING,this.clearAsset,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.clearAsset,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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 s;let r=(s=this.hls)==null?void 0:s.pathwayPriority;t.length&&r&&this.iframeInstances.forEach(n=>{n.pathwayPriority=r})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===te.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;let r=this.hls;r&&r.hasEnoughToStart&&(((s=r.mainForwardBufferInfo)==null?void 0:s.len)||0)>RM&&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(Tu,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let s=(t=this.hls)==null?void 0:t.iframeVariants.filter(r=>r.imageCodec);return this.createInstance(lp,s,e,"image-")}createInstance(e,t,s,r){let{hls:n}=this;if(!n)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:u,bandwidthEstimate:c,sessionId:h}=n,{stats:f,variableList:m}=this;if(!(t!=null&&t.length)||!f||!a)return null;let p=`${r||""}iframe-player-${this.instanceCounter++}`,g=n.levels,v=d||g[u],b=CT(v,o.videoPreference),E=(v==null?void 0:v.pathwayId)||".",T=ae(ae({},o),{},{loggerId:p,primarySessionId:h,videoPreference:b,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},s),_=new e(T,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(I=>!I.url),this.iframeInstances.push(_),_.trigger(y.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:m}),_}};function xM(i){return class extends i{constructor(t,s,r,n){t.streamController||(t.streamController=ic),super(t),this._url=s,this.streamController.setInitPts(r),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,s=Yb){if(t<0)return;let r=ae(ae({},Yb),s);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,r)}}}function kM(i){return class extends i{constructor(t,s,r,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=pg),t.capLevelController=void 0,t.bufferController=void 0,super(t,s,r,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(LM)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var Sr=.025,sc=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function DM(i,e,t){return`${i.identifier}-${t+1}-${el(e)}`}var vg=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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return jb(t,e)?xu(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,s=xu(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=Q(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 jb(t,e)?xu(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)<Sr))}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"?sc.Range:sc.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 CM(this)}};function xu(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Sr)?e.start:e.start+e.duration}function jb(i,e){return e>i.start-Sr&&e<i.start+i.duration+Sr}function $_(i,e,t){let s=new self.URL(i,t);return s.protocol!=="data:"&&Ar(s,"_HLS_primary_id",e),s}function dp(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function CM(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function ha(i){let e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Eg=class{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=s,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 u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,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=$_(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=be.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=be.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 s=t-this.startOffset;if(s>0&&s<e)return s}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 s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ha(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},up=.033,yg=class extends si{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s,0):0}get duration(){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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];t&&t!=="primary"&&(n=n[t]);let a=n.start,o=s[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 s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){let n=s[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 s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){let s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){let a=s[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 s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t,s=0){let r=e.main.details,{dateRanges:n}=r,a=this.events,o=this.parseDateRanges(n,{url:r.url},t),l=Object.keys(n),d=a?a.filter(u=>l.indexOf(u.identifier)===-1):[];o.length&&o.sort((u,c)=>{let h=u.cue.pre,f=u.cue.post,m=c.cue.pre,p=c.cue.post;if(h&&!m)return-1;if(m&&!h||f&&!p)return 1;if(p&&!f)return-1;if(!h&&!m&&!f&&!p){let g=u.startTime,v=c.startTime;if(g!==v)return g-v}return u.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=o,d.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(e,d,s)}updateSchedule(e,t=[],s=0,r=!1){let n=this.events||[];if(n.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(n,e,s);(r||t.length||(a==null?void 0:a.length)!==o.length||o.some((d,u)=>Math.abs(d.playout.start-a[u].playout.start)>.005||Math.abs(d.playout.end-a[u].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){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 d=this.eventMap[o];d?d.setDateRange(l):(d=new vg(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t,s=0){let r=[],n=t.main.details,a=n.live?1/0:n.edge,o=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,u=0;if(e.forEach((c,h)=>{let f=c.cue.pre,m=c.cue.post,p=e[h-1]||null,g=c.appendInPlace,v=m?a:c.startOffset,b=c.duration,E=c.timelineOccupancy===sc.Range?b:0,T=f&&n.live?s+(c.resumeOffset||0):0,_=T||c.resumptionOffset,I=(p==null?void 0:p.startTime)===v,S=v+c.cumulativeDuration,x=g?S+b:v+_;if(f||!m&&v<=0){let R=u;u+=E,c.timelineStart=S;let D=o;o+=b,r.push({event:c,start:S,end:x,playout:{start:D,end:o},integrated:{start:R,end:u}})}else if(v<=a){if(!I){let w=v-d;if(w>up){let N=d,$=u;u+=w;let H=o;o+=w;let O={previousEvent:e[h-1]||null,nextEvent:c,start:N,end:N+w,playout:{start:H,end:o},integrated:{start:$,end:u}};r.push(O)}else w>0&&p&&(p.cumulativeDuration+=w,r[r.length-1].end=v)}m&&(x=S),c.timelineStart=S;let R=u;u+=E;let D=o;o+=b,r.push({event:c,start:S,end:x,playout:{start:D,end:o},integrated:{start:R,end:u}})}else return;let k=T||c.resumeTime;m||k>a?d=a:!f&&x&&c.appendInPlaceStarted&&k-x>up?d=x:d=k}),d<a){var l;let c=d,h=u,f=a-d;u+=f;let m=o;o+=f,r.push({previousEvent:((l=r[r.length-1])==null?void 0:l.event)||null,nextEvent:null,start:d,end:c+f,playout:{start:m,end:o},integrated:{start:h,end:u}})}this.setDurations(a,o,u)}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,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,r=s.live?1/0:s.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=Ea(null,s.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<up&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=Q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>Sr?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;let d=Ea(null,o.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let u=a==="audio"?.175:0;return Math.abs(d.start-s)<Sr+u||Math.abs(d.end-s)<Sr+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ti(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}var bg=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,r;try{r=$_(s,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,P.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(y.ERROR,f);return}t&&r.protocol!=="data:"&&Ar(r,"_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={type:Re.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.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 b=this.assignAssetListError(e,P.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(y.ERROR,b);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,P.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,P.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,u,c),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:re.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}};function zb(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function gn(i,e){return`[${i}] Advancing timeline position to ${e}`}var Tg=class extends si{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (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 d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=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);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
56
|
-
Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);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 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))),s.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(b){Math.abs(v)>Sr&&this.warn(`${b} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.indexOf(a.event.identifier)>-1){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 bg(e),this.schedule=new yg(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=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){We(e,"play",this.onPlay),We(e,"pause",this.onPause),We(e,"seeking",this.onSeeking),We(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;Ye(s,"seeking",this.onSeeking),Ye(s,"timeupdate",this.onTimeupdate),Ye(s,"play",this.onPlay),Ye(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(s);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 s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(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,s=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!==sc.Point){let b=s(f);(b==null?void 0:b.interstitial)===v&&(g+=b.assetItem.startOffset+b[p])}}else{let b=m==="bufferedPos"?a():e[m];g+=b-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),b=(m=e.schedule.items)==null?void 0:m[v],E=e.getBufferingPlayer(),T=E==null?void 0:E.interstitial,_=T==null?void 0:T.appendInPlace,I=g&&e.itemsMatch(g,b);if(g&&(_||I)){let S=s(e.playingAsset),x=(S==null?void 0:S.media)||e.primaryMedia;if(x){let k=h==="primary"?x.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),R=c-k,D=(_?k:x.currentTime)+R;if(D>=0&&(!S||_||D<=S.duration)){x.currentTime=D;return}}}if(b){let S=c;if(h!=="primary"){let k=b[h].start,R=c-k;S=b.start+R}let x=!e.isInterstitial(b);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(x||b.event.appendInPlace)){let k=e.media||(_?E==null?void 0:E.media:null);k&&(k.currentTime=S)}else if(g){let k=e.findItemIndex(g);if(v>k){let D=e.schedule.findJumpRestrictedIndex(k+1,v);if(D>k){e.setSchedulePosition(D);return}}let R=0;if(x)e.timelinePos=S,e.checkBuffer();else{let D=b.event.assetList,w=c-(b[h]||b).start;for(let N=D.length;N--;){let $=D[N];if($.duration&&w>=$.startOffset&&w<$.startOffset+$.duration){R=N;break}}}e.setSchedulePosition(v,R)}}},d=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},u={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=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};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 d()?u: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 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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.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||!Q(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${rt(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource,u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else{let m=this.getBufferingPlayer();m?(n=m.transferMedia(),this.detachedData=n,u=`${m}`):d?u="detached MediaSource":u="detached media"}if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${rt(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";if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`),!c&&!o){e.attachMedia(t);return}let h=c&&n?ae({},n):{media:t},f=this.schedule;if(f&&o){let m=e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:m||e.appendInPlace===!1}}if(!c&&l){let m=e,p=m.assetItem.timelineStart;if(p){let g=m.hls,v=Math.max(this.timelinePos-p,Number.EPSILON);g.startPosition!==v&&(this.log(`Set ${m} startPosition: ${v}`),g.config.startPosition=v,g.loadingEnabled&&g.startLoad(v))}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=s.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(gn("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(gn("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(gn("checkStart (playing item)",n.start));let a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let s=e.event,r=s.findAssetIndex(t),n=dp(s,r);if(!s.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&&!Q(e.resumeOffset)&&this.hls){let s=this.getLiveStartPos();if(t){let r=this.getBufferingPlayer(),n=r!=null&&r.interstitial.cue.pre?r.remaining:0;return s+n}return s}}getNextItemIndex(e,t){if(this.schedule){let s=this.livePrerollResumption(e.event,t);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){let r=dp(e,s);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 d=e.resumeTime;this.timelinePos<d&&(this.log(gn("advanceAfterAssetEnded",d)),this.timelinePos=d,e.appendInPlace&&!n[o].event&&this.hls.startLoad(d+.01),this.checkBuffer(this.bufferedPos<d)),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 s=this.schedule;if(!s)return;let r=t.parentIdentifier,n=s.getEvent(r);if(n){let a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ti(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,m=f?this.getAssetPlayer(f):null;if(m&&f&&(!this.eventItemsMatch(a,n)||t!==void 0&&f!==c.assetList[t].identifier)){var l;let p=c.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${c.assetList.length} ${ha(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:p,event:c,schedule:r.slice(0),scheduleIndex:e,player:m}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(f,n),m.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&m.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${Ti(a)}`),c.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once&&this.hls)){var d;this.updateSchedule();let p=(d=this.schedule)==null?void 0:d.items;if(n&&p){let g=this.findItemIndex(n),v=this.livePrerollResumption(c);if(v!==void 0){let b=v,E=this.getNextItemIndex(a);if(!this.isInterstitial(r[E])){var u;let T=(u=this.primaryDetails)==null?void 0:u.fragments;if(c.snapOptions.in&&T){let _=Ea(null,T,v);_&&(b=Math.min(Math.max(r[E].start,xu(b,_)),r[E].end))}}if(this.log(gn("live join (preroll)",b)),this.timelinePos=b,E!==g&&(E||E===0)){this.advanceSchedule(E,p,void 0,a,o);return}}this.advanceSchedule(g,p,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{let c=u.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 u=o.event;if(s===void 0){s=u.cue.pre?0:a.findAssetIndex(u,this.timelinePos);let m=dp(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ti(o)} ${u.appendInPlace?"append in place":""}`),u.hasPlayed=!1,this.hls.trigger(y.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&zb(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&zb(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,s){var r,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ti(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(gn("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!s)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ti(e)}`),this.hls.trigger(y.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,s){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,s):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:d}=o;if(r<l||r>d&&!s){let u=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${l}-${d}]) snapping to liveSync ${u}`),u||l}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){var e;let t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,r=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||s&&s-t<r?s||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:be.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(gn("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){let s=this.hls,{loadingEnabled:r,bufferingEnabled:n,startPosition:a}=s,o=s.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 d=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${d?Ti(d):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(e,t)}else n||s.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 s=this.hls.levels[t.level];if(!s.details)return;let r=ae(ae({},this.mediaSelection||this.altSelection),{},{main:s});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 d=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${d?Ti(d):null}`),(d==null?void 0:d.end)===1/0){let c=this.playingItem,h=this.isInterstitial(c)&&c.event.appendInPlace;this.hls.startLoad(Math.max(l,d.start),h)}else{let c=this.getBufferingPlayer();c&&c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(y.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ae(ae({},this.altSelection),{},{audio:s});return}let n=ae(ae({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ae(ae({},this.altSelection),{},{subtitles:s});return}let n=ae(ae({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){let s=Vy(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=Vy(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){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 s=0;s<t.length;s++){let r=t[s];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 s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let r=(s=this.schedule)==null?void 0:s.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 s=e.end+.25,r=be.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ti(e)} (was ${Ti(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let s=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;let r=this.mediaSelection;if(!r)return;let n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(r,[],n,e)}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let r=be.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){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 d;let u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.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>u&&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 s&&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,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:r,events:n}=s;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 ${Ti(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{let h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==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 s=e.event,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart,d=this.playingItem,u=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,h=0;if((!u||u.interstitial.cue.pre)&&this.primaryLive&&(h=this.getLiveStartPos(),u&&(h+=u.remaining)),h&&!(e.cue.pre||e.cue.post)){let m=h-l;m>0&&(c=Math.round(m*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${h?` live-start: ${h} start-offset: ${c} (timeline-start: ${l})`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);let f=this.assetListLoader.loadAssetList(e,c);f&&(e.assetListLoader=f)}else if(!a&&r){for(let d=t;d<r;d++){let u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let s=this.primaryDetails;if(s&&e>=s.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,r,n,a){let o={parentIdentifier:e.identifier,identifier:DM(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let r=this.hls,n=r.userConfig,a=r.loadLevelObj||r.levels[r.currentLevel],o=CT(a,n.videoPreference),l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){let T=this.timelinePos-t.timelineStart;if(T>=0){let _=t.duration;_&&T<_&&(u=T)}}let c=t.identifier,h=ae(ae({},n),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:d||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=Qe({},f,{contentId:el(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let m=new Eg(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0,g=T=>{if(T.live){let S=new Error(`Interstitials MUST be VOD assets ${e}`),x={fatal:!0,type:re.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:S},k=this.findEventIndex(e.identifier);this.handleAssetItemError(x,e,k,s,S.message);return}let _=T.edge-T.fragmentStart,I=t.duration;(p||I===null||_>I)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${I} > ${_}`),t.duration=_,this.updateSchedule())};m.on(y.LEVEL_UPDATED,(T,{details:_})=>g(_)),m.on(y.LEVEL_PTS_UPDATED,(T,{details:_})=>g(_)),m.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(T,_)=>{let I=this.getAssetPlayer(c);if(I&&_.tracks){I.off(y.BUFFER_CODECS,v),I.tracks=_.tracks;let S=this.primaryMedia;this.bufferingAsset===I.assetItem&&S&&!I.media&&this.bufferAssetPlayer(I,S)}};m.on(y.BUFFER_CODECS,v);let b=()=>{let T=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;let _=this.getEventItem(e.identifier);_&&this.advanceAssetBuffering(_,T.assetItem)};m.on(y.BUFFERED_TO_END,b);let E=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let I=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,I,T)};return m.once(y.MEDIA_ENDED,E(s)),m.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(y.ERROR,(T,_)=>{if(!this.schedule)return;let I=this.getAssetPlayer(c);if(_.details===P.BUFFER_STALLED_ERROR){if(I!=null&&I.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(_.details===P.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(_,e,this.findEventIndex(e.identifier),s,`Asset player error ${_.error} ${e}`)}),m.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let _=new Error(`Asset player destroyed unexpectedly ${c}`),I={fatal:!0,type:re.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(I,e,this.findEventIndex(e.identifier),s,_.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ha(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&Ti(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(u==null?void 0:u.identifier)!==l&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${ha(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s;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 d=(o==null?void 0:o.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!nT(d,e.tracks)){let u=new Error(`Asset ${ha(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),c={fatal:!0,type:re.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},h=r.findAssetIndex(n);this.handleAssetItemError(c,r,this.findEventIndex(r.identifier),h,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let r=s.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,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){let u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,r,n){if(e.details===P.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&ha(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=Qe({},e,{fatal:!1,errorAction:Zo(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});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==null?void 0:h.identifier)===o?this.advanceAfterAssetEnded(t,s,r):(f==null?void 0:f.identifier)===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,r=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ti(s)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);let d=this.updateItem(s,o);this.itemsMatch(s,d)&&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 s,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,u=0;o.forEach((m,p)=>{let g=parseFloat(m.DURATION);this.createAsset(n,p,u,l+u,g,m.URI),u+=g}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${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 m=this.findEventIndex(a),p=this.getEventItem(a);if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){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(p)}this.setSchedulePosition(m)}else if((f==null?void 0:f.identifier)===a){let m=n.assetList[0];if(m){let p=this.getAssetPlayer(m.identifier);if(f.appendInPlace){let g=this.primaryMedia;p&&g&&this.bufferAssetPlayer(p,g)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case P.ASSET_LIST_PARSING_ERROR:case P.ASSET_LIST_LOAD_ERROR:case P.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case P.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.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}}}},_g=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:s}=this,r=this.levelDetails;if(!s||!r||!this.hls)return;this.currentTime=s.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 d=this.targetLatency;if(d===null)return;let u=a-d,c=Math.min(this.maxLatency,d+r.targetduration),h=u<c,f=Vu(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(h&&u>.05&&this.forwardBufferLength>1&&!f){let m=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,g=Math.min(m,Math.max(1,p));this.changeMediaPlaybackRate(s,g)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,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 s=this.levelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:s,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,d=this.hls.userConfig,u=l&&r||s;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||u===0)&&(u=a!==void 0?a:o*n);let c=n;return u+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 s=this.levelDetails;if(s===null)return null;let r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.hls.config.lowLatencyMode&&s.partTarget||s.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 s=e.buffered.length;return(s?e.buffered.end(s-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),e.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,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),e.off(y.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 s;let r=this.hls,n=this.media||t.event.appendInPlace&&(r==null||(s=r.interstitialsManager)==null?void 0:s.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 s;t.details===P.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.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}},Qb=500,Ag=class extends hl{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",te.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=U.IDLE,this.setInterval(Qb),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:s,part:r,success:n}=t;if(!n)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,l=(r||s).start;for(let u=0;u<a.length;u++)if(l>=a[u].start&&l<=a[u].end){o=a[u];break}let d=l+(r||s).duration;if(o?o.end=d:(o={start:l,end:d},a.push(o)),!r||d>=s.end){let u=this.fragmentTracker.fragBuffered(s);r&&u&&(u.range.subs={time:[{startPTS:s.start,endPTS:d}],partial:!0}),Et(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:s,endOffset:r}=t;if(s===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(s,n,te.SUBTITLE)}}onError(e,t){let s=t.frag;(s==null?void 0:s.type)===te.SUBTITLE&&(t.details===P.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==U.STOPPED&&(this.state=U.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&u_(this.levels,t)){this.levels=t.map(s=>new Tn(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let r=new Tn(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,te.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((s=this.levels)!=null&&s.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!==U.STOPPED&&this.setInterval(Qb)}onSubtitleTrackLoaded(e,t){var s;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 d=this.mainDetails,u=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!d){this.startFragRequested=!1;return}if(l.details){var c;u=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}a.alignedSliding||(Gu(d,a,this),u=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,u),o===r&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:s,payload:r}=e;!s||!(r!=null&&r.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(r,t,s)}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e;this.fragContextChanged(t)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&pa(t.method))}decryptPayload(e,t,s){let r=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,Vg(r.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(y.FRAG_DECRYPTED,{frag:t,part:s,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=U.IDLE)})}doTick(){if(this.state===U.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:s,levels:r}=this,n=r[s],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,d=be.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:u,len:c}=d,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(u,a);if(!f)return;if(Et(f)){var t;let m=f.sn-a.startSN,p=a.fragments[m-1];f.cc===(p==null?void 0:p.cc)&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(p)===ft.NOT_LOADED&&(f=p)}this.loadFragment(f,n,u)}}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);(r===ft.NOT_LOADED||r===ft.PARTIAL)&&super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new Sg(this.tracksBuffered[this.currentTrackId]||[])}},Sg=class{constructor(e){this.buffered=void 0;let t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},wM={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},H_=i=>String.fromCharCode(wM[i]||i),Yi=15,qi=42,MM={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},PM={17:2,18:4,21:6,22:8,23:10,19:13,20:15},OM={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},NM={25:2,26:4,29:6,30:8,31:10,27:13,28:15},UM=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Ig=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;$e.log(`${this.time} [${e}] ${s}`)}}},vn=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Rg=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),rc=class{constructor(){this.styles=Rg}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=Rg}setStyles(e){let t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Lg=class{constructor(){this.uchar=" ",this.penState=new rc}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}},xg=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new rc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<qi;t++)this.chars.push(new Lg);this.logger=e}equals(e){let t=this.chars,s=e.chars;for(let r=0;r<qi;r++){let n=t[r],a=s[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<qi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<qi;t++){let s=e[t];if(s.uchar!==" ")return!1;let r=s.penState.styles;if(r!==Rg&&(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>=qi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qi-1)}moveCursor(e){let t=Math.min(this.pos+e,qi);if(e>1)for(let s=this.pos+1;s<t;s++)this.chars[s].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=H_(e);if(this.pos>=qi){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<qi;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 s=0;s<qi;s++){let r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},tl=class{constructor(e){this.rows=[],this.currRow=Yi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Yi;t++)this.rows.push(new xg(e));this.logger=e}reset(){for(let e=0;e<Yi;e++)this.rows[e].clear();this.currRow=Yi-1}equals(e){let t=!0;for(let s=0;s<Yi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Yi;t++){let s=this.rows[t].chars,r=e.rows[t].chars;for(let n=0;n<qi;n++){let a=s[n],o=r[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Yi;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 = "+rt(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<Yi;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 d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.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 = "+rt(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=[],s="",r=-1;for(let n=0;n<Yi;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?s="["+t.join(" | ")+"]":s=t.join(`
|
|
57
|
-
`)),s}getTextAndFormat(){return this.rows}},kg=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new tl(s),this.nonDisplayedMemory=new tl(s),this.lastOutputScreen=new tl(s),this.currRollUpRow=this.displayedMemory.rows[Yi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Yi-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+rt(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))}},nc=class{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=BM(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Ig,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,(s=this.channels[e])==null||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new kg(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){let r=t[s]&127,n=t[s+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+vn([t[s],t[s+1]])+"] -> ("+vn([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(FM(r,n,l)){_u(null,null,l),this.logger.log(3,()=>"Repeated command ("+vn([r,n])+") is dropped");continue}_u(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 _u(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let u=this.currentChannel;u&&u>0?this.getChannel(u).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+vn([r,n])+" orig: "+vn([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(s||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 s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[s];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+vn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,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?s=a===1?MM[e]:OM[e]:s=a===1?PM[e]:NM[e],this.getChannel(a).setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0}interpretPAC(e,t){let s,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,r.underline=(s&1)===1,s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((s-16)/2)*4,r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=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 '"+H_(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+vn(r).join(",")),r}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(s||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=UM[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()}_u(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function _u(i,e,t){t.a=i,t.b=e}function FM(i,e,t){return t.a===i&&t.b===e}function BM(){return{a:null,b:null}}var ma=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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dg=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=Xb(),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(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_APPENDED,this.onBufferAppended,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_APPENDED,this.onBufferAppended,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 ma(this,"textTrack1"),t=new ma(this,"textTrack2"),s=new ma(this,"textTrack3"),r=new ma(this,"textTrack4");this.cea608Parser1=new nc(1,e,t),this.cea608Parser2=new nc(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let l=n.length;l--;){let d=n[l],u=$M(d[0],d[1],t,s);if(u>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],s),a=!0,u/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let d=this.Cues.newCue(null,t,s,r);d.length&&l.push.apply(l,d)}else{let d=this.captionsTracks[e].track;this.Cues.newCue(d,t,s,r)}}else{var o;let l=this.Cues.newCue(null,t,s,r),d=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:d})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){let{unparsedVttFrags:r}=this;t===te.MAIN&&(this.initPTS=s),r.length&&(this.unparsedVttFrags=[],r.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,n):this.hls.trigger(y.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:s,cueCache:r,media:n}=this,{label:a,languageCode:o}=t[e];n&&(r[e]=[],s[e]=r0(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,r={_id:e,label:s,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]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,!s){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=Xb(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!u_(this.tracks,s)){let r=s.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}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===te.MAIN){var s,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:s,payload:r}=t;if(s.level<this.tracks.length&&s.type===te.SUBTITLE){var n;if(r.byteLength||(n=s.initSegment)!=null&&(n=n.data)!=null&&n.byteLength){let a=s.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){let l=this.tracks[s.level],d=this.vttCCs;d[s.cc]||(d[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(l==null?void 0:l.textCodec)===lg?this._parseIMSC1(t):this._parseVTTs(t)}}else{let a="part"in t?t.part:null;this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:s}=e,r="part"in e?e.part:null,n=this.hls;Hb(s,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:a})})}_parseVTTs(e){var t;let{frag:s,payload:r}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(e);return}let d=this.hls,u=(t=s.initSegment)==null?void 0:t.data,c=u?Ci(u,new Uint8Array(r)).buffer:r;hM(c,this.initPTS[s.cc],this.vttCCs,s.cc,(n&&!u?n:s).start,h=>{this._appendCues(h,s.level),d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:n})},h=>{let f=h.message.startsWith("Missing initPTS");if(d.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${h}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:n,error:h})})}_fallbackToIMSC1(e){let{frag:t,payload:s}=e,r=this.tracks[t.level];r.textCodec||Hb(s,this.initPTS[t.cc],()=>{r.textCodec=lg,this._parseIMSC1(e)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){let s=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=>dg(n,a))}else{let n=this.tracks[t];if(!n)return;let a=n.default?"default":"subtitles"+t;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===te.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:r}=t;if(!(s.type===te.MAIN&&this.closedCaptionsForLevel(s)==="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 s;let{type:r,timeRanges:n}=t;if(r==="video"&&(s=n[r])!=null&&s.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var d;let u=(d=a[l])==null?void 0:d.track;if(u){let c=o[l];for(let h=0;h<c.length;h++)dg(u,c[h])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:s,endOffset:r,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a==="video"){let{captionsTracks:l,cueCache:d}=this;Object.keys(l).forEach(u=>ug(l[u].track,s,r)),Object.keys(d).forEach(u=>{let c=d[u];for(let h=c.length;h--;){let f=c[h];f.startTime>=s&&f.endTime<=r&&c.splice(h,1)}})}this.config.renderTextTracksNatively&&s===0&&n!==void 0&&this.tracks.forEach(l=>{var d;let u=(d=l.trackNode)==null?void 0:d.track;u&&ug(u,s,n)})}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,r=2;for(let n=0;n<s;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function $M(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function Xb(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var HM=/\s/,GM={newCue(i,e,t,s){let r=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)HM.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=P_(d.trim()),m=s0(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(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 i&&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=>dg(i,h))),r}},ac=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 il}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){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=s,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(sl(e,t,!0))this.retry(e);else{var s;$e.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=Ug(e,s.retry),s.retry++,$e.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function KM(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var VM=/(\d+)-(\d+)\/(\d+)/,oc=class extends ac{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||jM}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:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;let r=WM(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&&Q(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(pl(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var c;this.response=u;let h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(h-s.loading.start)),!u.ok){let{status:m,statusText:p}=u;throw new Cg(p||"fetch, bad network response",m,u)}s.loading.first=h,s.total=YM(u.headers)||s.total;let f=(c=this.callbacks)==null?void 0:c.onProgress;return f&&Q(e.highWaterMark)?this.loadProgressively(u,s,t,e.highWaterMark,f):n?u.arrayBuffer():t.responseType==="json"?u.json():u.text()}).then(u=>{var c,h;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let m=u[a];m&&(s.loaded=s.total=m);let p={url:f.url,data:u,code:f.status},g=(c=this.callbacks)==null?void 0:c.onProgress;g&&!Q(e.highWaterMark)&&g(s,t,u,f),(h=this.callbacks)==null||h.onSuccess(p,s,t,f)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;let c=u&&u.code||0,h=u?u.message:null,f=e.loadPolicy.errorRetry,m=s.retry,p={url:t.url,data:void 0,code:c};if(sl(f,m,!1,p))this.retry(f);else{var g;$e.error(`${c} while loading ${t.url}`),(g=this.callbacks)==null||g.onError({code:c,text:h},t,u?u.details:null,s)}})}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,s,r=0,n){let a=new Wu,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function WM(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Qe({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function qM(i){let e=VM.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function YM(i){let e=i.get("Content-Range");if(e){let s=qM(e);if(Q(s))return s}let t=i.get("Content-Length");if(t)return parseInt(t)}function jM(i,e){return new self.Request(i.url,e)}var Cg=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},zM=(i,e,t)=>Math.max(e,Math.min(i,t)),QM=/^age:\s*[\d.]+\s*$/im,lc=class extends ac{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 s=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!==s||this.stats.aborted))return n.call(this,s,t.url,t)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.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),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=u!=null?u:t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);let v={url:t.responseURL,data:m,code:d};e.rangeEnd&&p!==e.rangeEnd-e.rangeStart&&$e.warn(`Payload length ${p} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(sl(c,h,!1,f))this.retry(c);else{var l;$e.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&QM.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}},XM={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ZM=ae(ae({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:lc,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:$T,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:XM},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:tc,abrController:Tp,bufferController:jp,capLevelController:El,errorController:_p,fpsController:sg,id3TrackController:mg,gapController:hg,latencyController:_g},JM()),{},{subtitleStreamController:Ag,subtitleTrackController:cg,timelineController:Dg,audioStreamController:Vp,audioTrackController:Wp,emeController:ec,cmcdController:eg,contentSteeringController:tg,iframeController:gg,interstitialsController:Tg});function JM(){return{cueHandler:GM,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 eP(i,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=zM(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let s=wg(i),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,d=[];n.forEach(u=>{let c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);let f=s[o].default;switch(e[o]={default:f},u){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}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${rt(e[o])}`)}),ae(ae({},s),e)}function wg(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(wg):Object.keys(i).reduce((e,t)=>(e[t]=wg(i[t]),e),{}):i}function tP(i,e){let t=i.loader;t!==oc&&t!==lc?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):KM()&&(i.loader=oc,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Mg=class extends gl{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(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,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,d=!1,u=!1;t.levels.forEach(c=>{let h=c.attrs,f=Zb(c,s),{audioCodec:m,videoCodec:p,imageCodec:g,width:v,height:b}=c;if(!f){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}o||(o=!!(v&&b)),l||(l=!!p),d||(d=!!m),u||(u=!!g);let{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":_,"PATHWAY-ID":I,RESOLUTION:S,"VIDEO-RANGE":x}=h,R=`${`${I||"."}-`}${c.bitrate}-${S}-${T}-${E}-${x}-${_}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let D=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");let w=this.createLevel(c);n[R]=w,r.push(w)}else c.iframes||(n[R].addGroupId("audio",h.AUDIO),n[R].addGroupId("text",h.SUBTITLES));else{let D=this.createLevel(c);n[R]=D,a[R]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,d,u)}createLevel(e){let t=new Tn(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!K_(s.videoCodec,this.hls.config.preferManagedMediaSource)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=RT(r,[])}return t}filterAndSortMediaOptions(e,t,s,r,n,a){var o;let l=[],d=[],u=e,c=((o=t.stats)==null?void 0:o.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((s||r)&&n&&(u=u.filter(({videoCodec:_,videoRange:I,width:S,height:x})=>(!!_||!!(S&&x))&&AD(I))),r&&a&&(u=u.filter(_=>!_.imageCodec)),u.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",I=_;t.levels.length&&(I=`one or more CODECS in variant not supported: ${rt(t.levels.map(x=>x.attrs.CODECS).filter((x,k,R)=>R.indexOf(x)===k))}`,this.warn(I),_+=` (${I})`);let S=new Error(_);this.hls.trigger(y.ERROR,{type:re.MEDIA_ERROR,details:P.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:I})}}),c.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(_=>!_.audioCodec||G_(_.audioCodec,h)),Jb(l)),t.subtitles&&(d=t.subtitles,Jb(d));let f=u.slice(0);u.sort((_,I)=>{if(_.attrs["HDCP-LEVEL"]!==I.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(I.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&_.height!==I.height)return _.height-I.height;if(_.frameRate!==I.frameRate)return _.frameRate-I.frameRate;if(_.videoRange!==I.videoRange)return Mu.indexOf(_.videoRange)-Mu.indexOf(I.videoRange);if(_.videoCodec!==I.videoCodec){let S=By(_.videoCodec),x=By(I.videoCodec);if(S!==x)return x-S}if(_.uri===I.uri&&_.codecSet!==I.codecSet){let S=Cu(_.codecSet),x=Cu(I.codecSet);if(S!==x)return x-S}return _.averageBitrate!==I.averageBitrate?_.averageBitrate-I.averageBitrate:0});let m=f[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==f.length)){for(let _=0;_<f.length;_++)if(f[_].pathwayId===u[0].pathwayId){m=f[_];break}}this._levels=u;for(let _=0;_<u.length;_++)if(u[_]===m){var p;this._firstLevel=_;let I=m.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${I}`),((p=this.hls.userConfig)==null?void 0:p.abrEwmaDefaultEstimate)===void 0){let x=Math.min(I,this.hls.config.abrEwmaDefaultEstimateMax);x>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}let g=t.iframeVariants.filter(_=>Zb(_,h));this._iframeVariants=g;let v=n&&!r,b=this.hls.config,E=!!(b.audioStreamController&&b.audioTrackController),T={levels:u,audioTracks:l,subtitleTracks:d,iframeVariants:g,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:E&&!v&&l.some(_=>!!_.url)};c.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,T)}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 u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(y.ERROR,{type:re.OTHER_ERROR,details:P.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let s=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,s===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 ${s}${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 d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,r==null?void 0:r.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){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(),s=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=s}}onError(e,t){t.fatal||!t.context||t.context.type===Re.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===te.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[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 s;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(s=t.deliveryDirectives)!=null&&s.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 s=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||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,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 s=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));YT(s),this._levels=s,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=s.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:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}};function G_(i,e){return ol(i,"audio",e)}function K_(i,e){return ol(i,"video",e)}function Zb(i,e){let{audioCodec:t,videoCodec:s}=i;t&&(i.audioCodec=t=wu(t,e)||void 0),s&&(s=i.videoCodec=mD(s));let{unknownCodecs:r}=i;return!((r==null?void 0:r.length)||0||t&&!G_(t,e)||s&&!K_(s,e))}function Jb(i){let e={};i.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var Pg=class extends si{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyLoaderInfo){let r=this.keyLoaderInfo[s].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,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);let r=e.decryptdata;if(!r){let a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Er(e,P.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(Er(e,P.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 s=jk(e.initSegment.data);if(s.length){let r=s[0],n=e.decryptdata.uri;if(r.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ct(r)} keyUri: ${n}`),_n.setKeyIdForUri(n,r);else{let a=_n.addKeyIdForUri(n);this.log(`Patching empty keyId with ${Ct(a)} keyUri: ${n}`),r=a}e.decryptdata.keyId=r}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Er(e,P.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(Er(e,P.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));let r=this.keyLoaderInfo[s];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(d=>(t.key=r.decryptdata.key,ae(ae({},d),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ct(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[s]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((d,u)=>{let c={type:Re.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:s},h=n.keyLoadPolicy.default,f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(p,g,v,b)=>{let{frag:E,keyInfo:T,url:_}=v;if(!E.decryptdata||T!==this.keyLoaderInfo[_])return u(Er(E,P.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),b));T.decryptdata.key=E.decryptdata.key=new Uint8Array(p.data),E.keyLoader=T.loader=T.keyLoadPromise=null,d({frag:E,keyInfo:T})},onError:(p,g,v,b)=>{this.resetLoader(g),u(Er(e,P.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),v,ae({url:s,data:void 0},p)))},onTimeout:(p,g,v)=>{this.resetLoader(g),u(Er(e,P.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(p,g,v)=>{this.resetLoader(g),u(Er(e,P.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};o.load(c,f,m)})}resetLoader(e){let{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[r],n&&n.destroy()}};function Er(i,e=P.KEY_LOAD_ERROR,t,s,r){return new Di({type:re.NETWORK_ERROR,details:e,fatal:!1,frag:i,response:r,error:t,networkDetails:s||null})}function eT(i){let{type:e}=i;switch(e){case Re.AUDIO_TRACK:return te.AUDIO;case Re.SUBTITLE_TRACK:return te.SUBTITLE;default:return te.MAIN}}function cp(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Og=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,s=t.pLoader,r=t.loader,n=s||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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Re.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:Re.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Re.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Re.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Re.LEVEL];if(s){let r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[Re.LEVEL])}}load(e){var t;let s=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,u=r.context;if((u==null?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===Re.MANIFEST?n=s.manifestLoadPolicy.default:n=Qe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Re.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Re.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Re.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let u=d.partTarget,c=d.targetduration;if(u&&c){let h=Math.max(u*3,c*.8)*1e3;n=Qe({},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:(d,u,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=d.data;u.parsing.start=performance.now(),_r.isMediaPlaylist(m)||c.type!==Re.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){let n=this.hls,a=e.data,o=cp(e,s),l=_r.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:u,iframeVariants:c,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p}=l;this.variableList=p,u.forEach(E=>{let{unknownCodecs:T}=E;if(T){let{preferManagedMediaSource:_}=this.hls.config,{audioCodec:I,videoCodec:S}=E;for(let x=T.length;x--;){let k=T[x];ol(k,"audio",_)?(E.audioCodec=I=I?`${I},${k}`:k,va.audio[I.substring(0,4)]=2,T.splice(x,1)):ol(k,"video",_)&&(E.videoCodec=S=S?`${S},${k}`:k,va.video[S.substring(0,4)]=2,T.splice(x,1))}}});let{AUDIO:g=[],SUBTITLES:v,"CLOSED-CAPTIONS":b}=_r.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(T=>!T.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ht({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:v,iframeVariants:c,captions:b,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p})}handleTrackOrLevelPlaylist(e,t,s,r,n){let a=this.hls,{id:o,level:l,type:d}=s,u=cp(e,s),c=Q(l)?l:Q(o)?o:0,h=eT(s),f=_r.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Re.MANIFEST){let m={attrs:new ht({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+VT(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[m],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:P.MANIFEST_PARSING_ERROR,fatal:t.type===Re.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Re.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Re.AUDIO_TRACK||e.type===Re.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=P.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Re.MANIFEST:l=s?P.MANIFEST_LOAD_TIMEOUT:P.MANIFEST_LOAD_ERROR,d=!0;break;case Re.LEVEL:l=s?P.LEVEL_LOAD_TIMEOUT:P.LEVEL_LOAD_ERROR,d=!1;break;case Re.AUDIO_TRACK:l=s?P.AUDIO_TRACK_LOAD_TIMEOUT:P.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Re.SUBTITLE_TRACK:l=s?P.SUBTITLE_TRACK_LOAD_TIMEOUT:P.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:re.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=e.url;t&&"url"in t&&(h=t.url),c.response=ae({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=cp(t,r),p=eT(r),g=typeof r.level=="number"&&p===te.MAIN?d:void 0;u&&"iframes"in u&&u.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 v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let b=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:re.NETWORK_ERROR,details:P.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Re.MANIFEST:case Re.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){let b=o.levels.indexOf(u);b>-1&&(g=b)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Re.MANIFEST,context:r});break;case Re.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f,context:r});break;case Re.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f,context:r});break}}},bl=class i{static get version(){return fl}static isMSESupported(){return B_()}static isSupported(){return AM()}static getMediaSource(){return Ir()}static get Events(){return y}static get MetadataSchema(){return ii}static get ErrorTypes(){return re}static get ErrorDetails(){return P}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:ZM}static set DefaultConfig(e){i.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 qg,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=Tk(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),s=this.config=eP(i.DefaultConfig,e,t);this.userConfig=e,s.progressive&&tP(s,t);let{streamController:r,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:d,id3TrackController:u,iframeController:c,gapController:h}=s,f=new l(this),m=this.abrController=new n(this),p=new Ap(this),g=s.interstitialsController,v=g?this.interstitialsController=new g(this,i):null,b=a?this.bufferController=new a(this,p):null,E=o?this.capLevelController=new o(this):null,T=d?new d(this):null,_=s.cmcdController,I=_?this.cmcdController=new _(this):null,S=new Og(this),x=s.contentSteeringController,k=x?new x(this):null,R=this.levelController=new Mg(this,k),D=u?new u(this):void 0,w=new Pg(this.config,this.logger),N=this.streamController=new r(this,p,w),$=this.gapController=h?new h(this,p):void 0;E&&E.setStreamController(N);let H=[S,R,N];v&&H.splice(1,0,v),k&&H.splice(1,0,k),this.networkControllers=H;let O=[m];b&&O.push(b),$&&O.push($),E&&O.push(E),T&&(T.setStreamController(N),O.push(T)),D&&O.push(D),O.push(p),this.audioTrackController=this.createController(s.audioTrackController,H);let F=s.audioStreamController;F&&H.push(this.audioStreamController=new F(this,p,w)),this.subtitleTrackController=this.createController(s.subtitleTrackController,H);let B=s.subtitleStreamController;B&&H.push(this.subtititleStreamController=new B(this,p,w)),this.createController(s.timelineController,O),w.emeController=this.emeController=this.createController(s.emeController,O),I&&O.push(I),this.latencyController=this.createController(s.latencyController,O),this.coreComponents=O,this.iframeController=c?new c(this,i):void 0,H.push(f);let W=f.onErrorOut;typeof W=="function"&&this.on(y.ERROR,W,f),this.on(y.MANIFEST_LOADED,S.onManifestLoaded,S)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let r=e===y.ERROR;this.trigger(y.ERROR,{type:re.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),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,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(y.ERROR,{type:re.OTHER_ERROR,details:P.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,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(y.MEDIA_DETACHING,e),this._media=null,this.trigger(y.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(y.MEDIA_DETACHING,s),this.trigger(y.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();let s=this.media,r=this._url,n=this._url=Ng.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),s&&r&&(r!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),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 s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==U.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={[te.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[te.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[te.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,s=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=oT()),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,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}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){_D(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 s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)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 s=DT(t);return LT(e,s,navigator.mediaCapabilities)}};bl.defaultConfig=void 0;var ke=bl,qe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},oe={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},Il=i=>i===qe.VIDEO?"playback":i,Lr=class _l extends Error{constructor(e,t=_l.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s!=null?s:t>=_l.MEDIA_ERR_NETWORK&&t<=_l.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=_l.defaultMessages[this.code])!=null?n:"")}};Lr.MEDIA_ERR_ABORTED=1,Lr.MEDIA_ERR_NETWORK=2,Lr.MEDIA_ERR_DECODE=3,Lr.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Lr.MEDIA_ERR_ENCRYPTED=5,Lr.MEDIA_ERR_CUSTOM=100,Lr.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 X=Lr,iP=i=>i==null,b0=(i,e)=>iP(e)?!1:i in e,d0={ANY:"any",MUTED:"muted"},He={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},wi={MSE:"mse",NATIVE:"native"},Al={HEADER:"header",QUERY:"query",NONE:"none"},_a=Object.values(Al),zs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},u0={HLS:zs.M3U8},uF=Object.keys(u0),cF=[...Object.values(zs),"hls","HLS"];var sP="en",c0={code:sP},rP=i=>{let e=i;for(;e;){if(e.hasAttribute("lang"))return e.getAttribute("lang")||void 0;let t=e.getRootNode();e=t instanceof ShadowRoot?t.host:void 0}},nP=i=>{var e,t,s;let r=(s=(e=globalThis.navigator)==null?void 0:e.languages)!=null?s:[(t=globalThis.navigator)==null?void 0:t.language];return[rP(i),...r].filter(n=>!!n)},Tt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function aP(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var Ec=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},yc=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return b0(t,u0)?u0[t]:e}return oP(i)},J_=i=>i==="VOD"?He.ON_DEMAND:He.LIVE,eA=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,oP=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=bc(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let s=t.lastIndexOf(".");if(s<0)return uP(i)?zs.M3U8:"";let r=t.slice(s+1).toUpperCase();return b0(r,zs)?zs[r]:""},h0=i=>{try{return new URL(i),!1}catch{return!0}},lP=i=>i.split(`
|
|
58
|
-
`).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),bc=(i,e)=>{var t;if(!h0(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&h0(e.toString())&&(r=new URL(e,s)),new URL(i,r)},dP="mux.com",uP=({src:i,customDomain:e=dP})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},xr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},cP=({exp:i},e=Date.now())=>!i||i*1e3<e,hP=({sub:i},e)=>i!==e,fP=({aud:i},e)=>!i,mP=({aud:i},e)=>i!==e,tA="en";function ne(i,e=!0){var t,s;let r=e&&(s=(t=c0)==null?void 0:t[i])!=null?s:i,n=e?c0.code:tA;return new pP(r,n)}var pP=class{constructor(i,e=(t=>(t=c0)!=null?t:tA)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},gP=Object.values(d0),V_=i=>typeof i=="boolean"||typeof i=="string"&&gP.includes(i),vP=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=V_(s)?s:!!s,o=()=>{r||Tt(e,"playing",()=>{r=!0},{once:!0})};if(o(),Tt(e,"loadstart",()=>{r=!1,o(),n0(e,a)},{once:!0}),Tt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==He.UNKNOWN?n=i.streamType===He.LIVE:n=!Number.isFinite(e.duration)),n0(e,a)},{once:!0}),t&&t.once(ke.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==He.UNKNOWN?n=i.streamType===He.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Tt(e,"play",()=>{e.preload==="metadata"?t.once(ke.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=V_(l)?l:!!l,n0(e,a))}},n0=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case d0.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case d0.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},EP=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return Tt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},yP=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=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,Tt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(ke.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(ke.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},bP=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(ke.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function TP(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(ke.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(ke.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(ke.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(ke.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var W_=i=>i.split("-")[0],fc=({language:i})=>typeof i=="string"?i.toLowerCase():void 0;function _P(i,e){var t,s;let r=e.toLowerCase(),n=W_(r);return(s=(t=i.find(a=>fc(a)===r))!=null?t:i.find(a=>fc(a)===n))!=null?s:i.find(a=>{let o=fc(a);return o!==void 0&&W_(o)===n})}function AP(i,e){var t;let s=(Array.isArray(i)?i:[]).filter(r=>typeof(r==null?void 0:r.title)=="string"&&r.title!=="");if(!s.length)return"";for(let r of e){let n=_P(s,r);if(n)return n.title}return((t=s.find(r=>fc(r)==="und"))!=null?t:s[0]).title}function SP(i,e=[]){return Array.isArray(i)?i.filter(t=>typeof(t==null?void 0:t["start-time"])=="number").map((t,s,r)=>{var n;let a=t["start-time"],o=(n=r[s+1])==null?void 0:n["start-time"],l=typeof t.duration=="number"?a+t.duration:typeof o=="number"?o:void 0;return{startTime:a,...l!=null?{endTime:l}:{},value:AP(t.titles,e)}}).filter(t=>t.value!==""):[]}var iA=Number.MAX_SAFE_INTEGER,a0=i=>"time"in i?i.time:i.startTime;function IP(i,e){e.on(ke.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(d==null?void 0:d.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;Tc(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.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:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(ke.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(ke.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let a="track";r.kind&&(a+=`[kind="${r.kind}"]`),r.label&&(a+=`[label="${r.label}"]`);let o=i.querySelector(a),l=o==null?void 0:o.getAttribute("src");o&&l&&(o.removeAttribute("src"),setTimeout(()=>{o.setAttribute("src",l)},0))}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(ke.Events.MANIFEST_LOADED,s),e.once(ke.Events.MEDIA_ATTACHED,s)}function Tc(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function sA(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function Rl(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}var o0=new WeakMap;async function T0(i,e,t){let s=Rl(i,e,t);if(s){let a=o0.get(s);return a&&await a,s}let r=Tc(i,t,e);r.mode="hidden";let n=new Promise(a=>setTimeout(a,0));return o0.set(r,n),await n,o0.delete(r),r}async function RP(i,e,t,s){let r=await T0(i,t,s);return _0(i,r,e,s),r}function _0(i,e,t,s){e.mode!=="hidden"&&(e.mode="hidden"),[...t].sort((r,n)=>a0(n)-a0(r)).forEach(r=>{var n,a;let o=r.value,l=a0(r);if("endTime"in r&&r.endTime!=null&&Number.isFinite(r.endTime))e==null||e.addCue(new VTTCue(l,r.endTime,s==="chapters"?o:JSON.stringify(o!=null?o:null)));else{let d=Array.prototype.findIndex.call(e==null?void 0:e.cues,f=>f.startTime>=l),u=(n=e==null?void 0:e.cues)==null?void 0:n[d],c=u?u.startTime:Number.isFinite(i.duration)&&i.duration>0?i.duration:iA,h=(a=e==null?void 0:e.cues)==null?void 0:a[d-1];h&&(h.endTime=l),e==null||e.addCue(new VTTCue(l,c,s==="chapters"?o:JSON.stringify(o!=null?o:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))}var A0="cuepoints",rA=Object.freeze({label:A0});async function S0(i,e,t=rA){return RP(i,e,t.label,"metadata")}var f0=i=>({time:i.startTime,value:JSON.parse(i.text)});function nA(i,e={label:A0}){let t=Rl(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>f0(s)):[]}function I0(i,e={label:A0}){var t,s;let r=Rl(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return f0(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return f0(a||r.activeCues[0])}async function LP(i,e=rA){return new Promise(t=>{Tt(i,"loadstart",async()=>{let s=await S0(i,[],e);Tt(i,"cuechange",()=>{let r=I0(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var R0="chapters",L0=Object.freeze({label:R0}),m0=(i,e)=>{let{duration:t}=e,s=Number.isFinite(t)&&t>0?Math.min(i.endTime,t):i.endTime>=iA?1/0:i.endTime;return{startTime:i.startTime,endTime:s,value:i.text}},p0=new WeakSet;function aA(i){var e;Array.from((e=i.cues)!=null?e:[]).filter(t=>p0.has(t)).forEach(t=>i.removeCue(t))}async function x0(i,e,t=L0){let s=await T0(i,t.label,"chapters");return e.length&&aA(s),_0(i,s,e,"chapters"),s}async function xP(i,e,t,s=L0){var r,n;let a=await T0(i,s.label,"chapters");return t!=null&&t.aborted||Array.from((r=a.cues)!=null?r:[]).some(o=>!p0.has(o))||(aA(a),_0(i,a,e,"chapters"),Array.from((n=a.cues)!=null?n:[]).forEach(o=>p0.add(o))),a}function oA(i,e={label:R0}){var t;let s=Rl(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>m0(r,i)):[]}function k0(i,e={label:R0}){var t,s;let r=Rl(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return m0(r.activeCues[0],i);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return m0(a||r.activeCues[0],i)}async function kP(i,e=L0){return new Promise(t=>{Tt(i,"loadstart",async()=>{let s=await x0(i,[],e);Tt(i,"cuechange",()=>{let r=k0(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function lA(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function dA(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var Ta={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},DP=i=>{if(i===qe.VIDEO)return Ta.VIDEO;if(i===qe.DRM)return Ta.DRM},CP=(i,e)=>{var t,s;let r=Il(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:b0(n,e)?e[n]:void 0},gc=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=ne("Your device appears to be offline",r),b,E=X.MEDIA_ERR_NETWORK,T=new X(v,E,!1,b);return T.errorCategory=e,T.muxCode=oe.NETWORK_OFFLINE,T.data=i,T}let l="status"in i?i.status:i.code,d=Date.now(),u=X.MEDIA_ERR_NETWORK;if(l===200)return;let c=Il(e),h=CP(e,t),f=DP(e),[m]=Ec((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=xr(h);if(h&&!p){let v=ne("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),b=ne("Compact JWT string: {token}",r).format({token:h}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_MALFORMED,E.data=i,E}if(l>=500){let v=new X("",u,s!=null?s:!0);return v.errorCategory=e,v.muxCode=oe.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(cP(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},b=ne("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),E=ne("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(d)}),T=new X(b,u,!0,E);return T.errorCategory=e,T.muxCode=oe.NETWORK_TOKEN_EXPIRED,T.data=i,T}if(hP(p,m)){let v=ne("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),b=ne("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 X(v,u,!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_SUB_MISMATCH,E.data=i,E}if(fP(p,f)){let v=ne("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=ne("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_AUD_MISSING,E.data=i,E}if(mP(p,f)){let v=ne("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=ne("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 X(v,u,!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_AUD_MISMATCH,E.data=i,E}}else{let v=ne("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}),b=ne("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s!=null?s:!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_MISSING,E.data=i,E}if(l===412){let v=ne("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),b=ne("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s!=null?s:!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_NOT_READY,E.streamType=t.streamType===He.LIVE?"live":t.streamType===He.ON_DEMAND?"on-demand":"unknown",E.data=i,E}if(l===404){let v=ne("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),b=ne("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s!=null?s:!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_NOT_FOUND,E.data=i,E}if(l===400){let v=ne("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),b=ne("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s!=null?s:!0,b);return E.errorCategory=e,E.muxCode=oe.NETWORK_INVALID_URL,E.data=i,E}let g=new X("",u,s!=null?s:!0);return g.errorCategory=e,g.muxCode=oe.NETWORK_UNKNOWN_ERROR,g.data=i,g},g0=ke.DefaultConfig.capLevelController;g0||console.error("MinCapLevelController - hls.js DefaultConfig.capLevelController is unavailable");var wP={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function MP(i){let e=i.toLowerCase().trim();return wP[e]}var v0=class Sl extends g0{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?Sl.maxAutoResolution.set(e,t):Sl.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=Sl.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,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=MP(s);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(d=>d===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),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=Sl.minMaxResolution;return r>=n?t:g0.getMaxLevelByMediaSize(s,n*(16/9),n)}};v0.minMaxResolution=720,v0.maxAutoResolution=new WeakMap;var PP=v0,E0=PP,OP="com.apple.fps.1_0",NP="application/vnd.apple.mpegurl",UP=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=ne("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new X(h,X.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=qe.DRM,f.muxCode=oe.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=FP(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(OP);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 X(h,X.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=qe.DRM,f.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(NP,h),m=async v=>{try{let b=v.message,E=await t(b);f.update(E)}catch(b){console.error("Error on FairPlay session message",b),s(i,b)}},p=v=>{let b=v.target.error;if(!b)return;console.error(`Internal Webkit Key Session Error - sysCode: ${b.systemCode} code: ${b.code}`);let E=ne("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),T=new X(E,X.MEDIA_ERR_ENCRYPTED,!0);T.errorCategory=qe.DRM,T.muxCode=oe.ENCRYPTED_CDM_ERROR,s(i,T)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},FP=(i,e)=>{let t=$P(BP(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},BP=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function $P(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var HP=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,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}i.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 d(h,f)}catch(h){s(i,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=ne("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new X(m,X.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=qe.DRM,p.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=ne("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new X(p,X.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=qe.DRM,g.muxCode=oe.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let b=v.message,E=await t(b);try{await f.update(E)}catch{let T=ne("Failed to update DRM license. This may be an issue with the player or your protected content."),_=new X(T,X.MEDIA_ERR_ENCRYPTED,!0);_.errorCategory=qe.DRM,_.muxCode=oe.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,_)}},p=()=>{let v=b=>{let E;if(b==="internal-error"){let T=ne("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");E=new X(T,X.MEDIA_ERR_ENCRYPTED,!0),E.errorCategory=qe.DRM,E.muxCode=oe.ENCRYPTED_CDM_ERROR}else if(b==="output-restricted"||b==="output-downscaled"){let T=ne("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");E=new X(T,X.MEDIA_ERR_ENCRYPTED,!1),E.errorCategory=qe.DRM,E.muxCode=oe.ENCRYPTED_OUTPUT_RESTRICTED}E&&s(i,E)};f.keyStatuses.forEach(b=>v(b))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let b=ne("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),E=new X(b,X.MEDIA_ERR_ENCRYPTED,!0);return E.errorCategory=qe.DRM,E.muxCode=oe.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(E)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},GP=({hls:i,mediaEl:e,src:t,muxMediaState:s,saveAndDispatchError:r,maxRetries:n})=>{var a;let o,l=0,d=!1,u=!1,c=!1,h=()=>{o!=null&&(clearTimeout(o),o=void 0)},f=S=>(S==null?void 0:S.muxCode)===oe.NETWORK_RECONNECTING,m=()=>!e.paused&&e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA,p=()=>{let S=s.get(e);if(f(S==null?void 0:S.error))return;let x=new X(ne("Attempting to reconnect..."),X.MEDIA_ERR_NETWORK,!1);x.errorCategory=qe.VIDEO,x.muxCode=oe.NETWORK_RECONNECTING,S&&(S.error=x),e.dispatchEvent(new CustomEvent("error",{detail:x}))},g=()=>{if(!c&&t){i.loadSource(t);return}i.startLoad(e.currentTime)},v=()=>{d=!1,u=!0,h();let S=new X(ne("Network error, try reloading."),X.MEDIA_ERR_NETWORK,!0);S.errorCategory=qe.VIDEO,S.reload=!0,r(e,S)},b=()=>{if(o!=null||d)return;if(l>=n){v();return}d=!0;let S=Math.min(1e3*2**l,3e4);o=setTimeout(()=>{o=void 0,l+=1,g()},S)},E=()=>{let S=s.get(e);!(S!=null&&S.networkError)||u||m()&&(p(),b())},T=()=>{let S=s.get(e);S&&(S.networkError=!0),d=!1,E()},_=()=>{let S=s.get(e);S!=null&&S.networkError&&(l=0,u=!1,h(),d=!0,g())};(a=globalThis.addEventListener)==null||a.call(globalThis,"online",_);let I=()=>{let S=s.get(e);S&&(!S.networkError&&!f(S.error)||(S.networkError=!1,d=!1,l=0,u=!1,h(),S.error&&(S.error=null,e.dispatchEvent(new Event("emptied")))))};return i.on(ke.Events.FRAG_BUFFERED,I),Tt(e,"playing",()=>{let S=s.get(e);S!=null&&S.networkError&&(d=!1,l=0,u=!1,h(),S.error&&(S.error=null))}),Tt(e,"waiting",E),e.addEventListener("teardown",()=>{var S;(S=globalThis.removeEventListener)==null||S.call(globalThis,"online",_),h()},{once:!0}),{handleHlsError:(S,x)=>{var k,R;if(S.type!==ke.ErrorTypes.NETWORK_ERROR)return!1;let D=(R=(k=S.response)==null?void 0:k.code)!=null?R:0;return(x.muxCode===oe.NETWORK_OFFLINE||D===0||D>=500)&&S.fatal?(T(),!0):!1},onManifestLoaded:()=>{c=!0,d=!1,h()}}},mc={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},KP=i=>{if(i.includes("fps"))return mc.FAIRPLAY;if(i.includes("playready"))return mc.PLAYREADY;if(i.includes("widevine"))return mc.WIDEVINE},VP=(i,e,t)=>{let s=lP(i);if(!s)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(h0(s)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let r;try{r=bc(s,e)}catch(n){return Promise.reject(n)}return fetch(r,{signal:t}).then(n=>n.status!==200?Promise.reject(n):n.text())},WP=i=>{let e=i.split(`
|
|
53
|
+
`),d=[],u=e?$C(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,m=!1,p,g=!0;o.oncue=function(v){let E=t[s],b=t.ccOffset,T=(h-u)/9e4;if(m){if(E!=null&&E.new&&(b=t.ccOffset=E.start),T){if(!e){p=new Error($b+"MPEGTS");return}b=T-t.presentationOffset}}else if(e)b=-e.baseTime/e.timescale;else{p=new Error($b+"without X-TIMESTAMP-MAP");return}let _=v.endTime-v.startTime,I=Ai((v.startTime+b-f)*9e4,r*9e4)/9e4;v.startTime=Math.max(I,0),v.endTime=Math.max(I+_,0);let S=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(S)),v.id?s&&(v.id=`hlsjscc${s}_${v.id}`):v.id=s0(v.startTime,v.endTime,S),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){p=v},o.onflush=function(){if(p){a(p);return}n(d)},l.forEach(v=>{if(g)if(v.startsWith("X-TIMESTAMP-MAP=")){g=!1,m=!0,v.slice(16).split(",").forEach(E=>{E.startsWith("LOCAL:")?c=E.slice(6):E.startsWith("MPEGTS:")&&(h=parseInt(E.slice(7)))});try{f=cM(c)/1e3}catch(E){p=E}return}else v===""&&(g=!1);o.parse(v+`
|
|
54
|
+
`)}),o.flush()}var lg="stpp.ttml.im1t",O_=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,N_=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,fM={left:"start",center:"center",right:"end",start:"start",end:"end"};function Hb(i,e,t,s){let r=Ee(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>Si(o)),a=BC(e.baseTime,1,e.timescale);try{n.forEach(o=>t(mM(o,a)))}catch(o){s(o)}}function mM(i,e){let r=new DOMParser().parseFromString(i,"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=Gb(rp(r,"styling","style")),d=Gb(rp(r,"layout","region")),u=rp(r,"body","[begin]");return[].map.call(u,c=>{let h=U_(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=ap(c.getAttribute("begin"),a),m=ap(c.getAttribute("dur"),a),p=ap(c.getAttribute("end"),a);if(f===null)throw Kb(c);if(p===null){if(m===null)throw Kb(c);p=f+m}let g=new i0(f-e,p-e,h);g.id=s0(g.startTime,g.endTime,g.text);let v=d[c.getAttribute("region")],E=l[c.getAttribute("style")],b=pM(v,E,l),{textAlign:T}=b;if(T){let _=fM[T];_&&(g.lineAlign=_),g.align=T}return Qe(g,b),g}).filter(c=>c!==null)}function rp(i,e,t){let s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gb(i){return i.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function U_(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
|
|
55
|
+
`:(n=s.childNodes)!=null&&n.length?U_(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function pM(i,e,t){let s="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=np(e,s,l)||np(i,s,l)||np(r,s,l);return d&&(o[l]=d),o},{})}function np(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Kb(i){return new Error(`Could not parse ttml timestamp ${i}`)}function ap(i,e){if(!i)return null;let t=w_(i);return t===null&&(O_.test(i)?t=gM(i,e):N_.test(i)&&(t=vM(i,e))),t}function gM(i,e){let t=O_.exec(i),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function vM(i,e){let t=N_.exec(i),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}function r0(i,e,t,s="",r="disabled"){let n=i.ownerDocument.createElement("track");return n.kind=e,n.label=t,s&&(n.srclang=s),n.src="data:,WEBVTT",n.track.mode=r,i.appendChild(n),n}function EM(i){return i.forced&&dD()?"forced":i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function dg(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){$e.debug(`[texttrack-utils]: ${s}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){$e.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function ug(i,e,t,s){let r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){let n=bM(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function yM(i,e){if(e<=i[0].startTime)return 0;let t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function bM(i,e,t){let s=[],r=yM(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){let o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}var cg=class extends gl{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,s=!1;if(this.currentTrack){var r;let o=(r=this.currentTrack.trackNode)==null?void 0:r.track.mode;o==="showing"?(t=this.trackId,s=!0):o==="hidden"&&(t=this.trackId)}if(!s)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(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)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=r0(this.media,EM(s),s.name,s.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 s=t.media;this.media=s;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} 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 ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=s;let a=[];if(this.tracks.forEach(u=>{(u.textCodec===lg?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(u.groupId)>-1?(u.id=a.length,a.push(u)):u.trackNode&&(u.trackNode.remove(),u.trackNode=void 0))}),a.length===this.tracksInGroup.length){let u=!1;for(let c=0;c<a.length;c++)if(a[c]!==this.tracksInGroup[c]){u=!0;break}if(!u)return}a.length&&this.selectDefaultTrack&&!a.some(u=>u.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 u=ps(o,a);if(u>-1)n=a[u];else{let c=ps(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||yn(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(vl(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(vl(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Re.SUBTITLE_TRACK&&t.context.id===this.trackId&&dl(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 s=this.currentTrack;if(s&&yn(e,s))return s;let r=ps(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),n}else{if(s)return null;{let n=ps(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 s=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 ${s} "${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:s,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 s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",r=t.trackNode.track;r.mode!==s&&(r.mode=s)}})}setSubtitleTrack(e,t=!1){let s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,n=s[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){r&&this.hls.trigger(y.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:d,type:u,url:c}=n;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:u,url:c});let h=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(h)}},Lu=2,TM=100,hg=class extends Fu{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),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(TM),this.mediaSource=t.mediaSource;let s=this.media=t.media;Ye(s,"playing",this.onMediaPlaying),Ye(s,"waiting",this.onMediaWaiting),Ye(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(We(s,"playing",this.onMediaPlaying),We(s,"waiting",this.onMediaWaiting),We(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}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 s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=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&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.skipRetry=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(!be.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let c=be.bufferInfo(a,e,0),h=this.fragmentTracker;h&&this.hls&&qb(c,e,h,this.hls);let f=c.nextStart||0;if(o&&h&&this.hls){let I=Vb(this.hls.inFlightFragments,e),S=c.len>Lu,x=!f||I||f-e>Lu&&!h.getPartialFragment(e);if(S||x)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&h){if(!(c.len>0)&&!f)return;let S=Math.max(f,c.start||0)-e,k=!!(m!=null&&m.live)?m.targetduration*2:Lu,R=Qo(e,h);if(S>0&&(S<=k||R)){a.paused||this._trySkipBufferHole(R);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,E=this.stalled;if(E===null)if(v>0&&g-v<p)E=this.stalled=v;else{this.stalled=g;return}let b=g-E;if(!o&&(b>=p||v&&this.moved)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.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;if(a.currentTime!==e){let I=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${I} > ${e}`);return}}let _=be.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(_,b,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){let n=be.bufferedInfo(be.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=be.timeRangesToArray(r),o=be.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=be.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=Qo(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=be.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=Qo(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<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 s=this.fragmentTracker,r=e.nextStart;if(s&&r){let n=s.getFragAtPos(t,te.MAIN),a=s.getFragAtPos(r,te.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${rt(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:s,hls:r}=this,n=r==null?void 0:r.config;if(!s||!t||!n)return 0;let a=s.currentTime,o=be.bufferInfo(s,a,0);qb(o,a,t,r);let l=a<o.start?o.start:o.nextStart;if(l){let u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let v=!1;if(a===0){let E=t.getAppendedFrag(0,te.MAIN);E&&l<E.end&&(v=!0)}if(!v&&e){var d;if(!((d=r.loadLevelObj)!=null&&d.details)||Vb(r.inFlightFragments,l))return 0;let b=!1,T=e.end;for(;T<l;){let _=Qo(T,t),I=_?_.duration:0;if(I>0)T+=I;else{b=!0;break}}if(b)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:m}=n,p=++this.skipRetry>f,g=Math.max(l,a)+m;if(p||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${g}`),this.moved=!0,s.currentTime=g),!(e!=null&&e.gap)||p){let v=new Error(p?`Playhead still not moving after seeking over buffer hole from ${a} to ${g} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${g}`),E={type:ne.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:p,error:v,reason:v.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?E.part=e:E.frag=e),r.trigger(y.ERROR,E)}return g}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!s||!n)return 0;let a=s.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),s.currentTime=o,t.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.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:ne.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Vb(i,e){let t=Wb(i.main);if(t&&t.start<=e)return t;let s=Wb(i.audio);return s&&s.start<=e?s:null}function Wb(i){if(!i)return null;switch(i.state){case U.IDLE:case U.STOPPED:case U.ENDED:case U.ERROR:return null}return i.frag}function Qo(i,e){return e.getAppendedFrag(i,te.MAIN)||e.getPartialFragment(i)}function qb(i,e,t,s){let r=s.latestLevelDetails,n=Qo(e,t);if(Vu(s.config)&&!i.nextStart&&r&&n&&s.interstitialsManager){let a="type"in n?n:n.fragment,o=PT(r,a.sn);(o==null?void 0:o.level)===a.level&&zT(o,s.interstitialsManager.playerQueue,e)&&(i.nextStart=o.start)}}var _M=.25;function fg(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function op(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,rt(r?ae({type:r},s):s))}return n}var bu=(()=>{let i=fg();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),mg=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){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 r0(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=fg();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===ii.emsg&&!s||!r)continue;let d=dT(n[o].data),u=n[o].pts,c=u+n[o].duration;c>bu&&(c=bu),c-u<=0&&(c=u+_M);for(let f=0;f<d.length;f++){let m=d[f];if(!uT(m)){this.updateId3CueEnds(u,l);let p=op(a,u,c,m,l);p&&this.id3Track.track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let r=(s=this.id3Track)==null?void 0:s.track.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===bu&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===ii.audioId3&&l:r==="video"?d=u=>u.type===ii.emsg&&o:d=u=>u.type===ii.audioId3&&l||u.type===ii.emsg&&o,ug(n.track,t,s,d)}}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:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=fg();if(s&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=op(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.track.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>u.indexOf(g)===-1);for(let g=p.length;g--;){var f;let v=p[g],E=(f=c[v])==null?void 0:f.cues;delete c[v],E&&Object.keys(E).forEach(b=>{let T=E[b];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){let g=u[p],v=d[g],E=v.startTime,b=c[g],T=(b==null?void 0:b.cues)||{},_=(b==null?void 0:b.durationKnown)||!1,I=bu,{duration:S,endDate:x}=v;if(x&&S!==null)I=E+S,_=!0;else if(v.endOnNext&&!_){let R=u.reduce((D,w)=>{if(w!==v.id){let N=d[w];if(N.class===v.class&&N.startDate>v.startDate&&(!D||v.startDate<D.startDate))return N}return D},null);R&&(I=R.startTime,_=!0)}let k=Object.keys(v.attr);for(let R=0;R<k.length;R++){let D=k[R];if(!GD(D))continue;let w=T[D];if(w)_&&!(b!=null&&b.durationKnown)?w.endTime=I:Math.abs(w.startTime-E)>.01&&(w.startTime=E,w.endTime=I);else if(o){let N=v.attr[D];KD(D)&&(N=cT(N));let H=op(o,E,I,{key:D,data:N},ii.dateRange);H&&(H.id=g,this.id3Track.track.addCue(H),T[D]=H,a&&(D==="X-ASSET-LIST"||D==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:v,durationKnown:_}}}}};function F_(){return self.SourceBuffer||self.WebKitSourceBuffer}function B_(){if(!Ir())return!1;let e=F_();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function AM(){if(!B_())return!1;let i=Ir();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(ll(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(ll(e,"audio"))))}function SM(){var i;let e=F_();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var cs={DISABLED:0,SWITCHING:1,SWITCHED:2},IM=100,tc=class extends hl{constructor(e,t,s){super(e,t,s,"stream-controller",te.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=cs.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||!Q(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,te.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(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:s,hls:r}=this;if(this.stopLoad(),this.setInterval(IM),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}s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=U.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=U.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case U.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=U.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=U.IDLE;break}break}case U.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===U.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:s,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(!(s!=null&&s[n]))return;let a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,p),this.state=U.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 d=a.details;if(!d||this.state===U.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=U.WAITING_LEVEL,this.startFragRequested=!1;return}let u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=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,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==ft.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?Je.AUDIO:Je.VIDEO,v=(g===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g)}f=this.getNextFragmentLoopLoading(f,d,o,te.MAIN,c)}f&&(this.exceedsMaxBuffer(o,c,f)||this.loadFragment(f,a,h))}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);r===ft.NOT_LOADED||r===ft.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,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==cs.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===cs.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let s=this.fragPlaying;if(s){let r=s.level;this.hls.trigger(y.FRAG_CHANGED,{frag:s,previousFrag:e}),(e==null?void 0:e.level)!==r&&this.hls.trigger(y.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===cs.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;Ye(s,"playing",this.onMediaPlaying),Ye(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(We(s,"playing",this.onMediaPlaying),We(s,"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(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=cs.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!SM(),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:s}=this;if(!s||this.state!==U.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=U.WAITING_LEVEL)}onLevelLoaded(e,t){var s;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 d=t.levelInfo,u=this.fragCurrent;u&&(this.state===U.FRAG_LOADING||this.state===U.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===U.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=U.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,m)=>{if(m>=o.startCC)return!0;delete this.initPTS[m]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)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&&s.duration>r&&(n<r||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.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 d;let c=be.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}let{nextStart:f}=be.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ju(this.hls,te.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,{decryptRange:g,byteRange:v}=Uu(s,r,this.iframesOnly),E=new cl(s.level,s.sn,s.stats.chunkCount,v?v.end-v.start:n.byteLength,m,p,s.duration,this.iframesOnly,g),b=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,E,b)}onAudioTrackSwitching(e,t){let s=this.hls,r=this.altAudio!==cs.DISABLED;if(Ou(t.url,s))this.altAudio=cs.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=cs.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=Ou(t.url,this.hls);if(s){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=s?cs.SWITCHED:cs.DISABLED,this.tick()}onBufferCreated(e,t){let s=t.tracks,r,n,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=s[o];d&&(this.videoBuffer=d.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:s,part:r}=t,n=s.type===te.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===U.PARSED&&(this.state=U.IDLE);return}let l=!1;if(Et(s)&&(l=!!s.gap&&!s.tagList.some(d=>d[0]==="GAP")),this.fragBufferedComplete(s,r),l){var a;s.stats.retry++;let d=(a=this.levels)==null?void 0:a[s.level];d&&d.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&be.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.MAIN,t);break;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Re.LEVEL&&(this.state=U.IDLE);break;case P.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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case P.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 P.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=U.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Je.AUDIO||!this.altAudio){let s=(t===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,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,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&s&&(s+=r);let n=this.getLevelDetails(),a=be.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_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(s=>{let{hls:r}=this,n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=U.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,s),n.bitrateTest=!1}).catch(s=>{this.state===U.STOPPED||this.state===U.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=U.PARSING,f){let g=f.tracks;if(g){let T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,T,n),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}let v=f.initPTS,E=f.timescale,b=this.initPTS[o.cc];if(Q(v)&&(!b||b.baseTime!==v||b.timescale!==E)){let T=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:E,trackId:T};let _=this.initPTS.slice(0);s.trigger(y.INIT_PTS_FOUND,{timestampOffsets:_,frag:o,id:t,initPTS:v,timescale:E,trackId:T})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,E=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:b,endPTS:T,startDTS:_,endDTS:I}=u;if(l)l.elementaryStreams[u.type]={startPTS:b,endPTS:T,startDTS:_,endDTS:I};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){let S=this.getMainFwdBufferInfo(),x=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,k=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!v&&x<k-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,I,!0)}else v&&b-(m.appliedTimelineOffset||0)>Lu&&(o.gap=!0);o.setElementaryStreamInfo(u.type,b,T,_,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||E)}else if(v||E)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:E,endDTS:b}=p;l&&(l.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:v,startDTS:E,endDTS:b}),o.setElementaryStreamInfo(Je.AUDIO,g,v,E,b),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){let g={id:t,frag:o,details:m,samples:h.samples};s.trigger(y.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};s.trigger(y.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${Et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==U.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=Su(n.codec,d);if(u==="mp4a"&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&!lD()&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&uD()&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=te.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=te.MAIN;let d=a.codec;if((d==null?void 0:d.length)===4)switch(d){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||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),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(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,te.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=U.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 Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let s=this.getLevelDetails(),r=this.currentFrag||(s?Ea(null,s.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}},ic=class extends tc{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:s}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}this.state===U.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(y.BUFFERED_TO_END,this.onBufferedToEnd);let n=this.media;s&&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 s;let r=(s=this.getLevelDetails())==null?void 0:s.edge,n=r!==void 0?r:t.duration;if(e>=n&&(e=n-.01),be.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,te.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&s.length>1;){let n=s.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.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:s,payload:r}=e;this.cacheFragmentData&&!s&&r!=null&&r.byteLength&&!t.data&&Et(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if((r===ft.NOT_LOADED||r===ft.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,s)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let s=e.decryptdata;return(s==null?void 0:s.keyFormat)!=="identity"||!!s.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 s=e.stats=new il;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=U.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(y.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:s,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=U.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!r),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Ku(be.getBuffered(this.media)):"none"}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let s=this.media;if(s){let r=be.bufferInfo(s,e,0),n=r.len?r.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,te.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(y.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(y.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,s){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,te.MAIN);return!!(t!=null&&t.endList)}},pg=class extends ic{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 s=(t=this._img)==null?void 0:t.src;s&&self.URL.revokeObjectURL(s),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 U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}if(this.state===U.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===U.IDLE){let s=this.getBufferedAt(e);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{let s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){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 u=this.hls.levels[e.level];u!=null&&u.fragmentError&&(u.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(y.FRAG_BUFFERED,{frag:e,part:t,stats:h,id:e.type,chunkMeta:s})},n.onerror=()=>{this.handleError("Image decode error",e,t,s)};let l=n.src;l&&self.URL.revokeObjectURL(l);let d=new Blob([r],{type:"image/jpeg"});n.src=self.URL.createObjectURL(d)}else this.state=U.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,r){if(!this.hls)return;let n=new Error(e);this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:s,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,s,r){super.bufferFragmentData(e,t,s,r,!0);let n=Ee(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,s,r);return}let a=t;this.cacheSet(a,n[0]),this.updateImage(a,s,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 s=this.getAppendedFrag(t);if(s&&!zo(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},RM=10,LM="Image I-Frame player does not accept HTMLMediaElements",Yb={seekOnAppend:!0},Tu,lp,gg=class extends si{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,Tu||(Tu=xM(t)),lp||(lp=kM(Tu)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MANIFEST_LOADING,this.clearAsset,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.clearAsset,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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 s;let r=(s=this.hls)==null?void 0:s.pathwayPriority;t.length&&r&&this.iframeInstances.forEach(n=>{n.pathwayPriority=r})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===te.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;let r=this.hls;r&&r.hasEnoughToStart&&(((s=r.mainForwardBufferInfo)==null?void 0:s.len)||0)>RM&&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(Tu,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let s=(t=this.hls)==null?void 0:t.iframeVariants.filter(r=>r.imageCodec);return this.createInstance(lp,s,e,"image-")}createInstance(e,t,s,r){let{hls:n}=this;if(!n)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:u,bandwidthEstimate:c,sessionId:h}=n,{stats:f,variableList:m}=this;if(!(t!=null&&t.length)||!f||!a)return null;let p=`${r||""}iframe-player-${this.instanceCounter++}`,g=n.levels,v=d||g[u],E=CT(v,o.videoPreference),b=(v==null?void 0:v.pathwayId)||".",T=ae(ae({},o),{},{loggerId:p,primarySessionId:h,videoPreference:E,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},s),_=new e(T,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(I=>!I.url),this.iframeInstances.push(_),_.trigger(y.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:b},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:m}),_}};function xM(i){return class extends i{constructor(t,s,r,n){t.streamController||(t.streamController=ic),super(t),this._url=s,this.streamController.setInitPts(r),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,s=Yb){if(t<0)return;let r=ae(ae({},Yb),s);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,r)}}}function kM(i){return class extends i{constructor(t,s,r,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=pg),t.capLevelController=void 0,t.bufferController=void 0,super(t,s,r,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(LM)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var Sr=.025,sc=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function DM(i,e,t){return`${i.identifier}-${t+1}-${el(e)}`}var vg=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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return jb(t,e)?xu(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,s=xu(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=Q(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 jb(t,e)?xu(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)<Sr))}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"?sc.Range:sc.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 CM(this)}};function xu(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Sr)?e.start:e.start+e.duration}function jb(i,e){return e>i.start-Sr&&e<i.start+i.duration+Sr}function $_(i,e,t){let s=new self.URL(i,t);return s.protocol!=="data:"&&Ar(s,"_HLS_primary_id",e),s}function dp(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function CM(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function ha(i){let e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Eg=class{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=s,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 u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,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=$_(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=be.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=be.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 s=t-this.startOffset;if(s>0&&s<e)return s}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 s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ha(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},up=.033,yg=class extends si{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s,0):0}get duration(){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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];t&&t!=="primary"&&(n=n[t]);let a=n.start,o=s[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 s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){let n=s[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 s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){let s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){let a=s[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 s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t,s=0){let r=e.main.details,{dateRanges:n}=r,a=this.events,o=this.parseDateRanges(n,{url:r.url},t),l=Object.keys(n),d=a?a.filter(u=>l.indexOf(u.identifier)===-1):[];o.length&&o.sort((u,c)=>{let h=u.cue.pre,f=u.cue.post,m=c.cue.pre,p=c.cue.post;if(h&&!m)return-1;if(m&&!h||f&&!p)return 1;if(p&&!f)return-1;if(!h&&!m&&!f&&!p){let g=u.startTime,v=c.startTime;if(g!==v)return g-v}return u.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=o,d.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(e,d,s)}updateSchedule(e,t=[],s=0,r=!1){let n=this.events||[];if(n.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(n,e,s);(r||t.length||(a==null?void 0:a.length)!==o.length||o.some((d,u)=>Math.abs(d.playout.start-a[u].playout.start)>.005||Math.abs(d.playout.end-a[u].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){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 d=this.eventMap[o];d?d.setDateRange(l):(d=new vg(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t,s=0){let r=[],n=t.main.details,a=n.live?1/0:n.edge,o=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,u=0;if(e.forEach((c,h)=>{let f=c.cue.pre,m=c.cue.post,p=e[h-1]||null,g=c.appendInPlace,v=m?a:c.startOffset,E=c.duration,b=c.timelineOccupancy===sc.Range?E:0,T=f&&n.live?s+(c.resumeOffset||0):0,_=T||c.resumptionOffset,I=(p==null?void 0:p.startTime)===v,S=v+c.cumulativeDuration,x=g?S+E:v+_;if(f||!m&&v<=0){let R=u;u+=b,c.timelineStart=S;let D=o;o+=E,r.push({event:c,start:S,end:x,playout:{start:D,end:o},integrated:{start:R,end:u}})}else if(v<=a){if(!I){let w=v-d;if(w>up){let N=d,$=u;u+=w;let H=o;o+=w;let O={previousEvent:e[h-1]||null,nextEvent:c,start:N,end:N+w,playout:{start:H,end:o},integrated:{start:$,end:u}};r.push(O)}else w>0&&p&&(p.cumulativeDuration+=w,r[r.length-1].end=v)}m&&(x=S),c.timelineStart=S;let R=u;u+=b;let D=o;o+=E,r.push({event:c,start:S,end:x,playout:{start:D,end:o},integrated:{start:R,end:u}})}else return;let k=T||c.resumeTime;m||k>a?d=a:!f&&x&&c.appendInPlaceStarted&&k-x>up?d=x:d=k}),d<a){var l;let c=d,h=u,f=a-d;u+=f;let m=o;o+=f,r.push({previousEvent:((l=r[r.length-1])==null?void 0:l.event)||null,nextEvent:null,start:d,end:c+f,playout:{start:m,end:o},integrated:{start:h,end:u}})}this.setDurations(a,o,u)}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,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,r=s.live?1/0:s.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=Ea(null,s.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<up&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=Q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>Sr?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;let d=Ea(null,o.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let u=a==="audio"?.175:0;return Math.abs(d.start-s)<Sr+u||Math.abs(d.end-s)<Sr+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ti(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}var bg=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,r;try{r=$_(s,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,P.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(y.ERROR,f);return}t&&r.protocol!=="data:"&&Ar(r,"_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={type:Re.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.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 E=this.assignAssetListError(e,P.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(y.ERROR,E);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,P.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,P.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,u,c),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:ne.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}};function zb(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function gn(i,e){return`[${i}] Advancing timeline position to ${e}`}var Tg=class extends si{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (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 d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=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);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
56
|
+
Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);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 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))),s.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(E){Math.abs(v)>Sr&&this.warn(`${E} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.indexOf(a.event.identifier)>-1){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 bg(e),this.schedule=new yg(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=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){We(e,"play",this.onPlay),We(e,"pause",this.onPause),We(e,"seeking",this.onSeeking),We(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;Ye(s,"seeking",this.onSeeking),Ye(s,"timeupdate",this.onTimeupdate),Ye(s,"play",this.onPlay),Ye(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(s);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 s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(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,s=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!==sc.Point){let E=s(f);(E==null?void 0:E.interstitial)===v&&(g+=E.assetItem.startOffset+E[p])}}else{let E=m==="bufferedPos"?a():e[m];g+=E-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),E=(m=e.schedule.items)==null?void 0:m[v],b=e.getBufferingPlayer(),T=b==null?void 0:b.interstitial,_=T==null?void 0:T.appendInPlace,I=g&&e.itemsMatch(g,E);if(g&&(_||I)){let S=s(e.playingAsset),x=(S==null?void 0:S.media)||e.primaryMedia;if(x){let k=h==="primary"?x.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),R=c-k,D=(_?k:x.currentTime)+R;if(D>=0&&(!S||_||D<=S.duration)){x.currentTime=D;return}}}if(E){let S=c;if(h!=="primary"){let k=E[h].start,R=c-k;S=E.start+R}let x=!e.isInterstitial(E);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(x||E.event.appendInPlace)){let k=e.media||(_?b==null?void 0:b.media:null);k&&(k.currentTime=S)}else if(g){let k=e.findItemIndex(g);if(v>k){let D=e.schedule.findJumpRestrictedIndex(k+1,v);if(D>k){e.setSchedulePosition(D);return}}let R=0;if(x)e.timelinePos=S,e.checkBuffer();else{let D=E.event.assetList,w=c-(E[h]||E).start;for(let N=D.length;N--;){let $=D[N];if($.duration&&w>=$.startOffset&&w<$.startOffset+$.duration){R=N;break}}}e.setSchedulePosition(v,R)}}},d=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},u={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=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};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 d()?u: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 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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.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||!Q(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${rt(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource,u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else{let m=this.getBufferingPlayer();m?(n=m.transferMedia(),this.detachedData=n,u=`${m}`):d?u="detached MediaSource":u="detached media"}if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${rt(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";if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`),!c&&!o){e.attachMedia(t);return}let h=c&&n?ae({},n):{media:t},f=this.schedule;if(f&&o){let m=e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:m||e.appendInPlace===!1}}if(!c&&l){let m=e,p=m.assetItem.timelineStart;if(p){let g=m.hls,v=Math.max(this.timelinePos-p,Number.EPSILON);g.startPosition!==v&&(this.log(`Set ${m} startPosition: ${v}`),g.config.startPosition=v,g.loadingEnabled&&g.startLoad(v))}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=s.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(gn("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(gn("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(gn("checkStart (playing item)",n.start));let a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let s=e.event,r=s.findAssetIndex(t),n=dp(s,r);if(!s.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&&!Q(e.resumeOffset)&&this.hls){let s=this.getLiveStartPos();if(t){let r=this.getBufferingPlayer(),n=r!=null&&r.interstitial.cue.pre?r.remaining:0;return s+n}return s}}getNextItemIndex(e,t){if(this.schedule){let s=this.livePrerollResumption(e.event,t);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){let r=dp(e,s);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 d=e.resumeTime;this.timelinePos<d&&(this.log(gn("advanceAfterAssetEnded",d)),this.timelinePos=d,e.appendInPlace&&!n[o].event&&this.hls.startLoad(d+.01),this.checkBuffer(this.bufferedPos<d)),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 s=this.schedule;if(!s)return;let r=t.parentIdentifier,n=s.getEvent(r);if(n){let a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ti(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,m=f?this.getAssetPlayer(f):null;if(m&&f&&(!this.eventItemsMatch(a,n)||t!==void 0&&f!==c.assetList[t].identifier)){var l;let p=c.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${c.assetList.length} ${ha(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:p,event:c,schedule:r.slice(0),scheduleIndex:e,player:m}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(f,n),m.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&m.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${Ti(a)}`),c.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once&&this.hls)){var d;this.updateSchedule();let p=(d=this.schedule)==null?void 0:d.items;if(n&&p){let g=this.findItemIndex(n),v=this.livePrerollResumption(c);if(v!==void 0){let E=v,b=this.getNextItemIndex(a);if(!this.isInterstitial(r[b])){var u;let T=(u=this.primaryDetails)==null?void 0:u.fragments;if(c.snapOptions.in&&T){let _=Ea(null,T,v);_&&(E=Math.min(Math.max(r[b].start,xu(E,_)),r[b].end))}}if(this.log(gn("live join (preroll)",E)),this.timelinePos=E,b!==g&&(b||b===0)){this.advanceSchedule(b,p,void 0,a,o);return}}this.advanceSchedule(g,p,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{let c=u.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 u=o.event;if(s===void 0){s=u.cue.pre?0:a.findAssetIndex(u,this.timelinePos);let m=dp(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ti(o)} ${u.appendInPlace?"append in place":""}`),u.hasPlayed=!1,this.hls.trigger(y.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&zb(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&zb(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,s){var r,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ti(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(gn("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!s)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ti(e)}`),this.hls.trigger(y.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,s){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,s):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:d}=o;if(r<l||r>d&&!s){let u=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${l}-${d}]) snapping to liveSync ${u}`),u||l}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){var e;let t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,r=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||s&&s-t<r?s||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:be.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(gn("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){let s=this.hls,{loadingEnabled:r,bufferingEnabled:n,startPosition:a}=s,o=s.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 d=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${d?Ti(d):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(e,t)}else n||s.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 s=this.hls.levels[t.level];if(!s.details)return;let r=ae(ae({},this.mediaSelection||this.altSelection),{},{main:s});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 d=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${d?Ti(d):null}`),(d==null?void 0:d.end)===1/0){let c=this.playingItem,h=this.isInterstitial(c)&&c.event.appendInPlace;this.hls.startLoad(Math.max(l,d.start),h)}else{let c=this.getBufferingPlayer();c&&c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(y.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ae(ae({},this.altSelection),{},{audio:s});return}let n=ae(ae({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ae(ae({},this.altSelection),{},{subtitles:s});return}let n=ae(ae({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){let s=Vy(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=Vy(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){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 s=0;s<t.length;s++){let r=t[s];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 s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let r=(s=this.schedule)==null?void 0:s.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 s=e.end+.25,r=be.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ti(e)} (was ${Ti(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let s=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;let r=this.mediaSelection;if(!r)return;let n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(r,[],n,e)}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let r=be.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){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 d;let u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.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>u&&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 s&&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,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:r,events:n}=s;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 ${Ti(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{let h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==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 s=e.event,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart,d=this.playingItem,u=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,h=0;if((!u||u.interstitial.cue.pre)&&this.primaryLive&&(h=this.getLiveStartPos(),u&&(h+=u.remaining)),h&&!(e.cue.pre||e.cue.post)){let m=h-l;m>0&&(c=Math.round(m*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${h?` live-start: ${h} start-offset: ${c} (timeline-start: ${l})`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);let f=this.assetListLoader.loadAssetList(e,c);f&&(e.assetListLoader=f)}else if(!a&&r){for(let d=t;d<r;d++){let u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let s=this.primaryDetails;if(s&&e>=s.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,r,n,a){let o={parentIdentifier:e.identifier,identifier:DM(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let r=this.hls,n=r.userConfig,a=r.loadLevelObj||r.levels[r.currentLevel],o=CT(a,n.videoPreference),l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){let T=this.timelinePos-t.timelineStart;if(T>=0){let _=t.duration;_&&T<_&&(u=T)}}let c=t.identifier,h=ae(ae({},n),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:d||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=Qe({},f,{contentId:el(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let m=new Eg(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0,g=T=>{if(T.live){let S=new Error(`Interstitials MUST be VOD assets ${e}`),x={fatal:!0,type:ne.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:S},k=this.findEventIndex(e.identifier);this.handleAssetItemError(x,e,k,s,S.message);return}let _=T.edge-T.fragmentStart,I=t.duration;(p||I===null||_>I)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${I} > ${_}`),t.duration=_,this.updateSchedule())};m.on(y.LEVEL_UPDATED,(T,{details:_})=>g(_)),m.on(y.LEVEL_PTS_UPDATED,(T,{details:_})=>g(_)),m.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(T,_)=>{let I=this.getAssetPlayer(c);if(I&&_.tracks){I.off(y.BUFFER_CODECS,v),I.tracks=_.tracks;let S=this.primaryMedia;this.bufferingAsset===I.assetItem&&S&&!I.media&&this.bufferAssetPlayer(I,S)}};m.on(y.BUFFER_CODECS,v);let E=()=>{let T=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;let _=this.getEventItem(e.identifier);_&&this.advanceAssetBuffering(_,T.assetItem)};m.on(y.BUFFERED_TO_END,E);let b=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let I=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,I,T)};return m.once(y.MEDIA_ENDED,b(s)),m.once(y.PLAYOUT_LIMIT_REACHED,b(1/0)),m.on(y.ERROR,(T,_)=>{if(!this.schedule)return;let I=this.getAssetPlayer(c);if(_.details===P.BUFFER_STALLED_ERROR){if(I!=null&&I.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(_.details===P.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(_,e,this.findEventIndex(e.identifier),s,`Asset player error ${_.error} ${e}`)}),m.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let _=new Error(`Asset player destroyed unexpectedly ${c}`),I={fatal:!0,type:ne.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(I,e,this.findEventIndex(e.identifier),s,_.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ha(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&Ti(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(u==null?void 0:u.identifier)!==l&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${ha(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s;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 d=(o==null?void 0:o.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!nT(d,e.tracks)){let u=new Error(`Asset ${ha(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),c={fatal:!0,type:ne.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},h=r.findAssetIndex(n);this.handleAssetItemError(c,r,this.findEventIndex(r.identifier),h,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let r=s.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,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){let u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,r,n){if(e.details===P.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&ha(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=Qe({},e,{fatal:!1,errorAction:Zo(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});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==null?void 0:h.identifier)===o?this.advanceAfterAssetEnded(t,s,r):(f==null?void 0:f.identifier)===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,r=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ti(s)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);let d=this.updateItem(s,o);this.itemsMatch(s,d)&&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 s,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,u=0;o.forEach((m,p)=>{let g=parseFloat(m.DURATION);this.createAsset(n,p,u,l+u,g,m.URI),u+=g}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${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 m=this.findEventIndex(a),p=this.getEventItem(a);if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){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(p)}this.setSchedulePosition(m)}else if((f==null?void 0:f.identifier)===a){let m=n.assetList[0];if(m){let p=this.getAssetPlayer(m.identifier);if(f.appendInPlace){let g=this.primaryMedia;p&&g&&this.bufferAssetPlayer(p,g)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case P.ASSET_LIST_PARSING_ERROR:case P.ASSET_LIST_LOAD_ERROR:case P.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case P.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.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}}}},_g=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:s}=this,r=this.levelDetails;if(!s||!r||!this.hls)return;this.currentTime=s.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 d=this.targetLatency;if(d===null)return;let u=a-d,c=Math.min(this.maxLatency,d+r.targetduration),h=u<c,f=Vu(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(h&&u>.05&&this.forwardBufferLength>1&&!f){let m=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,g=Math.min(m,Math.max(1,p));this.changeMediaPlaybackRate(s,g)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,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 s=this.levelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:s,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,d=this.hls.userConfig,u=l&&r||s;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||u===0)&&(u=a!==void 0?a:o*n);let c=n;return u+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 s=this.levelDetails;if(s===null)return null;let r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.hls.config.lowLatencyMode&&s.partTarget||s.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 s=e.buffered.length;return(s?e.buffered.end(s-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),e.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,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),e.off(y.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 s;let r=this.hls,n=this.media||t.event.appendInPlace&&(r==null||(s=r.interstitialsManager)==null?void 0:s.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 s;t.details===P.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.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}},Qb=500,Ag=class extends hl{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",te.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=U.IDLE,this.setInterval(Qb),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:s,part:r,success:n}=t;if(!n)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,l=(r||s).start;for(let u=0;u<a.length;u++)if(l>=a[u].start&&l<=a[u].end){o=a[u];break}let d=l+(r||s).duration;if(o?o.end=d:(o={start:l,end:d},a.push(o)),!r||d>=s.end){let u=this.fragmentTracker.fragBuffered(s);r&&u&&(u.range.subs={time:[{startPTS:s.start,endPTS:d}],partial:!0}),Et(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:s,endOffset:r}=t;if(s===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(s,n,te.SUBTITLE)}}onError(e,t){let s=t.frag;(s==null?void 0:s.type)===te.SUBTITLE&&(t.details===P.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==U.STOPPED&&(this.state=U.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&u_(this.levels,t)){this.levels=t.map(s=>new Tn(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let r=new Tn(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,te.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((s=this.levels)!=null&&s.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!==U.STOPPED&&this.setInterval(Qb)}onSubtitleTrackLoaded(e,t){var s;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 d=this.mainDetails,u=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!d){this.startFragRequested=!1;return}if(l.details){var c;u=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}a.alignedSliding||(Gu(d,a,this),u=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,u),o===r&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:s,payload:r}=e;!s||!(r!=null&&r.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(r,t,s)}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e;this.fragContextChanged(t)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&pa(t.method))}decryptPayload(e,t,s){let r=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,Vg(r.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(y.FRAG_DECRYPTED,{frag:t,part:s,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=U.IDLE)})}doTick(){if(this.state===U.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:s,levels:r}=this,n=r[s],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,d=be.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:u,len:c}=d,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(u,a);if(!f)return;if(Et(f)){var t;let m=f.sn-a.startSN,p=a.fragments[m-1];f.cc===(p==null?void 0:p.cc)&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(p)===ft.NOT_LOADED&&(f=p)}this.loadFragment(f,n,u)}}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);(r===ft.NOT_LOADED||r===ft.PARTIAL)&&super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new Sg(this.tracksBuffered[this.currentTrackId]||[])}},Sg=class{constructor(e){this.buffered=void 0;let t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},wM={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},H_=i=>String.fromCharCode(wM[i]||i),Yi=15,qi=42,MM={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},PM={17:2,18:4,21:6,22:8,23:10,19:13,20:15},OM={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},NM={25:2,26:4,29:6,30:8,31:10,27:13,28:15},UM=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Ig=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;$e.log(`${this.time} [${e}] ${s}`)}}},vn=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Rg=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),rc=class{constructor(){this.styles=Rg}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=Rg}setStyles(e){let t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Lg=class{constructor(){this.uchar=" ",this.penState=new rc}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}},xg=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new rc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<qi;t++)this.chars.push(new Lg);this.logger=e}equals(e){let t=this.chars,s=e.chars;for(let r=0;r<qi;r++){let n=t[r],a=s[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<qi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<qi;t++){let s=e[t];if(s.uchar!==" ")return!1;let r=s.penState.styles;if(r!==Rg&&(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>=qi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qi-1)}moveCursor(e){let t=Math.min(this.pos+e,qi);if(e>1)for(let s=this.pos+1;s<t;s++)this.chars[s].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=H_(e);if(this.pos>=qi){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<qi;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 s=0;s<qi;s++){let r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},tl=class{constructor(e){this.rows=[],this.currRow=Yi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Yi;t++)this.rows.push(new xg(e));this.logger=e}reset(){for(let e=0;e<Yi;e++)this.rows[e].clear();this.currRow=Yi-1}equals(e){let t=!0;for(let s=0;s<Yi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Yi;t++){let s=this.rows[t].chars,r=e.rows[t].chars;for(let n=0;n<qi;n++){let a=s[n],o=r[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Yi;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 = "+rt(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<Yi;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 d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.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 = "+rt(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=[],s="",r=-1;for(let n=0;n<Yi;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?s="["+t.join(" | ")+"]":s=t.join(`
|
|
57
|
+
`)),s}getTextAndFormat(){return this.rows}},kg=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new tl(s),this.nonDisplayedMemory=new tl(s),this.lastOutputScreen=new tl(s),this.currRollUpRow=this.displayedMemory.rows[Yi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Yi-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+rt(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))}},nc=class{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=BM(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Ig,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,(s=this.channels[e])==null||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new kg(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){let r=t[s]&127,n=t[s+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+vn([t[s],t[s+1]])+"] -> ("+vn([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(FM(r,n,l)){_u(null,null,l),this.logger.log(3,()=>"Repeated command ("+vn([r,n])+") is dropped");continue}_u(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 _u(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let u=this.currentChannel;u&&u>0?this.getChannel(u).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+vn([r,n])+" orig: "+vn([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(s||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 s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[s];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+vn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,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?s=a===1?MM[e]:OM[e]:s=a===1?PM[e]:NM[e],this.getChannel(a).setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0}interpretPAC(e,t){let s,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,r.underline=(s&1)===1,s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((s-16)/2)*4,r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=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 '"+H_(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+vn(r).join(",")),r}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(s||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=UM[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()}_u(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function _u(i,e,t){t.a=i,t.b=e}function FM(i,e,t){return t.a===i&&t.b===e}function BM(){return{a:null,b:null}}var ma=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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dg=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=Xb(),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(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_APPENDED,this.onBufferAppended,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_APPENDED,this.onBufferAppended,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 ma(this,"textTrack1"),t=new ma(this,"textTrack2"),s=new ma(this,"textTrack3"),r=new ma(this,"textTrack4");this.cea608Parser1=new nc(1,e,t),this.cea608Parser2=new nc(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let l=n.length;l--;){let d=n[l],u=$M(d[0],d[1],t,s);if(u>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],s),a=!0,u/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let d=this.Cues.newCue(null,t,s,r);d.length&&l.push.apply(l,d)}else{let d=this.captionsTracks[e].track;this.Cues.newCue(d,t,s,r)}}else{var o;let l=this.Cues.newCue(null,t,s,r),d=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:d})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){let{unparsedVttFrags:r}=this;t===te.MAIN&&(this.initPTS=s),r.length&&(this.unparsedVttFrags=[],r.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,n):this.hls.trigger(y.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:s,cueCache:r,media:n}=this,{label:a,languageCode:o}=t[e];n&&(r[e]=[],s[e]=r0(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,r={_id:e,label:s,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]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,!s){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=Xb(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!u_(this.tracks,s)){let r=s.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}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===te.MAIN){var s,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:s,payload:r}=t;if(s.level<this.tracks.length&&s.type===te.SUBTITLE){var n;if(r.byteLength||(n=s.initSegment)!=null&&(n=n.data)!=null&&n.byteLength){let a=s.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){let l=this.tracks[s.level],d=this.vttCCs;d[s.cc]||(d[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(l==null?void 0:l.textCodec)===lg?this._parseIMSC1(t):this._parseVTTs(t)}}else{let a="part"in t?t.part:null;this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:s}=e,r="part"in e?e.part:null,n=this.hls;Hb(s,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:a})})}_parseVTTs(e){var t;let{frag:s,payload:r}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(e);return}let d=this.hls,u=(t=s.initSegment)==null?void 0:t.data,c=u?Ci(u,new Uint8Array(r)).buffer:r;hM(c,this.initPTS[s.cc],this.vttCCs,s.cc,(n&&!u?n:s).start,h=>{this._appendCues(h,s.level),d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:n})},h=>{let f=h.message.startsWith("Missing initPTS");if(d.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${h}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:n,error:h})})}_fallbackToIMSC1(e){let{frag:t,payload:s}=e,r=this.tracks[t.level];r.textCodec||Hb(s,this.initPTS[t.cc],()=>{r.textCodec=lg,this._parseIMSC1(e)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){let s=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=>dg(n,a))}else{let n=this.tracks[t];if(!n)return;let a=n.default?"default":"subtitles"+t;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===te.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:r}=t;if(!(s.type===te.MAIN&&this.closedCaptionsForLevel(s)==="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 s;let{type:r,timeRanges:n}=t;if(r==="video"&&(s=n[r])!=null&&s.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var d;let u=(d=a[l])==null?void 0:d.track;if(u){let c=o[l];for(let h=0;h<c.length;h++)dg(u,c[h])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:s,endOffset:r,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a==="video"){let{captionsTracks:l,cueCache:d}=this;Object.keys(l).forEach(u=>ug(l[u].track,s,r)),Object.keys(d).forEach(u=>{let c=d[u];for(let h=c.length;h--;){let f=c[h];f.startTime>=s&&f.endTime<=r&&c.splice(h,1)}})}this.config.renderTextTracksNatively&&s===0&&n!==void 0&&this.tracks.forEach(l=>{var d;let u=(d=l.trackNode)==null?void 0:d.track;u&&ug(u,s,n)})}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,r=2;for(let n=0;n<s;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function $M(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function Xb(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var HM=/\s/,GM={newCue(i,e,t,s){let r=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)HM.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=P_(d.trim()),m=s0(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(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 i&&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=>dg(i,h))),r}},ac=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 il}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){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=s,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(sl(e,t,!0))this.retry(e);else{var s;$e.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=Ug(e,s.retry),s.retry++,$e.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function KM(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var VM=/(\d+)-(\d+)\/(\d+)/,oc=class extends ac{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||jM}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:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;let r=WM(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&&Q(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(pl(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var c;this.response=u;let h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(h-s.loading.start)),!u.ok){let{status:m,statusText:p}=u;throw new Cg(p||"fetch, bad network response",m,u)}s.loading.first=h,s.total=YM(u.headers)||s.total;let f=(c=this.callbacks)==null?void 0:c.onProgress;return f&&Q(e.highWaterMark)?this.loadProgressively(u,s,t,e.highWaterMark,f):n?u.arrayBuffer():t.responseType==="json"?u.json():u.text()}).then(u=>{var c,h;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let m=u[a];m&&(s.loaded=s.total=m);let p={url:f.url,data:u,code:f.status},g=(c=this.callbacks)==null?void 0:c.onProgress;g&&!Q(e.highWaterMark)&&g(s,t,u,f),(h=this.callbacks)==null||h.onSuccess(p,s,t,f)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;let c=u&&u.code||0,h=u?u.message:null,f=e.loadPolicy.errorRetry,m=s.retry,p={url:t.url,data:void 0,code:c};if(sl(f,m,!1,p))this.retry(f);else{var g;$e.error(`${c} while loading ${t.url}`),(g=this.callbacks)==null||g.onError({code:c,text:h},t,u?u.details:null,s)}})}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,s,r=0,n){let a=new Wu,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function WM(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Qe({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function qM(i){let e=VM.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function YM(i){let e=i.get("Content-Range");if(e){let s=qM(e);if(Q(s))return s}let t=i.get("Content-Length");if(t)return parseInt(t)}function jM(i,e){return new self.Request(i.url,e)}var Cg=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},zM=(i,e,t)=>Math.max(e,Math.min(i,t)),QM=/^age:\s*[\d.]+\s*$/im,lc=class extends ac{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 s=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!==s||this.stats.aborted))return n.call(this,s,t.url,t)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.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),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=u!=null?u:t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);let v={url:t.responseURL,data:m,code:d};e.rangeEnd&&p!==e.rangeEnd-e.rangeStart&&$e.warn(`Payload length ${p} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(sl(c,h,!1,f))this.retry(c);else{var l;$e.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&QM.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}},XM={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ZM=ae(ae({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:lc,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:$T,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:XM},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:tc,abrController:Tp,bufferController:jp,capLevelController:El,errorController:_p,fpsController:sg,id3TrackController:mg,gapController:hg,latencyController:_g},JM()),{},{subtitleStreamController:Ag,subtitleTrackController:cg,timelineController:Dg,audioStreamController:Vp,audioTrackController:Wp,emeController:ec,cmcdController:eg,contentSteeringController:tg,iframeController:gg,interstitialsController:Tg});function JM(){return{cueHandler:GM,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 eP(i,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=zM(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let s=wg(i),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,d=[];n.forEach(u=>{let c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);let f=s[o].default;switch(e[o]={default:f},u){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}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${rt(e[o])}`)}),ae(ae({},s),e)}function wg(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(wg):Object.keys(i).reduce((e,t)=>(e[t]=wg(i[t]),e),{}):i}function tP(i,e){let t=i.loader;t!==oc&&t!==lc?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):KM()&&(i.loader=oc,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Mg=class extends gl{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(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,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,d=!1,u=!1;t.levels.forEach(c=>{let h=c.attrs,f=Zb(c,s),{audioCodec:m,videoCodec:p,imageCodec:g,width:v,height:E}=c;if(!f){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}o||(o=!!(v&&E)),l||(l=!!p),d||(d=!!m),u||(u=!!g);let{CODECS:b,"FRAME-RATE":T,"HDCP-LEVEL":_,"PATHWAY-ID":I,RESOLUTION:S,"VIDEO-RANGE":x}=h,R=`${`${I||"."}-`}${c.bitrate}-${S}-${T}-${b}-${x}-${_}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let D=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");let w=this.createLevel(c);n[R]=w,r.push(w)}else c.iframes||(n[R].addGroupId("audio",h.AUDIO),n[R].addGroupId("text",h.SUBTITLES));else{let D=this.createLevel(c);n[R]=D,a[R]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,d,u)}createLevel(e){let t=new Tn(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!K_(s.videoCodec,this.hls.config.preferManagedMediaSource)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=RT(r,[])}return t}filterAndSortMediaOptions(e,t,s,r,n,a){var o;let l=[],d=[],u=e,c=((o=t.stats)==null?void 0:o.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((s||r)&&n&&(u=u.filter(({videoCodec:_,videoRange:I,width:S,height:x})=>(!!_||!!(S&&x))&&AD(I))),r&&a&&(u=u.filter(_=>!_.imageCodec)),u.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",I=_;t.levels.length&&(I=`one or more CODECS in variant not supported: ${rt(t.levels.map(x=>x.attrs.CODECS).filter((x,k,R)=>R.indexOf(x)===k))}`,this.warn(I),_+=` (${I})`);let S=new Error(_);this.hls.trigger(y.ERROR,{type:ne.MEDIA_ERROR,details:P.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:I})}}),c.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(_=>!_.audioCodec||G_(_.audioCodec,h)),Jb(l)),t.subtitles&&(d=t.subtitles,Jb(d));let f=u.slice(0);u.sort((_,I)=>{if(_.attrs["HDCP-LEVEL"]!==I.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(I.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&_.height!==I.height)return _.height-I.height;if(_.frameRate!==I.frameRate)return _.frameRate-I.frameRate;if(_.videoRange!==I.videoRange)return Mu.indexOf(_.videoRange)-Mu.indexOf(I.videoRange);if(_.videoCodec!==I.videoCodec){let S=By(_.videoCodec),x=By(I.videoCodec);if(S!==x)return x-S}if(_.uri===I.uri&&_.codecSet!==I.codecSet){let S=Cu(_.codecSet),x=Cu(I.codecSet);if(S!==x)return x-S}return _.averageBitrate!==I.averageBitrate?_.averageBitrate-I.averageBitrate:0});let m=f[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==f.length)){for(let _=0;_<f.length;_++)if(f[_].pathwayId===u[0].pathwayId){m=f[_];break}}this._levels=u;for(let _=0;_<u.length;_++)if(u[_]===m){var p;this._firstLevel=_;let I=m.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${I}`),((p=this.hls.userConfig)==null?void 0:p.abrEwmaDefaultEstimate)===void 0){let x=Math.min(I,this.hls.config.abrEwmaDefaultEstimateMax);x>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}let g=t.iframeVariants.filter(_=>Zb(_,h));this._iframeVariants=g;let v=n&&!r,E=this.hls.config,b=!!(E.audioStreamController&&E.audioTrackController),T={levels:u,audioTracks:l,subtitleTracks:d,iframeVariants:g,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:b&&!v&&l.some(_=>!!_.url)};c.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,T)}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 u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(y.ERROR,{type:ne.OTHER_ERROR,details:P.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let s=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,s===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 ${s}${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 d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,r==null?void 0:r.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){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(),s=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=s}}onError(e,t){t.fatal||!t.context||t.context.type===Re.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===te.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[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 s;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(s=t.deliveryDirectives)!=null&&s.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 s=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||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,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 s=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));YT(s),this._levels=s,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=s.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:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}};function G_(i,e){return ol(i,"audio",e)}function K_(i,e){return ol(i,"video",e)}function Zb(i,e){let{audioCodec:t,videoCodec:s}=i;t&&(i.audioCodec=t=wu(t,e)||void 0),s&&(s=i.videoCodec=mD(s));let{unknownCodecs:r}=i;return!((r==null?void 0:r.length)||0||t&&!G_(t,e)||s&&!K_(s,e))}function Jb(i){let e={};i.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var Pg=class extends si{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyLoaderInfo){let r=this.keyLoaderInfo[s].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,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);let r=e.decryptdata;if(!r){let a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Er(e,P.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(Er(e,P.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 s=jk(e.initSegment.data);if(s.length){let r=s[0],n=e.decryptdata.uri;if(r.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ct(r)} keyUri: ${n}`),_n.setKeyIdForUri(n,r);else{let a=_n.addKeyIdForUri(n);this.log(`Patching empty keyId with ${Ct(a)} keyUri: ${n}`),r=a}e.decryptdata.keyId=r}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Er(e,P.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(Er(e,P.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));let r=this.keyLoaderInfo[s];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(d=>(t.key=r.decryptdata.key,ae(ae({},d),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ct(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[s]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((d,u)=>{let c={type:Re.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:s},h=n.keyLoadPolicy.default,f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(p,g,v,E)=>{let{frag:b,keyInfo:T,url:_}=v;if(!b.decryptdata||T!==this.keyLoaderInfo[_])return u(Er(b,P.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),E));T.decryptdata.key=b.decryptdata.key=new Uint8Array(p.data),b.keyLoader=T.loader=T.keyLoadPromise=null,d({frag:b,keyInfo:T})},onError:(p,g,v,E)=>{this.resetLoader(g),u(Er(e,P.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),v,ae({url:s,data:void 0},p)))},onTimeout:(p,g,v)=>{this.resetLoader(g),u(Er(e,P.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(p,g,v)=>{this.resetLoader(g),u(Er(e,P.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};o.load(c,f,m)})}resetLoader(e){let{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[r],n&&n.destroy()}};function Er(i,e=P.KEY_LOAD_ERROR,t,s,r){return new Di({type:ne.NETWORK_ERROR,details:e,fatal:!1,frag:i,response:r,error:t,networkDetails:s||null})}function eT(i){let{type:e}=i;switch(e){case Re.AUDIO_TRACK:return te.AUDIO;case Re.SUBTITLE_TRACK:return te.SUBTITLE;default:return te.MAIN}}function cp(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Og=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,s=t.pLoader,r=t.loader,n=s||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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Re.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:Re.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Re.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Re.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Re.LEVEL];if(s){let r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[Re.LEVEL])}}load(e){var t;let s=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,u=r.context;if((u==null?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===Re.MANIFEST?n=s.manifestLoadPolicy.default:n=Qe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Re.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Re.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Re.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let u=d.partTarget,c=d.targetduration;if(u&&c){let h=Math.max(u*3,c*.8)*1e3;n=Qe({},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:(d,u,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=d.data;u.parsing.start=performance.now(),_r.isMediaPlaylist(m)||c.type!==Re.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){let n=this.hls,a=e.data,o=cp(e,s),l=_r.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:u,iframeVariants:c,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p}=l;this.variableList=p,u.forEach(b=>{let{unknownCodecs:T}=b;if(T){let{preferManagedMediaSource:_}=this.hls.config,{audioCodec:I,videoCodec:S}=b;for(let x=T.length;x--;){let k=T[x];ol(k,"audio",_)?(b.audioCodec=I=I?`${I},${k}`:k,va.audio[I.substring(0,4)]=2,T.splice(x,1)):ol(k,"video",_)&&(b.videoCodec=S=S?`${S},${k}`:k,va.video[S.substring(0,4)]=2,T.splice(x,1))}}});let{AUDIO:g=[],SUBTITLES:v,"CLOSED-CAPTIONS":E}=_r.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(T=>!T.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ht({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:v,iframeVariants:c,captions:E,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p})}handleTrackOrLevelPlaylist(e,t,s,r,n){let a=this.hls,{id:o,level:l,type:d}=s,u=cp(e,s),c=Q(l)?l:Q(o)?o:0,h=eT(s),f=_r.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Re.MANIFEST){let m={attrs:new ht({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+VT(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[m],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(y.ERROR,{type:ne.NETWORK_ERROR,details:P.MANIFEST_PARSING_ERROR,fatal:t.type===Re.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Re.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Re.AUDIO_TRACK||e.type===Re.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=P.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Re.MANIFEST:l=s?P.MANIFEST_LOAD_TIMEOUT:P.MANIFEST_LOAD_ERROR,d=!0;break;case Re.LEVEL:l=s?P.LEVEL_LOAD_TIMEOUT:P.LEVEL_LOAD_ERROR,d=!1;break;case Re.AUDIO_TRACK:l=s?P.AUDIO_TRACK_LOAD_TIMEOUT:P.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Re.SUBTITLE_TRACK:l=s?P.SUBTITLE_TRACK_LOAD_TIMEOUT:P.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:ne.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=e.url;t&&"url"in t&&(h=t.url),c.response=ae({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=cp(t,r),p=eT(r),g=typeof r.level=="number"&&p===te.MAIN?d:void 0;u&&"iframes"in u&&u.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 v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:ne.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:ne.NETWORK_ERROR,details:P.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:E,reason:E.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Re.MANIFEST:case Re.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){let E=o.levels.indexOf(u);E>-1&&(g=E)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Re.MANIFEST,context:r});break;case Re.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f,context:r});break;case Re.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f,context:r});break}}},bl=class i{static get version(){return fl}static isMSESupported(){return B_()}static isSupported(){return AM()}static getMediaSource(){return Ir()}static get Events(){return y}static get MetadataSchema(){return ii}static get ErrorTypes(){return ne}static get ErrorDetails(){return P}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:ZM}static set DefaultConfig(e){i.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 qg,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=Tk(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),s=this.config=eP(i.DefaultConfig,e,t);this.userConfig=e,s.progressive&&tP(s,t);let{streamController:r,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:d,id3TrackController:u,iframeController:c,gapController:h}=s,f=new l(this),m=this.abrController=new n(this),p=new Ap(this),g=s.interstitialsController,v=g?this.interstitialsController=new g(this,i):null,E=a?this.bufferController=new a(this,p):null,b=o?this.capLevelController=new o(this):null,T=d?new d(this):null,_=s.cmcdController,I=_?this.cmcdController=new _(this):null,S=new Og(this),x=s.contentSteeringController,k=x?new x(this):null,R=this.levelController=new Mg(this,k),D=u?new u(this):void 0,w=new Pg(this.config,this.logger),N=this.streamController=new r(this,p,w),$=this.gapController=h?new h(this,p):void 0;b&&b.setStreamController(N);let H=[S,R,N];v&&H.splice(1,0,v),k&&H.splice(1,0,k),this.networkControllers=H;let O=[m];E&&O.push(E),$&&O.push($),b&&O.push(b),T&&(T.setStreamController(N),O.push(T)),D&&O.push(D),O.push(p),this.audioTrackController=this.createController(s.audioTrackController,H);let F=s.audioStreamController;F&&H.push(this.audioStreamController=new F(this,p,w)),this.subtitleTrackController=this.createController(s.subtitleTrackController,H);let B=s.subtitleStreamController;B&&H.push(this.subtititleStreamController=new B(this,p,w)),this.createController(s.timelineController,O),w.emeController=this.emeController=this.createController(s.emeController,O),I&&O.push(I),this.latencyController=this.createController(s.latencyController,O),this.coreComponents=O,this.iframeController=c?new c(this,i):void 0,H.push(f);let W=f.onErrorOut;typeof W=="function"&&this.on(y.ERROR,W,f),this.on(y.MANIFEST_LOADED,S.onManifestLoaded,S)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let r=e===y.ERROR;this.trigger(y.ERROR,{type:ne.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),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,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(y.ERROR,{type:ne.OTHER_ERROR,details:P.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,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(y.MEDIA_DETACHING,e),this._media=null,this.trigger(y.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(y.MEDIA_DETACHING,s),this.trigger(y.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();let s=this.media,r=this._url,n=this._url=Ng.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),s&&r&&(r!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),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 s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==U.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={[te.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[te.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[te.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,s=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=oT()),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,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}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){_D(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 s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)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 s=DT(t);return LT(e,s,navigator.mediaCapabilities)}};bl.defaultConfig=void 0;var ke=bl,qe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},oe={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},Il=i=>i===qe.VIDEO?"playback":i,Lr=class _l extends Error{constructor(e,t=_l.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s!=null?s:t>=_l.MEDIA_ERR_NETWORK&&t<=_l.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=_l.defaultMessages[this.code])!=null?n:"")}};Lr.MEDIA_ERR_ABORTED=1,Lr.MEDIA_ERR_NETWORK=2,Lr.MEDIA_ERR_DECODE=3,Lr.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Lr.MEDIA_ERR_ENCRYPTED=5,Lr.MEDIA_ERR_CUSTOM=100,Lr.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 X=Lr,iP=i=>i==null,b0=(i,e)=>iP(e)?!1:i in e,d0={ANY:"any",MUTED:"muted"},He={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},wi={MSE:"mse",NATIVE:"native"},Al={HEADER:"header",QUERY:"query",NONE:"none"},_a=Object.values(Al),zs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},u0={HLS:zs.M3U8},uF=Object.keys(u0),cF=[...Object.values(zs),"hls","HLS"];var sP="en",c0={code:sP},rP=i=>{let e=i;for(;e;){if(e.hasAttribute("lang"))return e.getAttribute("lang")||void 0;let t=e.getRootNode();e=t instanceof ShadowRoot?t.host:void 0}},nP=i=>{var e,t,s;let r=(s=(e=globalThis.navigator)==null?void 0:e.languages)!=null?s:[(t=globalThis.navigator)==null?void 0:t.language];return[rP(i),...r].filter(n=>!!n)},Tt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function aP(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var Ec=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},yc=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return b0(t,u0)?u0[t]:e}return oP(i)},J_=i=>i==="VOD"?He.ON_DEMAND:He.LIVE,eA=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,oP=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=bc(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let s=t.lastIndexOf(".");if(s<0)return uP(i)?zs.M3U8:"";let r=t.slice(s+1).toUpperCase();return b0(r,zs)?zs[r]:""},h0=i=>{try{return new URL(i),!1}catch{return!0}},lP=i=>i.split(`
|
|
58
|
+
`).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),bc=(i,e)=>{var t;if(!h0(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&h0(e.toString())&&(r=new URL(e,s)),new URL(i,r)},dP="mux.com",uP=({src:i,customDomain:e=dP})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},xr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},cP=({exp:i},e=Date.now())=>!i||i*1e3<e,hP=({sub:i},e)=>i!==e,fP=({aud:i},e)=>!i,mP=({aud:i},e)=>i!==e,tA="en";function se(i,e=!0){var t,s;let r=e&&(s=(t=c0)==null?void 0:t[i])!=null?s:i,n=e?c0.code:tA;return new pP(r,n)}var pP=class{constructor(i,e=(t=>(t=c0)!=null?t:tA)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},gP=Object.values(d0),V_=i=>typeof i=="boolean"||typeof i=="string"&&gP.includes(i),vP=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=V_(s)?s:!!s,o=()=>{r||Tt(e,"playing",()=>{r=!0},{once:!0})};if(o(),Tt(e,"loadstart",()=>{r=!1,o(),n0(e,a)},{once:!0}),Tt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==He.UNKNOWN?n=i.streamType===He.LIVE:n=!Number.isFinite(e.duration)),n0(e,a)},{once:!0}),t&&t.once(ke.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==He.UNKNOWN?n=i.streamType===He.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Tt(e,"play",()=>{e.preload==="metadata"?t.once(ke.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=V_(l)?l:!!l,n0(e,a))}},n0=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case d0.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case d0.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},EP=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return Tt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},yP=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=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,Tt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(ke.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(ke.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},bP=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(ke.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function TP(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(ke.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(ke.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(ke.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(ke.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var W_=i=>i.split("-")[0],fc=({language:i})=>typeof i=="string"?i.toLowerCase():void 0;function _P(i,e){var t,s;let r=e.toLowerCase(),n=W_(r);return(s=(t=i.find(a=>fc(a)===r))!=null?t:i.find(a=>fc(a)===n))!=null?s:i.find(a=>{let o=fc(a);return o!==void 0&&W_(o)===n})}function AP(i,e){var t;let s=(Array.isArray(i)?i:[]).filter(r=>typeof(r==null?void 0:r.title)=="string"&&r.title!=="");if(!s.length)return"";for(let r of e){let n=_P(s,r);if(n)return n.title}return((t=s.find(r=>fc(r)==="und"))!=null?t:s[0]).title}function SP(i,e=[]){return Array.isArray(i)?i.filter(t=>typeof(t==null?void 0:t["start-time"])=="number").map((t,s,r)=>{var n;let a=t["start-time"],o=(n=r[s+1])==null?void 0:n["start-time"],l=typeof t.duration=="number"?a+t.duration:typeof o=="number"?o:void 0;return{startTime:a,...l!=null?{endTime:l}:{},value:AP(t.titles,e)}}).filter(t=>t.value!==""):[]}var iA=Number.MAX_SAFE_INTEGER,a0=i=>"time"in i?i.time:i.startTime;function IP(i,e){e.on(ke.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(d==null?void 0:d.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;Tc(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.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:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(ke.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(ke.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let a="track";r.kind&&(a+=`[kind="${r.kind}"]`),r.label&&(a+=`[label="${r.label}"]`);let o=i.querySelector(a),l=o==null?void 0:o.getAttribute("src");o&&l&&(o.removeAttribute("src"),setTimeout(()=>{o.setAttribute("src",l)},0))}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(ke.Events.MANIFEST_LOADED,s),e.once(ke.Events.MEDIA_ATTACHED,s)}function Tc(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function sA(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function Rl(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}var o0=new WeakMap;async function T0(i,e,t){let s=Rl(i,e,t);if(s){let a=o0.get(s);return a&&await a,s}let r=Tc(i,t,e);r.mode="hidden";let n=new Promise(a=>setTimeout(a,0));return o0.set(r,n),await n,o0.delete(r),r}async function RP(i,e,t,s){let r=await T0(i,t,s);return _0(i,r,e,s),r}function _0(i,e,t,s){e.mode!=="hidden"&&(e.mode="hidden"),[...t].sort((r,n)=>a0(n)-a0(r)).forEach(r=>{var n,a;let o=r.value,l=a0(r);if("endTime"in r&&r.endTime!=null&&Number.isFinite(r.endTime))e==null||e.addCue(new VTTCue(l,r.endTime,s==="chapters"?o:JSON.stringify(o!=null?o:null)));else{let d=Array.prototype.findIndex.call(e==null?void 0:e.cues,f=>f.startTime>=l),u=(n=e==null?void 0:e.cues)==null?void 0:n[d],c=u?u.startTime:Number.isFinite(i.duration)&&i.duration>0?i.duration:iA,h=(a=e==null?void 0:e.cues)==null?void 0:a[d-1];h&&(h.endTime=l),e==null||e.addCue(new VTTCue(l,c,s==="chapters"?o:JSON.stringify(o!=null?o:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))}var A0="cuepoints",rA=Object.freeze({label:A0});async function S0(i,e,t=rA){return RP(i,e,t.label,"metadata")}var f0=i=>({time:i.startTime,value:JSON.parse(i.text)});function nA(i,e={label:A0}){let t=Rl(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>f0(s)):[]}function I0(i,e={label:A0}){var t,s;let r=Rl(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return f0(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return f0(a||r.activeCues[0])}async function LP(i,e=rA){return new Promise(t=>{Tt(i,"loadstart",async()=>{let s=await S0(i,[],e);Tt(i,"cuechange",()=>{let r=I0(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var R0="chapters",L0=Object.freeze({label:R0}),m0=(i,e)=>{let{duration:t}=e,s=Number.isFinite(t)&&t>0?Math.min(i.endTime,t):i.endTime>=iA?1/0:i.endTime;return{startTime:i.startTime,endTime:s,value:i.text}},p0=new WeakSet;function aA(i){var e;Array.from((e=i.cues)!=null?e:[]).filter(t=>p0.has(t)).forEach(t=>i.removeCue(t))}async function x0(i,e,t=L0){let s=await T0(i,t.label,"chapters");return e.length&&aA(s),_0(i,s,e,"chapters"),s}async function xP(i,e,t,s=L0){var r,n;let a=await T0(i,s.label,"chapters");return t!=null&&t.aborted||Array.from((r=a.cues)!=null?r:[]).some(o=>!p0.has(o))||(aA(a),_0(i,a,e,"chapters"),Array.from((n=a.cues)!=null?n:[]).forEach(o=>p0.add(o))),a}function oA(i,e={label:R0}){var t;let s=Rl(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>m0(r,i)):[]}function k0(i,e={label:R0}){var t,s;let r=Rl(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return m0(r.activeCues[0],i);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return m0(a||r.activeCues[0],i)}async function kP(i,e=L0){return new Promise(t=>{Tt(i,"loadstart",async()=>{let s=await x0(i,[],e);Tt(i,"cuechange",()=>{let r=k0(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function lA(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function dA(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var Ta={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},DP=i=>{if(i===qe.VIDEO)return Ta.VIDEO;if(i===qe.DRM)return Ta.DRM},CP=(i,e)=>{var t,s;let r=Il(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:b0(n,e)?e[n]:void 0},gc=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a;if(n){let g=se("Your device appears to be offline",r),v,E=X.MEDIA_ERR_NETWORK,b=new X(g,E,!1,v);return b.errorCategory=e,b.muxCode=oe.NETWORK_OFFLINE,b.data=i,b}let o="status"in i?i.status:i.code,l=Date.now(),d=X.MEDIA_ERR_NETWORK;if(o===200)return;let u=Il(e),c=CP(e,t),h=DP(e),[f]=Ec((a=t.playbackId)!=null?a:"");if(!o||!f)return;let m=xr(c);if(c&&!m){let g=se("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:u}),v=se("Compact JWT string: {token}",r).format({token:c}),E=new X(g,d,!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_MALFORMED,E.data=i,E}if(o>=500){let g=new X("",d,s!=null?s:!0);return g.errorCategory=e,g.muxCode=oe.NETWORK_UNKNOWN_ERROR,g}if(o===403)if(m){if(cP(m,l)){let g={timeStyle:"medium",dateStyle:"medium"},v=se("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:u}),E=new Intl.DateTimeFormat("en",g).format(l),b=m.exp?se("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",g).format(m.exp*1e3),currentDate:E}):se("The {tokenNamePrefix}-token has no exp value. Current time: {currentDate}.",r).format({tokenNamePrefix:u,currentDate:E}),T=new X(v,d,!0,b);return T.errorCategory=e,T.muxCode=oe.NETWORK_TOKEN_EXPIRED,T.data=i,T}if(hP(m,f)){let g=se("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:u}),v=se("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:u,playbackId:f,tokenPlaybackId:m.sub}),E=new X(g,d,!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_SUB_MISMATCH,E.data=i,E}if(fP(m,h)){let g=se("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:u}),v=se("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:u,expectedAud:h}),E=new X(g,d,!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_AUD_MISSING,E.data=i,E}if(mP(m,h)){let g=se("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:u}),v=se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:u,expectedAud:h,aud:m.aud}),E=new X(g,d,!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_AUD_MISMATCH,E.data=i,E}}else{let g=se("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:u,category:e}),v=se("Specified playback ID: {playbackId}",r).format({playbackId:f}),E=new X(g,d,s!=null?s:!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_TOKEN_MISSING,E.data=i,E}if(o===412){let g=se("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),v=se("Specified playback ID: {playbackId}",r).format({playbackId:f}),E=new X(g,d,s!=null?s:!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_NOT_READY,E.streamType=t.streamType===He.LIVE?"live":t.streamType===He.ON_DEMAND?"on-demand":"unknown",E.data=i,E}if(o===404){let g=se("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),v=se("Specified playback ID: {playbackId}",r).format({playbackId:f}),E=new X(g,d,s!=null?s:!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_NOT_FOUND,E.data=i,E}if(o===400){let g=se("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),v=se("Specified playback ID: {playbackId}",r).format({playbackId:f}),E=new X(g,d,s!=null?s:!0,v);return E.errorCategory=e,E.muxCode=oe.NETWORK_INVALID_URL,E.data=i,E}let p=new X("",d,s!=null?s:!0);return p.errorCategory=e,p.muxCode=oe.NETWORK_UNKNOWN_ERROR,p.data=i,p},g0=ke.DefaultConfig.capLevelController;g0||console.error("MinCapLevelController - hls.js DefaultConfig.capLevelController is unavailable");var wP={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function MP(i){let e=i.toLowerCase().trim();return wP[e]}var v0=class Sl extends g0{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?Sl.maxAutoResolution.set(e,t):Sl.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=Sl.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,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=MP(s);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(d=>d===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),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=Sl.minMaxResolution;return r>=n?t:g0.getMaxLevelByMediaSize(s,n*(16/9),n)}};v0.minMaxResolution=720,v0.maxAutoResolution=new WeakMap;var PP=v0,E0=PP,OP="com.apple.fps.1_0",NP="application/vnd.apple.mpegurl",UP=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new X(h,X.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=qe.DRM,f.muxCode=oe.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=FP(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(OP);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 X(h,X.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=qe.DRM,f.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(NP,h),m=async v=>{try{let E=v.message,b=await t(E);f.update(b)}catch(E){console.error("Error on FairPlay session message",E),s(i,E)}},p=v=>{let E=v.target.error;if(!E)return;console.error(`Internal Webkit Key Session Error - sysCode: ${E.systemCode} code: ${E.code}`);let b=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),T=new X(b,X.MEDIA_ERR_ENCRYPTED,!0);T.errorCategory=qe.DRM,T.muxCode=oe.ENCRYPTED_CDM_ERROR,s(i,T)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},FP=(i,e)=>{let t=$P(BP(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},BP=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function $P(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var HP=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,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}i.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 d(h,f)}catch(h){s(i,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=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new X(m,X.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=qe.DRM,p.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new X(p,X.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=qe.DRM,g.muxCode=oe.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let E=v.message,b=await t(E);try{await f.update(b)}catch{let T=se("Failed to update DRM license. This may be an issue with the player or your protected content."),_=new X(T,X.MEDIA_ERR_ENCRYPTED,!0);_.errorCategory=qe.DRM,_.muxCode=oe.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,_)}},p=()=>{let v=E=>{let b;if(E==="internal-error"){let T=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");b=new X(T,X.MEDIA_ERR_ENCRYPTED,!0),b.errorCategory=qe.DRM,b.muxCode=oe.ENCRYPTED_CDM_ERROR}else if(E==="output-restricted"||E==="output-downscaled"){let T=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");b=new X(T,X.MEDIA_ERR_ENCRYPTED,!1),b.errorCategory=qe.DRM,b.muxCode=oe.ENCRYPTED_OUTPUT_RESTRICTED}b&&s(i,b)};f.keyStatuses.forEach(E=>v(E))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let E=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),b=new X(E,X.MEDIA_ERR_ENCRYPTED,!0);return b.errorCategory=qe.DRM,b.muxCode=oe.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(b)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},GP=({hls:i,mediaEl:e,src:t,muxMediaState:s,saveAndDispatchError:r,maxRetries:n})=>{var a;let o,l=0,d=!1,u=!1,c=!1,h=()=>{o!=null&&(clearTimeout(o),o=void 0)},f=S=>(S==null?void 0:S.muxCode)===oe.NETWORK_RECONNECTING,m=()=>!e.paused&&e.readyState<HTMLMediaElement.HAVE_FUTURE_DATA,p=()=>{let S=s.get(e);if(f(S==null?void 0:S.error))return;let x=new X(se("Attempting to reconnect..."),X.MEDIA_ERR_NETWORK,!1);x.errorCategory=qe.VIDEO,x.muxCode=oe.NETWORK_RECONNECTING,S&&(S.error=x),e.dispatchEvent(new CustomEvent("error",{detail:x}))},g=()=>{if(!c&&t){i.loadSource(t);return}i.startLoad(e.currentTime)},v=()=>{d=!1,u=!0,h();let S=new X(se("Network error, try reloading."),X.MEDIA_ERR_NETWORK,!0);S.errorCategory=qe.VIDEO,S.reload=!0,r(e,S)},E=()=>{if(o!=null||d)return;if(l>=n){v();return}d=!0;let S=Math.min(1e3*2**l,3e4);o=setTimeout(()=>{o=void 0,l+=1,g()},S)},b=()=>{let S=s.get(e);!(S!=null&&S.networkError)||u||m()&&(p(),E())},T=()=>{let S=s.get(e);S&&(S.networkError=!0),d=!1,b()},_=()=>{let S=s.get(e);S!=null&&S.networkError&&(l=0,u=!1,h(),d=!0,g())};(a=globalThis.addEventListener)==null||a.call(globalThis,"online",_);let I=()=>{let S=s.get(e);S&&(!S.networkError&&!f(S.error)||(S.networkError=!1,d=!1,l=0,u=!1,h(),S.error&&(S.error=null,e.dispatchEvent(new Event("emptied")))))};return i.on(ke.Events.FRAG_BUFFERED,I),Tt(e,"playing",()=>{let S=s.get(e);S!=null&&S.networkError&&(d=!1,l=0,u=!1,h(),S.error&&(S.error=null))}),Tt(e,"waiting",b),e.addEventListener("teardown",()=>{var S;(S=globalThis.removeEventListener)==null||S.call(globalThis,"online",_),h()},{once:!0}),{handleHlsError:(S,x)=>{var k,R;if(S.type!==ke.ErrorTypes.NETWORK_ERROR)return!1;let D=(R=(k=S.response)==null?void 0:k.code)!=null?R:0;return(x.muxCode===oe.NETWORK_OFFLINE||D===0||D>=500)&&S.fatal?(T(),!0):!1},onManifestLoaded:()=>{c=!0,d=!1,h()}}},mc={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},KP=i=>{if(i.includes("fps"))return mc.FAIRPLAY;if(i.includes("playready"))return mc.PLAYREADY;if(i.includes("widevine"))return mc.WIDEVINE},VP=(i,e,t)=>{let s=lP(i);if(!s)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(h0(s)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let r;try{r=bc(s,e)}catch(n){return Promise.reject(n)}return fetch(r,{signal:t}).then(n=>n.status!==200?Promise.reject(n):n.text())},WP=i=>{let e=i.split(`
|
|
59
59
|
`).filter(s=>s.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let s of e){let r=YP(s),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},qP=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function YP(i){let e=[...i.matchAll(qP)];return Object.fromEntries(e.map(([,t,s])=>[t,s]))}var jP=i=>{var e,t,s;let r=i.split(`
|
|
60
|
-
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=J_(n),o=eA(n),l;if(a===He.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},zP=async(i,e,t)=>{if(e===zs.MP4)return{streamType:He.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0,playlistUrl:void 0};if(e===zs.M3U8){let s=await fetch(i,{signal:t});if(!s.ok)return Promise.reject(s);let r=await s.text(),n=s.url||i,a=await VP(r,n,t);return{...WP(r),...jP(a),playlistUrl:n}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0,playlistUrl:void 0}},QP=async(i,e,t=yc({src:i}),s=_c(e))=>{var r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u,playlistUrl:c}=await zP(i,t,s);if(s.aborted)return;let h=uA(u==null?void 0:u["com.apple.hls.chapters"],c!=null?c:i);h&&fA(h,e,s),((r=Ze.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Ze.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Ze.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},uA=(i,e)=>{var t;let s=(i==null?void 0:i.URI)||((t=i==null?void 0:i.VALUE)!=null&&t.toLocaleLowerCase().startsWith("http")?i.VALUE:void 0);if(s)try{return bc(s,e).toString()}catch{return}},_c=i=>{let e=new AbortController;return i.addEventListener("teardown",()=>e.abort(),{once:!0}),e.signal},cA=async(i,e)=>{try{let t=await fetch(i,{signal:e});if(!t.ok)throw new Error(`Failed to fetch ${i}: ${t.status} ${t.statusText}`);let s=await t.json();return e.aborted?void 0:s}catch(t){e.aborted||console.error(t);return}},hA=(i,e)=>{var t,s;if(!Array.isArray((t=i==null?void 0:i[0])==null?void 0:t.metadata))return;let r={};for(let a of i[0].metadata)a!=null&&a.key&&a!=null&&a.value&&(r[a.key]=a.value);((s=Ze.get(e))!=null?s:{}).metadata=r;let n=new CustomEvent("muxmetadata");e.dispatchEvent(n)},XP=async(i,e,t=_c(e))=>{let s=await cA(i,t);s!==void 0&&hA(s,e)},fA=async(i,e,t=_c(e))=>{let s=await cA(i,t);s!==void 0&&(hA(s,e),await xP(e,SP(s,nP(e)),t))},ZP=i=>{var e;let t=i.type,s=J_(t),r=eA(t),n,a=!!((e=i.partList)!=null&&e.length);return s===He.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},JP=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=ZP(i);if(c===He.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s: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=Ze.get(e))!=null?o:{}).seekable=p}((l=Ze.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Ze.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Ze.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},q_,Y_,mA=(Y_=(q_=globalThis==null?void 0:globalThis.navigator)==null?void 0:q_.userAgent)!=null?Y_:"",j_,z_,Q_,eO=(Q_=(z_=(j_=globalThis==null?void 0:globalThis.navigator)==null?void 0:j_.userAgentData)==null?void 0:z_.platform)!=null?Q_:"",tO=mA.toLowerCase().includes("android")||["x11","android"].some(i=>eO.toLowerCase().includes(i)),iO=i=>/^((?!chrome|android).)*safari/i.test(mA)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Ze=new WeakMap,Qs="mux.com",X_,Z_,pA=(Z_=(X_=ke).isSupported)==null?void 0:Z_.call(X_),sO=i=>tO||!iO(i),Ac=()=>{if(typeof window!="undefined")return ou.utils.now()},rO=ou.utils.generateUUID,Ll=({playbackId:i,customDomain:e=Qs,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Ec(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"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()},Sc=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Ic=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},nO=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:IA(i)&&(s=(t=Sc(i.playbackId))!=null?t:Ic(i.src))!=null?s:i.src},D0=i=>{var e;return(e=Ze.get(i))==null?void 0:e.error},gA=i=>{var e;return(e=Ze.get(i))==null?void 0:e.metadata},vc=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.streamType)!=null?t:He.UNKNOWN},vA=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Rc=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},EA=i=>{var e;let t=(e=Ze.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=Rc(i);return s.length?s.end(s.length-1)-t:Number.NaN},yA=i=>{var e;return(e=Ze.get(i))==null?void 0:e.coreReference},C0=.034,aO=(i,e,t=C0)=>Math.abs(i-e)<=t,bA=(i,e,t=C0)=>i>e||aO(i,e,t),oO=(i,e=C0)=>i.paused&&bA(i.currentTime,i.duration,e),TA=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.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(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},w0=(i,e)=>i.ended||i.loop?i.ended:e&&TA(i,e)?!0:oO(i),M0=(i,e,t)=>{P0(e,t,i);let{metadata:s={}}=i,{view_session_id:r=rO()}=s,n=nO(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Ze.get(e))==null?void 0:h.coreReference;M0(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Ze.set(e,{retryCount:0});let o=uO(i,e),l=EP(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?ke:void 0}):RA(i,e,o),vO(i,e,o),LP(e),kP(e);let d=vP(i,e,o);yP(i,e,o),bP(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Ze.get(e);return c&&(c.coreReference=u),u},lO=()=>{let i=new Date(0).toUTCString(),e=new Set(["muxData"]);document.cookie.split(";").forEach(t=>{let s=t.split("=")[0].trim();s.startsWith("muxData")&&e.add(s)}),e.forEach(t=>{document.cookie=`${t}=;expires=${i};path=/`})},l0=new WeakMap,dO=(i,e,t)=>{e&&(e.mux&&(e.mux.deleted||e.mux.destroy(),delete e.mux),!l0.has(e)&&l0.set(e,Promise.resolve().then(()=>{var s,r;l0.delete(e);let n=Ze.get(e);if(!n||e.mux&&!e.mux.deleted)return;let a=(r=(s=n.coreReference)!=null?s:t)==null?void 0:r.engine;RA(i,e,a)})))},_A=(i,e,t)=>{if(!e)return;let s=!!i.disableCookies,r=Ze.get(e);!r||r.muxDataDisableCookies===s||(dO(i,e,t),s&&Promise.resolve().then(()=>{i.disableCookies&&lO()}))},P0=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",xA),i.removeEventListener("error",y0),i.removeEventListener("durationchange",LA),Ze.delete(i),i.dispatchEvent(new Event("teardown")))};function AA(i,e){var t;let s=yc(i);if(s!==zs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===wi.MSE,o=n===wi.NATIVE,l=pA&&(a||sO(e));return r&&(o||!l)}var uO=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=yc(i)===zs.M3U8,c=AA(i,e);if(u&&!c&&pA){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=cO(s),m=hO(i),p=[Al.QUERY,Al.HEADER].includes(a)?{useHeaders:a===Al.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=gO(i,o),v=new ke({debug:t,startPosition:r,cmcd:p,xhrSetup:(b,E)=>{var T,_;if(a&&a!==Al.QUERY)return;let I=bc(E);if(!I.searchParams.has("CMCD"))return;let S=((_=(T=I.searchParams.get("CMCD"))==null?void 0:T.split(","))!=null?_:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");I.searchParams.set("CMCD",S),b.open("GET",I)},...h,...g,...f,...m,...o});return g.capLevelController===E0&&l!==void 0&&E0.setMaxAutoResolution(v,l),v.on(ke.Events.MANIFEST_LOADED,async function(b,E){var T;let _=uA((T=E.sessionData)==null?void 0:T["com.apple.hls.chapters"],E.url);_&&fA(_,e)}),v}},cO=i=>i===He.LIVE?{backBufferLength:8}:{},hO=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=Sc(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:pc(i,"fairplay"),serverCertificateUrl:SA(i,"fairplay")},"com.widevine.alpha":{licenseUrl:pc(i,"widevine")},"com.microsoft.playready":{licenseUrl:pc(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=KP(n);return s==null||s(l),o}))}},fO=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},mO=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},pO=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>fO(SA(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=gc(s,qe.DRM,i);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(s)}),getLicenseKey:s=>mO(s,pc(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=gc(r,qe.DRM,i);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:js,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,mc.FAIRPLAY)}};if(i.useWebkitFairplay)UP(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=HP(s)}},pc=({playbackId:i,tokens:{drm:e}={},customDomain:t=Qs},s)=>{let r=Sc(i);return`https://license.${t.toLocaleLowerCase().endsWith(Qs)?t:Qs}/license/${s}/${r}?token=${e}`},SA=({playbackId:i,tokens:{drm:e}={},customDomain:t=Qs},s)=>{let r=Sc(i);return`https://license.${t.toLocaleLowerCase().endsWith(Qs)?t:Qs}/appcert/${s}/${r}?token=${e}`},IA=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(Qs)||!!t&&r.includes(t.toLocaleLowerCase())},gO=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=E0,t.capLevelToPlayerSize=!0):t.capLevelController=El,t},RA=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=ou,muxDataSDKOptions:o={}}=i,l=IA(i),d=Ze.get(e);if(d&&(d.muxDataDisableCookies=!!i.disableCookies),!n&&(r||l)){let{playerInitTime:u,playerSoftwareName:c,playerSoftwareVersion:h,beaconCollectionDomain:f,debug:m,disableCookies:p}=i,g={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},v=b=>typeof b.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(b):b;a.monitor(e,{debug:m,beaconCollectionDomain:f,hlsjs:t,Hls:t?ke: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:u,...g}})}},vO=(i,e,t)=>{var s,r,n;let a=AA(i,e),{src:o,customDomain:l=Qs}=i,d=()=>{e.ended||i.disablePseudoEnded||!w0(e,t)||(TA(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},u,c,h=()=>{let f=Rc(e),m,p;f.length>0&&(m=f.start(0),p=f.end(0)),(c!==p||u!==m)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),u=m,c=p};if(Tt(e,"durationchange",h),e&&a){let f=yc(i);if(typeof o=="string"){if(o.endsWith(".mp4")&&o.includes(l)){let g=Ic(o),v=new URL(`https://stream.${l}/${g}/metadata.json`);XP(v.toString(),e)}let m=()=>{if(vc(e)!==He.LIVE||Number.isFinite(e.duration))return;let g=setInterval(h,1e3);e.addEventListener("teardown",()=>{clearInterval(g)},{once:!0}),Tt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(g)})},p=async()=>{let g=_c(e);return QP(o,e,f,g).then(()=>{g.aborted||m()}).catch(v=>{if(v instanceof Response){let b=gc(v,qe.VIDEO,i);if(b){js(e,b);return}}else v instanceof Error})};if(e.preload==="none"){let g=()=>{p(),e.removeEventListener("loadedmetadata",v)},v=()=>{p(),e.removeEventListener("play",g)};Tt(e,"play",g,{once:!0}),Tt(e,"loadedmetadata",v,{once:!0})}else p();(s=i.tokens)!=null&&s.drm?pO(i,e):Tt(e,"encrypted",()=>{let g=ne("Attempting to play DRM-protected content without providing a DRM token."),v=new X(g,X.MEDIA_ERR_ENCRYPTED,!0);v.errorCategory=qe.DRM,v.muxCode=oe.ENCRYPTED_MISSING_TOKEN,js(e,v)},{once:!0}),e.setAttribute("src",o),i.startTime&&(((r=Ze.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",LA,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",xA),e.addEventListener("error",y0),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(m=>{m.remove()})},{once:!0}),Tt(e,"pause",d),Tt(e,"seeked",d),Tt(e,"play",()=>{e.ended||bA(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else if(t&&o){t.once(ke.Events.LEVEL_LOADED,(p,g)=>{JP(g.details,e,t),h(),vc(e)===He.LIVE&&!Number.isFinite(e.duration)&&(t.on(ke.Events.LEVEL_UPDATED,h),Tt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(ke.Events.LEVELS_UPDATED,h)}))});let f=(n=i.maxReconnectRetries)!=null?n:0,m=f>0?GP({hls:t,mediaEl:e,src:o,muxMediaState:Ze,saveAndDispatchError:js,maxRetries:f}):void 0;t.on(ke.Events.ERROR,(p,g)=>{var v,b;let E=EO(g,i);if(E.muxCode===oe.NETWORK_NOT_READY){let T=(v=Ze.get(e))!=null?v:{},_=(b=T.retryCount)!=null?b:0;if(_<6){let I=_===0?5e3:6e4,S=new X(`Retrying in ${I/1e3} seconds...`,E.code,E.fatal);Object.assign(S,E),js(e,S);let x=setTimeout(()=>{T.retryCount=_+1,g.details==="manifestLoadError"&&g.url&&t.loadSource(g.url)},I);e.addEventListener("teardown",()=>clearTimeout(x),{once:!0});return}else{T.retryCount=0;let I=new X("Network error, try reloading.",E.code,E.fatal);Object.assign(I,E),I.reload=!0,js(e,I);return}}m!=null&&m.handleHlsError(g,E)||js(e,E)}),t.on(ke.Events.MANIFEST_LOADED,()=>{m==null||m.onManifestLoaded();let p=Ze.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",y0),Tt(e,"waiting",d),TP(i,t),IP(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 LA(i){var e;let t=i.target,s=(e=Ze.get(t))==null?void 0:e.startTime;if(s&&aP(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function xA(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new X(t,s);if(e.src&&s===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=D0(e))!=null?n:e.error;(a==null?void 0:a.code)===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&js(e,r)},500);return}if(e.src&&(s!==X.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}js(e,r)}function js(i,e){var t;e.fatal&&(((t=Ze.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function y0(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof X))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Ze.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var EO=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[ke.ErrorTypes.NETWORK_ERROR]:X.MEDIA_ERR_NETWORK,[ke.ErrorTypes.MEDIA_ERROR]:X.MEDIA_ERR_DECODE,[ke.ErrorTypes.KEY_SYSTEM_ERROR]:X.MEDIA_ERR_ENCRYPTED},a=u=>[ke.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,ke.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?X.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===ke.ErrorTypes.KEY_SYSTEM_ERROR)return qe.DRM;if(u.type===ke.ErrorTypes.NETWORK_ERROR)return qe.VIDEO},l,d=a(i);if(d===X.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:qe.VIDEO;l=(s=gc(i.response,u,e,i.fatal))!=null?s:new X("",d,i.fatal)}else if(d===X.MEDIA_ERR_ENCRYPTED)if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=ne("Attempting to play DRM-protected content without providing a DRM token.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_MISSING_TOKEN}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=ne("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=ne("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=ne("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=ne("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=ne("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_CDM_ERROR}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=ne("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_OUTPUT_RESTRICTED}else l=new X(i.error.message,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_ERROR;else l=new X("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
60
|
+
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=J_(n),o=eA(n),l;if(a===He.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},zP=async(i,e,t)=>{if(e===zs.MP4)return{streamType:He.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0,playlistUrl:void 0};if(e===zs.M3U8){let s=await fetch(i,{signal:t});if(!s.ok)return Promise.reject(s);let r=await s.text(),n=s.url||i,a=await VP(r,n,t);return{...WP(r),...jP(a),playlistUrl:n}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0,playlistUrl:void 0}},QP=async(i,e,t=yc({src:i}),s=_c(e))=>{var r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u,playlistUrl:c}=await zP(i,t,s);if(s.aborted)return;let h=uA(u==null?void 0:u["com.apple.hls.chapters"],c!=null?c:i);h&&fA(h,e,s),((r=Ze.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Ze.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Ze.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},uA=(i,e)=>{var t;let s=(i==null?void 0:i.URI)||((t=i==null?void 0:i.VALUE)!=null&&t.toLocaleLowerCase().startsWith("http")?i.VALUE:void 0);if(s)try{return bc(s,e).toString()}catch{return}},_c=i=>{let e=new AbortController;return i.addEventListener("teardown",()=>e.abort(),{once:!0}),e.signal},cA=async(i,e)=>{try{let t=await fetch(i,{signal:e});if(!t.ok)throw new Error(`Failed to fetch ${i}: ${t.status} ${t.statusText}`);let s=await t.json();return e.aborted?void 0:s}catch(t){e.aborted||console.error(t);return}},hA=(i,e)=>{var t,s;if(!Array.isArray((t=i==null?void 0:i[0])==null?void 0:t.metadata))return;let r={};for(let a of i[0].metadata)a!=null&&a.key&&a!=null&&a.value&&(r[a.key]=a.value);((s=Ze.get(e))!=null?s:{}).metadata=r;let n=new CustomEvent("muxmetadata");e.dispatchEvent(n)},XP=async(i,e,t=_c(e))=>{let s=await cA(i,t);s!==void 0&&hA(s,e)},fA=async(i,e,t=_c(e))=>{let s=await cA(i,t);s!==void 0&&(hA(s,e),await xP(e,SP(s,nP(e)),t))},ZP=i=>{var e;let t=i.type,s=J_(t),r=eA(t),n,a=!!((e=i.partList)!=null&&e.length);return s===He.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},JP=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=ZP(i);if(c===He.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s: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=Ze.get(e))!=null?o:{}).seekable=p}((l=Ze.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Ze.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Ze.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},q_,Y_,mA=(Y_=(q_=globalThis==null?void 0:globalThis.navigator)==null?void 0:q_.userAgent)!=null?Y_:"",j_,z_,Q_,eO=(Q_=(z_=(j_=globalThis==null?void 0:globalThis.navigator)==null?void 0:j_.userAgentData)==null?void 0:z_.platform)!=null?Q_:"",tO=mA.toLowerCase().includes("android")||["x11","android"].some(i=>eO.toLowerCase().includes(i)),iO=i=>/^((?!chrome|android).)*safari/i.test(mA)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Ze=new WeakMap,Qs="mux.com",X_,Z_,pA=(Z_=(X_=ke).isSupported)==null?void 0:Z_.call(X_),sO=i=>tO||!iO(i),Ac=()=>{if(typeof window!="undefined")return ou.utils.now()},rO=ou.utils.generateUUID,Ll=({playbackId:i,customDomain:e=Qs,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Ec(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"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()},Sc=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Ic=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},nO=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:IA(i)&&(s=(t=Sc(i.playbackId))!=null?t:Ic(i.src))!=null?s:i.src},D0=i=>{var e;return(e=Ze.get(i))==null?void 0:e.error},gA=i=>{var e;return(e=Ze.get(i))==null?void 0:e.metadata},vc=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.streamType)!=null?t:He.UNKNOWN},vA=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Rc=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},EA=i=>{var e;let t=(e=Ze.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=Rc(i);return s.length?s.end(s.length-1)-t:Number.NaN},yA=i=>{var e;return(e=Ze.get(i))==null?void 0:e.coreReference},C0=.034,aO=(i,e,t=C0)=>Math.abs(i-e)<=t,bA=(i,e,t=C0)=>i>e||aO(i,e,t),oO=(i,e=C0)=>i.paused&&bA(i.currentTime,i.duration,e),TA=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.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(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},w0=(i,e)=>i.ended||i.loop?i.ended:e&&TA(i,e)?!0:oO(i),M0=(i,e,t)=>{P0(e,t,i);let{metadata:s={}}=i,{view_session_id:r=rO()}=s,n=nO(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Ze.get(e))==null?void 0:h.coreReference;M0(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Ze.set(e,{retryCount:0});let o=uO(i,e),l=EP(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?ke:void 0}):RA(i,e,o),vO(i,e,o),LP(e),kP(e);let d=vP(i,e,o);yP(i,e,o),bP(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Ze.get(e);return c&&(c.coreReference=u),u},lO=()=>{let i=new Date(0).toUTCString(),e=new Set(["muxData"]);document.cookie.split(";").forEach(t=>{let s=t.split("=")[0].trim();s.startsWith("muxData")&&e.add(s)}),e.forEach(t=>{document.cookie=`${t}=;expires=${i};path=/`})},l0=new WeakMap,dO=(i,e,t)=>{e&&(e.mux&&(e.mux.deleted||e.mux.destroy(),delete e.mux),!l0.has(e)&&l0.set(e,Promise.resolve().then(()=>{var s,r;l0.delete(e);let n=Ze.get(e);if(!n||e.mux&&!e.mux.deleted)return;let a=(r=(s=n.coreReference)!=null?s:t)==null?void 0:r.engine;RA(i,e,a)})))},_A=(i,e,t)=>{if(!e)return;let s=!!i.disableCookies,r=Ze.get(e);!r||r.muxDataDisableCookies===s||(dO(i,e,t),s&&Promise.resolve().then(()=>{i.disableCookies&&lO()}))},P0=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",xA),i.removeEventListener("error",y0),i.removeEventListener("durationchange",LA),Ze.delete(i),i.dispatchEvent(new Event("teardown")))};function AA(i,e){var t;let s=yc(i);if(s!==zs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===wi.MSE,o=n===wi.NATIVE,l=pA&&(a||sO(e));return r&&(o||!l)}var uO=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=yc(i)===zs.M3U8,c=AA(i,e);if(u&&!c&&pA){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=cO(s),m=hO(i),p=[Al.QUERY,Al.HEADER].includes(a)?{useHeaders:a===Al.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=gO(i,o),v=new ke({debug:t,startPosition:r,cmcd:p,xhrSetup:(E,b)=>{var T,_;if(a&&a!==Al.QUERY)return;let I=bc(b);if(!I.searchParams.has("CMCD"))return;let S=((_=(T=I.searchParams.get("CMCD"))==null?void 0:T.split(","))!=null?_:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");I.searchParams.set("CMCD",S),E.open("GET",I)},...h,...g,...f,...m,...o});return g.capLevelController===E0&&l!==void 0&&E0.setMaxAutoResolution(v,l),v.on(ke.Events.MANIFEST_LOADED,async function(E,b){var T;let _=uA((T=b.sessionData)==null?void 0:T["com.apple.hls.chapters"],b.url);_&&fA(_,e)}),v}},cO=i=>i===He.LIVE?{backBufferLength:8}:{},hO=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=Sc(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:pc(i,"fairplay"),serverCertificateUrl:SA(i,"fairplay")},"com.widevine.alpha":{licenseUrl:pc(i,"widevine")},"com.microsoft.playready":{licenseUrl:pc(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=KP(n);return s==null||s(l),o}))}},fO=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},mO=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},pO=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>fO(SA(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=gc(s,qe.DRM,i);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(s)}),getLicenseKey:s=>mO(s,pc(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=gc(r,qe.DRM,i);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:js,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,mc.FAIRPLAY)}};if(i.useWebkitFairplay)UP(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=HP(s)}},pc=({playbackId:i,tokens:{drm:e}={},customDomain:t=Qs},s)=>{let r=Sc(i);return`https://license.${t.toLocaleLowerCase().endsWith(Qs)?t:Qs}/license/${s}/${r}?token=${e}`},SA=({playbackId:i,tokens:{drm:e}={},customDomain:t=Qs},s)=>{let r=Sc(i);return`https://license.${t.toLocaleLowerCase().endsWith(Qs)?t:Qs}/appcert/${s}/${r}?token=${e}`},IA=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(Qs)||!!t&&r.includes(t.toLocaleLowerCase())},gO=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=E0,t.capLevelToPlayerSize=!0):t.capLevelController=El,t},RA=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=ou,muxDataSDKOptions:o={}}=i,l=IA(i),d=Ze.get(e);if(d&&(d.muxDataDisableCookies=!!i.disableCookies),!n&&(r||l)){let{playerInitTime:u,playerSoftwareName:c,playerSoftwareVersion:h,beaconCollectionDomain:f,debug:m,disableCookies:p}=i,g={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},v=E=>typeof E.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(E):E;a.monitor(e,{debug:m,beaconCollectionDomain:f,hlsjs:t,Hls:t?ke: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:u,...g}})}},vO=(i,e,t)=>{var s,r,n;let a=AA(i,e),{src:o,customDomain:l=Qs}=i,d=()=>{e.ended||i.disablePseudoEnded||!w0(e,t)||(TA(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},u,c,h=()=>{let f=Rc(e),m,p;f.length>0&&(m=f.start(0),p=f.end(0)),(c!==p||u!==m)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),u=m,c=p};if(Tt(e,"durationchange",h),e&&a){let f=yc(i);if(typeof o=="string"){if(o.endsWith(".mp4")&&o.includes(l)){let g=Ic(o),v=new URL(`https://stream.${l}/${g}/metadata.json`);XP(v.toString(),e)}let m=()=>{if(vc(e)!==He.LIVE||Number.isFinite(e.duration))return;let g=setInterval(h,1e3);e.addEventListener("teardown",()=>{clearInterval(g)},{once:!0}),Tt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(g)})},p=async()=>{let g=_c(e);return QP(o,e,f,g).then(()=>{g.aborted||m()}).catch(v=>{if(v instanceof Response){let E=gc(v,qe.VIDEO,i);if(E){js(e,E);return}}else v instanceof Error})};if(e.preload==="none"){let g=()=>{p(),e.removeEventListener("loadedmetadata",v)},v=()=>{p(),e.removeEventListener("play",g)};Tt(e,"play",g,{once:!0}),Tt(e,"loadedmetadata",v,{once:!0})}else p();(s=i.tokens)!=null&&s.drm?pO(i,e):Tt(e,"encrypted",()=>{let g=se("Attempting to play DRM-protected content without providing a DRM token."),v=new X(g,X.MEDIA_ERR_ENCRYPTED,!0);v.errorCategory=qe.DRM,v.muxCode=oe.ENCRYPTED_MISSING_TOKEN,js(e,v)},{once:!0}),e.setAttribute("src",o),i.startTime&&(((r=Ze.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",LA,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",xA),e.addEventListener("error",y0),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(m=>{m.remove()})},{once:!0}),Tt(e,"pause",d),Tt(e,"seeked",d),Tt(e,"play",()=>{e.ended||bA(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else if(t&&o){t.once(ke.Events.LEVEL_LOADED,(p,g)=>{JP(g.details,e,t),h(),vc(e)===He.LIVE&&!Number.isFinite(e.duration)&&(t.on(ke.Events.LEVEL_UPDATED,h),Tt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(ke.Events.LEVELS_UPDATED,h)}))});let f=(n=i.maxReconnectRetries)!=null?n:0,m=f>0?GP({hls:t,mediaEl:e,src:o,muxMediaState:Ze,saveAndDispatchError:js,maxRetries:f}):void 0;t.on(ke.Events.ERROR,(p,g)=>{var v,E;let b=EO(g,i);if(b.muxCode===oe.NETWORK_NOT_READY){let T=(v=Ze.get(e))!=null?v:{},_=(E=T.retryCount)!=null?E:0;if(_<6){let I=_===0?5e3:6e4,S=new X(`Retrying in ${I/1e3} seconds...`,b.code,b.fatal);Object.assign(S,b),js(e,S);let x=setTimeout(()=>{T.retryCount=_+1,g.details==="manifestLoadError"&&g.url&&t.loadSource(g.url)},I);e.addEventListener("teardown",()=>clearTimeout(x),{once:!0});return}else{T.retryCount=0;let I=new X("Network error, try reloading.",b.code,b.fatal);Object.assign(I,b),I.reload=!0,js(e,I);return}}m!=null&&m.handleHlsError(g,b)||js(e,b)}),t.on(ke.Events.MANIFEST_LOADED,()=>{m==null||m.onManifestLoaded();let p=Ze.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",y0),Tt(e,"waiting",d),TP(i,t),IP(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 LA(i){var e;let t=i.target,s=(e=Ze.get(t))==null?void 0:e.startTime;if(s&&aP(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function xA(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new X(t,s);if(e.src&&s===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=D0(e))!=null?n:e.error;(a==null?void 0:a.code)===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&js(e,r)},500);return}if(e.src&&(s!==X.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}js(e,r)}function js(i,e){var t;e.fatal&&(((t=Ze.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function y0(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof X))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Ze.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var EO=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[ke.ErrorTypes.NETWORK_ERROR]:X.MEDIA_ERR_NETWORK,[ke.ErrorTypes.MEDIA_ERROR]:X.MEDIA_ERR_DECODE,[ke.ErrorTypes.KEY_SYSTEM_ERROR]:X.MEDIA_ERR_ENCRYPTED},a=u=>[ke.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,ke.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?X.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===ke.ErrorTypes.KEY_SYSTEM_ERROR)return qe.DRM;if(u.type===ke.ErrorTypes.NETWORK_ERROR)return qe.VIDEO},l,d=a(i);if(d===X.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:qe.VIDEO;l=(s=gc(i.response,u,e,i.fatal))!=null?s:new X("",d,i.fatal)}else if(d===X.MEDIA_ERR_ENCRYPTED)if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=se("Attempting to play DRM-protected content without providing a DRM token.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_MISSING_TOKEN}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=se("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_CDM_ERROR}else if(i.details===ke.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_OUTPUT_RESTRICTED}else l=new X(i.error.message,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=qe.DRM,l.muxCode=oe.ENCRYPTED_ERROR;else l=new X("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
61
61
|
`:""}${i.response&&(i.response.code||i.response.text)?`response: ${i.response.code}, ${i.response.text}
|
|
62
62
|
`:""}${i.reason?`failure reason: ${i.reason}
|
|
63
63
|
`:""}${i.level?`level: ${i.level}
|
|
@@ -140,7 +140,7 @@ Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
140
140
|
`}get preferCmcd(){var i;return(i=this.getAttribute(C.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?_a.includes(i)?this.setAttribute(C.PREFER_CMCD,i):console.warn(`Invalid value for preferCmcd. Must be one of ${_a.join()}`):this.removeAttribute(C.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?+this.getAttribute(C.PLAYER_INIT_TIME):St(this,xc)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=St(this,wc))!=null?i:$A}set playerSoftwareName(i){zi(this,wc,i)}get playerSoftwareVersion(){var i;return(i=St(this,Cc))!=null?i:BA}set playerSoftwareVersion(i){zi(this,Cc,i)}get _hls(){var i;return(i=St(this,Ii,kr))==null?void 0:i.engine}get mux(){var i;return(i=this.nativeEl)==null?void 0:i.mux}get error(){var i;return(i=D0(this.nativeEl))!=null?i:null}get errorTranslator(){return St(this,Mc)}set errorTranslator(i){zi(this,Mc,i)}get src(){return this.getAttribute("src")}set src(i){i!==this.src&&(i==null?this.removeAttribute("src"):this.setAttribute("src",i))}get type(){var i;return(i=this.getAttribute(C.TYPE))!=null?i:void 0}set type(i){i!==this.type&&(i?this.setAttribute(C.TYPE,i):this.removeAttribute(C.TYPE))}get preload(){let i=this.getAttribute("preload");return i===""?"auto":["none","metadata","auto"].includes(i)?i:super.preload}set preload(i){i!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(i)?this.setAttribute("preload",i):this.removeAttribute("preload"))}get debug(){return this.getAttribute(C.DEBUG)!=null}set debug(i){i!==this.debug&&(i?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG))}get disableTracking(){return this.hasAttribute(C.DISABLE_TRACKING)}set disableTracking(i){i!==this.disableTracking&&this.toggleAttribute(C.DISABLE_TRACKING,!!i)}get disableCookies(){return this.hasAttribute(C.DISABLE_COOKIES)}set disableCookies(i){i!==this.disableCookies&&(i?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(C.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(i){i!==this.disablePseudoEnded&&(i?this.setAttribute(C.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(C.DISABLE_PSEUDO_ENDED))}get maxReconnectRetries(){let i=this.getAttribute(C.MAX_RECONNECT_RETRIES);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set maxReconnectRetries(i){i!==this.maxReconnectRetries&&(i==null?this.removeAttribute(C.MAX_RECONNECT_RETRIES):this.setAttribute(C.MAX_RECONNECT_RETRIES,`${i}`))}get startTime(){let i=this.getAttribute(C.START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set startTime(i){i!==this.startTime&&(i==null?this.removeAttribute(C.START_TIME):this.setAttribute(C.START_TIME,`${i}`))}get initialBandwidthEstimateKbps(){let i=this.getAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialBandwidthEstimateKbps(i){i!==this.initialBandwidthEstimateKbps&&(i==null?this.removeAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`))}get initialEstimateSegments(){let i=this.getAttribute(C.INITIAL_ESTIMATE_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialEstimateSegments(i){i!==this.initialEstimateSegments&&(i==null?this.removeAttribute(C.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(C.INITIAL_ESTIMATE_SEGMENTS,`${i}`))}get minPreloadSegments(){let i=this.getAttribute(C.MIN_PRELOAD_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set minPreloadSegments(i){i!==this.minPreloadSegments&&(i==null?this.removeAttribute(C.MIN_PRELOAD_SEGMENTS):this.setAttribute(C.MIN_PRELOAD_SEGMENTS,`${i}`))}get playbackId(){var i;return this.hasAttribute(C.PLAYBACK_ID)?this.getAttribute(C.PLAYBACK_ID):(i=Ic(this.src))!=null?i:void 0}set playbackId(i){i!==this.playbackId&&(i?this.setAttribute(C.PLAYBACK_ID,i):this.removeAttribute(C.PLAYBACK_ID))}get maxResolution(){var i;return(i=this.getAttribute(C.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(C.MAX_RESOLUTION,i):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(C.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(C.MIN_RESOLUTION,i):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(C.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(C.RENDITION_ORDER,i):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){let i=this.getAttribute(C.PROGRAM_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programStartTime(i){i==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${i}`)}get programEndTime(){let i=this.getAttribute(C.PROGRAM_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programEndTime(i){i==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){let i=this.getAttribute(C.ASSET_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetStartTime(i){i==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${i}`)}get assetEndTime(){let i=this.getAttribute(C.ASSET_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetEndTime(i){i==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${i}`)}get customDomain(){var i;return(i=this.getAttribute(C.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(C.CUSTOM_DOMAIN,i):this.removeAttribute(C.CUSTOM_DOMAIN))}get capRenditionToPlayerSize(){var i;return((i=this._hlsConfig)==null?void 0:i.capLevelToPlayerSize)!=null?this._hlsConfig.capLevelToPlayerSize:St(this,Oc)}set capRenditionToPlayerSize(i){zi(this,Oc,i)}get drmToken(){var i;return(i=this.getAttribute(C.DRM_TOKEN))!=null?i:void 0}set drmToken(i){i!==this.drmToken&&(i?this.setAttribute(C.DRM_TOKEN,i):this.removeAttribute(C.DRM_TOKEN))}get playbackToken(){var i,e,t,s;if(this.hasAttribute(C.PLAYBACK_TOKEN))return(i=this.getAttribute(C.PLAYBACK_TOKEN))!=null?i:void 0;if(this.hasAttribute(C.PLAYBACK_ID)){let[,r]=Ec((e=this.playbackId)!=null?e:"");return(t=new URLSearchParams(r).get("token"))!=null?t:void 0}if(this.src)return(s=new URLSearchParams(this.src).get("token"))!=null?s:void 0}set playbackToken(i){i!==this.playbackToken&&(i?this.setAttribute(C.PLAYBACK_TOKEN,i):this.removeAttribute(C.PLAYBACK_TOKEN))}get tokens(){let i=this.getAttribute(C.PLAYBACK_TOKEN),e=this.getAttribute(C.DRM_TOKEN);return{...St(this,kc),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{}}}set tokens(i){zi(this,kc,i!=null?i:{})}get ended(){return w0(this.nativeEl,this._hls)}get envKey(){var i;return(i=this.getAttribute(C.ENV_KEY))!=null?i:void 0}set envKey(i){i!==this.envKey&&(i?this.setAttribute(C.ENV_KEY,i):this.removeAttribute(C.ENV_KEY))}get beaconCollectionDomain(){var i;return(i=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get streamType(){var i;return(i=this.getAttribute(C.STREAM_TYPE))!=null?i:vc(this.nativeEl)}set streamType(i){i!==this.streamType&&(i?this.setAttribute(C.STREAM_TYPE,i):this.removeAttribute(C.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(C.TARGET_LIVE_WINDOW)?+this.getAttribute(C.TARGET_LIVE_WINDOW):vA(this.nativeEl)}set targetLiveWindow(i){i!=this.targetLiveWindow&&(i==null?this.removeAttribute(C.TARGET_LIVE_WINDOW):this.setAttribute(C.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i,e;if(this.hasAttribute(C.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:t}=this,s=(i=this.nativeEl.seekable.end(0))!=null?i:0,r=(e=this.nativeEl.seekable.start(0))!=null?e:0;return Math.max(r,s-t)}return EA(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(C.LIVE_EDGE_OFFSET))return+this.getAttribute(C.LIVE_EDGE_OFFSET)}set liveEdgeOffset(i){i!=this.liveEdgeOffset&&(i==null?this.removeAttribute(C.LIVE_EDGE_OFFSET):this.setAttribute(C.LIVE_EDGE_OFFSET,`${+i}`))}get seekable(){return Rc(this.nativeEl)}async addCuePoints(i){return this.nativeEl.currentSrc||console.warn("addCuePoints() was called before the media element has loaded. Wait for the loadstart event before calling addCuePoints()."),S0(this.nativeEl,i)}get activeCuePoint(){return I0(this.nativeEl)}get cuePoints(){return nA(this.nativeEl)}async addChapters(i){return this.nativeEl.currentSrc||console.warn("addChapters() was called before the media element has loaded. Wait for the loadstart event before calling addChapters()."),x0(this.nativeEl,i)}get activeChapter(){return k0(this.nativeEl)}get chapters(){return oA(this.nativeEl)}getStartDate(){return lA(this.nativeEl,this._hls)}get currentPdt(){return dA(this.nativeEl,this._hls)}get preferPlayback(){let i=this.getAttribute(C.PREFER_PLAYBACK);if(i===wi.MSE||i===wi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===wi.MSE||i===wi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,i):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(i=>i.startsWith("metadata-")&&![C.METADATA_URL].includes(i)).reduce((i,e)=>{let t=this.getAttribute(e);return t!=null&&(i[e.replace(/^metadata-/,"").replace(/-/g,"_")]=t),i},{}),...St(this,Dl)}}set metadata(i){zi(this,Dl,i!=null?i:{}),this.mux&&this.mux.emit("hb",St(this,Dl))}get _hlsConfig(){return St(this,Dc)}set _hlsConfig(i){zi(this,Dc,i)}get logo(){var i;return(i=this.getAttribute(C.LOGO))!=null?i:St(this,Cl)}set logo(i){i?this.setAttribute(C.LOGO,i):this.removeAttribute(C.LOGO)}load(){M0(this,this.nativeEl,St(this,Ii,kr))}unload(){P0(this.nativeEl,St(this,Ii,kr),this)}attributeChangedCallback(i,e,t){var s,r;switch(xl.observedAttributes.includes(i)&&!["src","autoplay","preload"].includes(i)&&super.attributeChangedCallback(i,e,t),i){case C.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=t!=null?t:void 0;break;case C.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=t!=null?t:void 0;break;case"src":{let n=!!e,a=!!t;!n&&a?Lc(this,Ii,wl).call(this):n&&!a?this.unload():n&&a&&(this.unload(),Lc(this,Ii,wl).call(this));break}case"autoplay":if(t===e)break;(s=St(this,Ii,kr))==null||s.setAutoplay(this.autoplay);break;case"preload":if(t===e)break;(r=St(this,Ii,kr))==null||r.setPreload(t);break;case C.PLAYBACK_ID:case C.CUSTOM_DOMAIN:case C.MAX_RESOLUTION:case C.MIN_RESOLUTION:case C.RENDITION_ORDER:case C.PROGRAM_START_TIME:case C.PROGRAM_END_TIME:case C.ASSET_START_TIME:case C.ASSET_END_TIME:case C.PLAYBACK_TOKEN:this.hasAttribute(C.PLAYBACK_ID)&&(this.src=Ll(this));break;case C.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 C.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 C.STREAM_TYPE:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case C.TARGET_LIVE_WINDOW:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case C.LOGO:(t==null||t!==e)&&this.updateLogo();break;case C.DISABLE_TRACKING:{if(t==null||t!==e){let n=this.currentTime,a=this.paused;this.unload(),Lc(this,Ii,wl).call(this).then(()=>{this.currentTime=n,a||this.play()})}break}case C.DISABLE_COOKIES:{(t==null||t!==e)&&_A(this,this.nativeEl,St(this,Ii,kr));break}case C.CAP_RENDITION_TO_PLAYER_SIZE:(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0)}}updateLogo(){if(!this.shadowRoot)return;let i=this.shadowRoot.querySelector('slot[name="logo"]');if(!i)return;let e=this.constructor.getLogoHTML(St(this,Cl)||this.logo);i.innerHTML=e}connectedCallback(){var i,e;(i=super.connectedCallback)==null||i.call(this),(e=this.nativeEl)==null||e.addEventListener("muxmetadata",St(this,Pc)),this.nativeEl&&this.src&&!St(this,Ii,kr)&&Lc(this,Ii,wl).call(this)}disconnectedCallback(){var i,e;(i=this.nativeEl)==null||i.removeEventListener("muxmetadata",St(this,Pc)),this.unload(),(e=super.disconnectedCallback)==null||e.call(this)}handleEvent(i){i.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(i.type,{composed:!0,detail:i.detail}))}};kl=new WeakMap,xc=new WeakMap,Dl=new WeakMap,kc=new WeakMap,Dc=new WeakMap,Cc=new WeakMap,wc=new WeakMap,Mc=new WeakMap,Cl=new WeakMap,Pc=new WeakMap,Ii=new WeakSet,kr=function(){return yA(this.nativeEl)},Oc=new WeakMap,wl=async function(){St(this,kl)||(await zi(this,kl,Promise.resolve()),zi(this,kl,null),this.load())};var vs=new WeakMap,Aa=class extends Error{},Nc=class extends Error{};var xO=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],WA=globalThis.WeakRef?class extends Set{add(i){super.add(new WeakRef(i))}forEach(i){super.forEach(e=>{let t=e.deref();t&&i(t)})}}:Set;function qA(i){var e,t,s;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(s=globalThis.cast)!=null&&s.framework?i():customElements.whenDefined("google-cast-button").then(i):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(i)}}function YA(){return globalThis.chrome}function jA(){var t;let i="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${i}"]`))return;let e=document.createElement("script");e.src=i,document.head.append(e)}function Xs(){var i,e;return(e=(i=globalThis.cast)==null?void 0:i.framework)==null?void 0:e.CastContext.getInstance()}function Ml(){var i;return(i=Xs())==null?void 0:i.getCurrentSession()}function Uc(){var i;return(i=Ml())==null?void 0:i.getSessionObj().media[0]}function zA(i){return new Promise((e,t)=>{Uc().editTracksInfo(i,e,t)})}function QA(i){return new Promise((e,t)=>{Uc().getStatus(i,e,t)})}function B0(i){return Xs().setOptions({...$0(),...i})}function $0(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function KA(i){if(!i)return;let e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=i.match(e);return t?t[1]:null}function kO(i){for(let e of i.split(`
|
|
141
141
|
`)){let t=e.trim();if(t.startsWith("#EXT-X-MEDIA")&&/TYPE=AUDIO/i.test(t)){let s=t.match(/URI="([^"]+)"/i);if(s)return s[1]}}}function DO(i){let e=i.split(`
|
|
142
142
|
`),t=[];for(let s=0;s<e.length;s++)if(e[s].trim().startsWith("#EXT-X-STREAM-INF")){let n=e[s+1]?e[s+1].trim():"";n&&!n.startsWith("#")&&t.push(n)}return t}function VA(i){let t=i.split(`
|
|
143
|
-
`).find(s=>!s.trim().startsWith("#")&&s.trim()!=="");return t==null?void 0:t.trim()}async function XA(i){if(!i)return!1;if(/\.m3u8?(\?.*)?$/i.test(i))return!0;if(i.startsWith("blob:"))return!1;try{let t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return xO.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function ZA(i){var e;if(!i||i.startsWith("blob:"))return{videoFormat:void 0,audioFormat:void 0};try{let t=await(await fetch(i)).text(),s=t,r=DO(t);if(r.length>0){let d=new URL(r[0],i).toString();s=await(await fetch(d)).text()}let n=VA(s),a=KA(n),o=kO(t),l=a;if(o)try{let d=new URL(o,i).toString(),u=await(await fetch(d)).text(),c=VA(u);l=(e=KA(c))!=null?e:a}catch(d){console.error("Error while trying to parse the audio rendition playlist",d)}return{videoFormat:a,audioFormat:l}}catch(t){return console.error("Error while trying to parse the manifest playlist",t),{videoFormat:void 0,audioFormat:void 0}}}var Fc=new WA,Zs=new WeakSet,Nt;qA(()=>{var i,e,t,s;if(!((e=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(s=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:s.isAvailable);return}Nt||(Nt=cast.framework,Xs().addEventListener(Nt.CastContextEventType.CAST_STATE_CHANGED,r=>{Fc.forEach(n=>{var a,o;return(o=(a=vs.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),Xs().addEventListener(Nt.CastContextEventType.SESSION_STATE_CHANGED,r=>{Fc.forEach(n=>{var a,o;return(o=(a=vs.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),Fc.forEach(r=>{var n,a;return(a=(n=vs.get(r)).init)==null?void 0:a.call(n)}))});var JA=0,Be,Sa,ri,Qi,In,Rn,Dr,$c,Pl,ot,Sn,eS,tS,H0,iS,G0,sS,K0,Bc=class extends EventTarget{constructor(t){super();fe(this,ot);fe(this,Be);fe(this,Sa);fe(this,ri);fe(this,Qi);fe(this,In,"disconnected");fe(this,Rn,!1);fe(this,Dr,new Set);fe(this,$c,new WeakMap);fe(this,Pl,()=>ze(this,ot,K0).call(this));le(this,Be,t),Fc.add(this),vs.set(this,{init:()=>ze(this,ot,G0).call(this),onCastStateChanged:()=>ze(this,ot,H0).call(this),onSessionStateChanged:()=>ze(this,ot,iS).call(this),getCastPlayer:()=>M(this,ot,Sn)}),ze(this,ot,G0).call(this)}destroy(){var t,s,r;(s=(t=M(this,Be))==null?void 0:t.textTracks)==null||s.removeEventListener("change",M(this,Pl)),M(this,Qi)&&((r=M(this,ri))!=null&&r.controller)&&Object.entries(M(this,Qi)).forEach(([n,a])=>{M(this,ri).controller.removeEventListener(n,a)}),M(this,Be)&&Zs.delete(M(this,Be)),le(this,Sa,!1)}get state(){return M(this,In)}async watchAvailability(t){if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");return M(this,$c).set(t,++JA),M(this,Dr).add(t),queueMicrotask(()=>t(ze(this,ot,tS).call(this))),JA}async cancelWatchAvailability(t){if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");t?M(this,Dr).delete(t):M(this,Dr).clear()}async prompt(){var s,r,n,a;if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");if(!((r=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&r.isAvailable))throw new Nc("The RemotePlayback API is disabled on this platform.");let t=Zs.has(M(this,Be));Zs.add(M(this,Be)),B0(M(this,Be).castOptions),Object.entries(M(this,Qi)).forEach(([o,l])=>{M(this,ri).controller.addEventListener(o,l)});try{await Xs().requestSession()}catch(o){if(t||Zs.delete(M(this,Be)),o==="cancel")return;throw new Error(o)}(a=(n=vs.get(M(this,Be)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};Be=new WeakMap,Sa=new WeakMap,ri=new WeakMap,Qi=new WeakMap,In=new WeakMap,Rn=new WeakMap,Dr=new WeakMap,$c=new WeakMap,Pl=new WeakMap,ot=new WeakSet,Sn=function(){if(Zs.has(M(this,Be)))return M(this,ri)},eS=function(){Zs.has(M(this,Be))&&(Object.entries(M(this,Qi)).forEach(([t,s])=>{M(this,ri).controller.removeEventListener(t,s)}),Zs.delete(M(this,Be)),M(this,Be).muted=M(this,ri).isMuted,M(this,Be).currentTime=M(this,ri).savedPlayerState.currentTime,M(this,ri).savedPlayerState.isPaused===!1&&M(this,Be).play())},tS=function(){var s;let t=(s=Xs())==null?void 0:s.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},H0=function(){let t=Xs().getCastState();if(Zs.has(M(this,Be))&&t==="CONNECTING"&&(le(this,In,"connecting"),this.dispatchEvent(new Event("connecting"))),!M(this,Rn)&&(t!=null&&t.includes("CONNECT"))){le(this,Rn,!0);for(let s of M(this,Dr))s(!0)}else if(M(this,Rn)&&(!t||t==="NO_DEVICES_AVAILABLE")){le(this,Rn,!1);for(let s of M(this,Dr))s(!1)}},iS=async function(){var s;let{SESSION_RESUMED:t}=Nt.SessionState;if(Xs().getSessionState()===t&&M(this,Be).castSrc===((s=Uc())==null?void 0:s.media.contentId)){Zs.add(M(this,Be)),Object.entries(M(this,Qi)).forEach(([r,n])=>{M(this,ri).controller.addEventListener(r,n)});try{await QA(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}M(this,Qi)[Nt.RemotePlayerEventType.IS_PAUSED_CHANGED](),M(this,Qi)[Nt.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},G0=function(){!Nt||M(this,Sa)||(le(this,Sa,!0),B0(M(this,Be).castOptions),M(this,Be).textTracks.addEventListener("change",M(this,Pl)),ze(this,ot,H0).call(this),le(this,ri,new Nt.RemotePlayer),new Nt.RemotePlayerController(M(this,ri)),le(this,Qi,{[Nt.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(le(this,In,"connected"),this.dispatchEvent(new Event("connect"))):(ze(this,ot,eS).call(this),le(this,In,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[Nt.RemotePlayerEventType.DURATION_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("durationchange"))},[Nt.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("volumechange"))},[Nt.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("volumechange"))},[Nt.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=M(this,ot,Sn))!=null&&t.isMediaLoaded&&M(this,Be).dispatchEvent(new Event("timeupdate"))},[Nt.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("resize"))},[Nt.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event(this.paused?"pause":"play"))},[Nt.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,s;((t=M(this,ot,Sn))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&M(this,Be).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(s=M(this,ot,Sn))==null?void 0:s.playerState]))},[Nt.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=M(this,ot,Sn))!=null&&t.isMediaLoaded&&(await Promise.resolve(),ze(this,ot,sS).call(this))}}))},sS=function(){ze(this,ot,K0).call(this)},K0=async function(){var h,f,m,p,g;if(!M(this,ot,Sn))return;let s=((f=(h=M(this,ri).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...M(this,Be).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=s.map(({language:v,name:b,trackId:E})=>{var _;let{mode:T}=(_=r.find(I=>I.language===v&&I.label===b))!=null?_:{};return T?{mode:T,trackId:E}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),d=(g=(p=(m=Ml())==null?void 0:m.getSessionObj().media[0])==null?void 0:p.activeTrackIds)!=null?g:[],u=d;if(d.length&&(u=u.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(u=[...u,l.trackId]),u=[...new Set(u)],!((v,b)=>v.length===b.length&&v.every(E=>b.includes(E)))(d,u))try{let v=new chrome.cast.media.EditTracksInfoRequest(u);await zA(v)}catch(v){console.error(v)}};var rS=i=>{var e,t,s,r,n,a,o,Ge,nS;return t=class extends i{constructor(){super(...arguments);fe(this,o);fe(this,s,{paused:!1});fe(this,r,$0());fe(this,n);fe(this,a)}get remote(){return M(this,a)?M(this,a):YA()?this.isConnected?(this.disableRemotePlayback||jA(),vs.set(this,{loadOnPrompt:()=>ze(this,o,nS).call(this)}),le(this,a,new Bc(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=M(this,a))==null||h.destroy(),le(this,a,null),vs.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,m){if(super.attributeChangedCallback(h,f,m),h==="cast-receiver"&&m){M(this,r).receiverApplicationId=m;return}if(M(this,o,Ge))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var b,E;if(!M(this,o,Ge))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:T,src:_})=>_&&(T==="subtitles"||T==="captions")),m=[],p=0;if(f.length&&(h.tracks=f.map(T=>{let _=++p;m.length===0&&T.track.mode==="showing"&&m.push(_);let I=new chrome.cast.media.Track(_,chrome.cast.media.TrackType.TEXT);return I.trackContentId=T.src,I.trackContentType="text/vtt",I.subtype=T.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,I.name=T.label,I.language=T.srclang,I})),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 XA(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let{videoFormat:T,audioFormat:_}=await ZA(this.castSrc);(T==null?void 0:T.includes("m4s"))||(T==null?void 0:T.includes("mp4"))||(T==null?void 0:T.includes("m4a"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):_!=null&&_.includes("aac")?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.AAC,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.MPEG2_TS):(T!=null&&T.includes("ts")||_!=null&&_.includes("ts"))&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.MPEG2_TS)}let v=new chrome.cast.media.LoadRequest(h);v.currentTime=(b=super.currentTime)!=null?b:0,v.autoplay=!M(this,s).paused,v.activeTrackIds=m,await((E=Ml())==null?void 0:E.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(M(this,o,Ge)){M(this,o,Ge).isPaused&&((h=M(this,o,Ge).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(M(this,o,Ge)){M(this,o,Ge).isPaused||(h=M(this,o,Ge).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return M(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,b;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(b=(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?b: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 M(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}le(this,n,h)}get readyState(){if(M(this,o,Ge))switch(M(this,o,Ge).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 M(this,o,Ge)?M(this,o,Ge).isPaused:super.paused}get muted(){var h;return M(this,o,Ge)?(h=M(this,o,Ge))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(M(this,o,Ge)){(h&&!M(this,o,Ge).isMuted||!h&&M(this,o,Ge).isMuted)&&((f=M(this,o,Ge).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return M(this,o,Ge)?(f=(h=M(this,o,Ge))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(M(this,o,Ge)){M(this,o,Ge).volumeLevel=+h,(f=M(this,o,Ge).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,m;return M(this,o,Ge)&&((h=M(this,o,Ge))!=null&&h.isMediaLoaded)?(m=(f=M(this,o,Ge))==null?void 0:f.duration)!=null?m:NaN:super.duration}get currentTime(){var h,f,m;return M(this,o,Ge)&&((h=M(this,o,Ge))!=null&&h.isMediaLoaded)?(m=(f=M(this,o,Ge))==null?void 0:f.currentTime)!=null?m:0:super.currentTime}set currentTime(h){var f;if(M(this,o,Ge)){M(this,o,Ge).currentTime=h,(f=M(this,o,Ge).controller)==null||f.seek();return}super.currentTime=h}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,Ge=function(){var h,f;return(f=(h=vs.get(M(this,a)))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},nS=async function(){M(this,s).paused=Jd(t.prototype,this,"paused"),Jd(t.prototype,this,"pause").call(this),this.muted=Jd(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},Oe(t,"observedAttributes",[...(e=i.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var Js=class extends Event{constructor(t,s){super(t);Oe(this,"track");this.track=s.track}};var V0=new WeakMap;function J(i){var e;return(e=V0.get(i))!=null?e:CO(i,{})}function CO(i,e){let t=V0.get(i);return t||V0.set(i,t={}),Object.assign(t,e)}function Hc(i,e){let t=i.videoTracks;J(e).media=new WeakRef(i),J(e).renditionSet||(J(e).renditionSet=new Set);let s=J(t).trackSet;s.add(e);let r=s.size-1;r in xn.prototype||Object.defineProperty(xn.prototype,r,{get(){return[...J(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Js("addtrack",{track:e}))})}function Gc(i){var s,r;let e=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks;if(!e)return;J(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Js("removetrack",{track:i}))})}function aS(i){var s,r,n;let e=(n=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==i&&(a.selected=!1,t=!0);if(t){if(J(e).changeRequested)return;J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var Cr,wr,Mr,Ln,Ol,xn=class extends EventTarget{constructor(){super();fe(this,Ln);fe(this,Cr);fe(this,wr);fe(this,Mr);J(this).trackSet=new Set}[Symbol.iterator](){return M(this,Ln,Ol).values()}get length(){return M(this,Ln,Ol).size}getTrackById(t){var s;return(s=[...M(this,Ln,Ol)].find(r=>r.id===t))!=null?s:null}get selectedIndex(){return[...M(this,Ln,Ol)].findIndex(t=>t.selected)}get onaddtrack(){return M(this,Cr)}set onaddtrack(t){M(this,Cr)&&(this.removeEventListener("addtrack",M(this,Cr)),le(this,Cr,void 0)),typeof t=="function"&&(le(this,Cr,t),this.addEventListener("addtrack",t))}get onremovetrack(){return M(this,wr)}set onremovetrack(t){M(this,wr)&&(this.removeEventListener("removetrack",M(this,wr)),le(this,wr,void 0)),typeof t=="function"&&(le(this,wr,t),this.addEventListener("removetrack",t))}get onchange(){return M(this,Mr)}set onchange(t){M(this,Mr)&&(this.removeEventListener("change",M(this,Mr)),le(this,Mr,void 0)),typeof t=="function"&&(le(this,Mr,t),this.addEventListener("change",t))}};Cr=new WeakMap,wr=new WeakMap,Mr=new WeakMap,Ln=new WeakSet,Ol=function(){return J(this).trackSet};var er=class extends Event{constructor(t,s){super(t);Oe(this,"rendition");this.rendition=s.rendition}};function oS(i,e){var n,a;let t=(a=(n=J(i).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;J(e).media=J(i).media,J(e).track=i;let s=J(i).renditionSet;s.add(e);let r=s.size-1;r in kn.prototype||Object.defineProperty(kn.prototype,r,{get(){return Ia(this)[r]}}),queueMicrotask(()=>{!t||!i.selected||t.dispatchEvent(new er("addrendition",{rendition:e}))})}function lS(i){var r,n;let e=(n=(r=J(i).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=J(i).track;J(t).renditionSet.delete(i),queueMicrotask(()=>{let a=J(i).track;!e||!a.selected||e.dispatchEvent(new er("removerendition",{rendition:i}))})}function dS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.videoRenditions;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,J(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function Ia(i){var t;let e=(t=J(i).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(s=>s.selected).flatMap(s=>[...J(s).renditionSet]):[]}var Pr,Or,Nr,kn=class extends EventTarget{constructor(){super(...arguments);fe(this,Pr);fe(this,Or);fe(this,Nr)}[Symbol.iterator](){return Ia(this).values()}get length(){return Ia(this).length}getRenditionById(t){var s;return(s=Ia(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return Ia(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of Ia(this).entries())r.selected=s===t}get onaddrendition(){return M(this,Pr)}set onaddrendition(t){M(this,Pr)&&(this.removeEventListener("addrendition",M(this,Pr)),le(this,Pr,void 0)),typeof t=="function"&&(le(this,Pr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return M(this,Or)}set onremoverendition(t){M(this,Or)&&(this.removeEventListener("removerendition",M(this,Or)),le(this,Or,void 0)),typeof t=="function"&&(le(this,Or,t),this.addEventListener("removerendition",t))}get onchange(){return M(this,Nr)}set onchange(t){M(this,Nr)&&(this.removeEventListener("change",M(this,Nr)),le(this,Nr,void 0)),typeof t=="function"&&(le(this,Nr,t),this.addEventListener("change",t))}};Pr=new WeakMap,Or=new WeakMap,Nr=new WeakMap;var Ra,Nl=class{constructor(){Oe(this,"src");Oe(this,"id");Oe(this,"width");Oe(this,"height");Oe(this,"bitrate");Oe(this,"frameRate");Oe(this,"codec");fe(this,Ra,!1)}get selected(){return M(this,Ra)}set selected(e){M(this,Ra)!==e&&(le(this,Ra,e),dS(this))}};Ra=new WeakMap;var La,xa=class{constructor(){Oe(this,"id");Oe(this,"kind");Oe(this,"label","");Oe(this,"language","");Oe(this,"sourceBuffer");fe(this,La,!1)}addRendition(e,t,s,r,n,a){let o=new Nl;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,oS(this,o),o}removeRendition(e){lS(e)}get selected(){return M(this,La)}set selected(e){M(this,La)!==e&&(le(this,La,e),e===!0&&aS(this))}};La=new WeakMap;function uS(i,e){var n,a;let t=(a=(n=J(i).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;J(e).media=J(i).media,J(e).track=i;let s=J(i).renditionSet;s.add(e);let r=s.size-1;r in Dn.prototype||Object.defineProperty(Dn.prototype,r,{get(){return ka(this)[r]}}),queueMicrotask(()=>{!t||!i.enabled||t.dispatchEvent(new er("addrendition",{rendition:e}))})}function cS(i){var r,n;let e=(n=(r=J(i).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=J(i).track;J(t).renditionSet.delete(i),queueMicrotask(()=>{let a=J(i).track;!e||!a.enabled||e.dispatchEvent(new er("removerendition",{rendition:i}))})}function hS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.audioRenditions;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,J(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function ka(i){var t;let e=(t=J(i).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(s=>s.enabled).flatMap(s=>[...J(s).renditionSet]):[]}var Ur,Fr,Br,Dn=class extends EventTarget{constructor(){super(...arguments);fe(this,Ur);fe(this,Fr);fe(this,Br)}[Symbol.iterator](){return ka(this).values()}get length(){return ka(this).length}getRenditionById(t){var s;return(s=ka(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return ka(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of ka(this).entries())r.selected=s===t}get onaddrendition(){return M(this,Ur)}set onaddrendition(t){M(this,Ur)&&(this.removeEventListener("addrendition",M(this,Ur)),le(this,Ur,void 0)),typeof t=="function"&&(le(this,Ur,t),this.addEventListener("addrendition",t))}get onremoverendition(){return M(this,Fr)}set onremoverendition(t){M(this,Fr)&&(this.removeEventListener("removerendition",M(this,Fr)),le(this,Fr,void 0)),typeof t=="function"&&(le(this,Fr,t),this.addEventListener("removerendition",t))}get onchange(){return M(this,Br)}set onchange(t){M(this,Br)&&(this.removeEventListener("change",M(this,Br)),le(this,Br,void 0)),typeof t=="function"&&(le(this,Br,t),this.addEventListener("change",t))}};Ur=new WeakMap,Fr=new WeakMap,Br=new WeakMap;var Da,Ul=class{constructor(){Oe(this,"src");Oe(this,"id");Oe(this,"bitrate");Oe(this,"codec");fe(this,Da,!1)}get selected(){return M(this,Da)}set selected(e){M(this,Da)!==e&&(le(this,Da,e),hS(this))}};Da=new WeakMap;function Vc(i,e){let t=i.audioTracks;J(e).media=new WeakRef(i),J(e).renditionSet||(J(e).renditionSet=new Set);let s=J(t).trackSet;s.add(e);let r=s.size-1;r in Cn.prototype||Object.defineProperty(Cn.prototype,r,{get(){return[...J(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Js("addtrack",{track:e}))})}function Wc(i){var s,r;let e=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.audioTracks;if(!e)return;J(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Js("removetrack",{track:i}))})}function fS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.audioTracks;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var $r,Hr,Gr,Ca,Kc,Cn=class extends EventTarget{constructor(){super();fe(this,Ca);fe(this,$r);fe(this,Hr);fe(this,Gr);J(this).trackSet=new Set}[Symbol.iterator](){return M(this,Ca,Kc).values()}get length(){return M(this,Ca,Kc).size}getTrackById(t){var s;return(s=[...M(this,Ca,Kc)].find(r=>r.id===t))!=null?s:null}get onaddtrack(){return M(this,$r)}set onaddtrack(t){M(this,$r)&&(this.removeEventListener("addtrack",M(this,$r)),le(this,$r,void 0)),typeof t=="function"&&(le(this,$r,t),this.addEventListener("addtrack",t))}get onremovetrack(){return M(this,Hr)}set onremovetrack(t){M(this,Hr)&&(this.removeEventListener("removetrack",M(this,Hr)),le(this,Hr,void 0)),typeof t=="function"&&(le(this,Hr,t),this.addEventListener("removetrack",t))}get onchange(){return M(this,Gr)}set onchange(t){M(this,Gr)&&(this.removeEventListener("change",M(this,Gr)),le(this,Gr,void 0)),typeof t=="function"&&(le(this,Gr,t),this.addEventListener("change",t))}};$r=new WeakMap,Hr=new WeakMap,Gr=new WeakMap,Ca=new WeakSet,Kc=function(){return J(this).trackSet};var wa,Ma=class{constructor(){Oe(this,"id");Oe(this,"kind");Oe(this,"label","");Oe(this,"language","");Oe(this,"sourceBuffer");fe(this,wa,!1)}addRendition(e,t,s){let r=new Ul;return r.src=e,r.codec=t,r.bitrate=s,uS(this,r),r}removeRendition(e){cS(e)}get enabled(){return M(this,wa)}set enabled(e){M(this,wa)!==e&&(le(this,wa,e),fS(this))}};wa=new WeakMap;var mS=qc(globalThis.HTMLMediaElement,"video"),pS=qc(globalThis.HTMLMediaElement,"audio");function gS(i){if(!(i!=null&&i.prototype))return i;let e=qc(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return wO(this)}});let t=qc(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return MO(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){let l=new xa;return l.kind=n,l.label=a,l.language=o,Hc(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=Gc),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){let l=new Ma;return l.kind=n,l.label=a,l.language=o,Vc(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=Wc),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});let s=n=>{let a=J(n).videoRenditions;return a||(a=new kn,J(a).media=new WeakRef(n),J(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=J(n).audioRenditions;return a||(a=new Dn,J(a).media=new WeakRef(n),J(n).audioRenditions=a),a};return i}function qc(i,e){var t;if(i!=null&&i.prototype)return(t=Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`))==null?void 0:t.get}function wO(i){var t;let e=J(i).videoTracks;if(!e&&(e=new xn,J(i).videoTracks=e,mS)){let s=mS.call((t=i.nativeEl)!=null?t:i);for(let o of s)Hc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof xa)){for(let l of s)Gc(l);return}Hc(i,o.track)},a=o=>{Gc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}function MO(i){var t;let e=J(i).audioTracks;if(!e&&(e=new Cn,J(i).audioTracks=e,pS)){let s=pS.call((t=i.nativeEl)!=null?t:i);for(let o of s)Vc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof Ma)){for(let l of s)Wc(l);return}Vc(i,o.track)},a=o=>{Wc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}var ES=i=>{throw TypeError(i)},yS=(i,e,t)=>e.has(i)||ES("Cannot "+t),bS=(i,e,t)=>(yS(i,e,"read from private field"),t?t.call(i):e.get(i)),TS=(i,e,t)=>e.has(i)?ES("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),_S=(i,e,t,s)=>(yS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends zc{}globalThis.DocumentFragment=i}var q0=class extends zc{},PO=class extends zc{},OO={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(q0)}},Yc,NO=class{constructor(i,e={}){TS(this,Yc),_S(this,Yc,e==null?void 0:e.detail)}get detail(){return bS(this,Yc)}initCustomEvent(){}};Yc=new WeakMap;function UO(i,e){return new q0}var AS={document:{createElement:UO},DocumentFragment,customElements:OO,CustomEvent:NO,EventTarget:zc,HTMLElement:q0,HTMLVideoElement:PO},SS=typeof window=="undefined"||typeof globalThis.customElements=="undefined",W0=SS?AS:globalThis,O4=SS?AS.document:globalThis.document,jc,vS=class extends rS(gS(GA)){constructor(){super(...arguments),TS(this,jc)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):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 i;return(i=bS(this,jc))!=null?i:this.muxCastCustomData}set castCustomData(i){_S(this,jc,i)}};jc=new WeakMap;W0.customElements.get("mux-video")||(W0.customElements.define("mux-video",vS),W0.MuxVideoElement=vS);var Y={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},Le={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Y0={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},IS=Object.entries(Y0),A=IS.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),FO={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},Ri=IS.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...FO}),q4=Object.entries(Ri).reduce((i,[e,t])=>{let s=A[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"}),RS=Object.entries(A).reduce((i,[e,t])=>{let s=Ri[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),hi={SUBTITLES:"subtitles",CAPTIONS:"captions",DESCRIPTIONS:"descriptions",CHAPTERS:"chapters",METADATA:"metadata"},Kr={DISABLED:"disabled",HIDDEN:"hidden",SHOWING:"showing"};var Qc={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},fi={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},Xi={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var LS={INLINE:"inline",FULLSCREEN:"fullscreen",PICTURE_IN_PICTURE:"picture-in-picture"};function xS(i){return i==null?void 0:i.map($O).join(" ")}function kS(i){return i==null?void 0:i.split(/\s+/).map(HO)}function $O(i){if(i){let{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function HO(i){if(i){let[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function DS(i){return i==null?void 0:i.map(GO).join(" ")}function CS(i){return i==null?void 0:i.split(/\s+/).map(KO)}function GO(i){if(i){let{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function KO(i){if(i){let[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function wS(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Pa(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function Xc(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}var Zc=i=>new Promise(e=>setTimeout(e,i));var MS={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it.",hour:"hour",hours:"hours",minute:"minute",minutes:"minutes",second:"second",seconds:"seconds","{time} remaining":"{time} remaining","{currentTime} of {totalTime}":"{currentTime} of {totalTime}","video not loaded, unknown time.":"video not loaded, unknown time."};var PS,Fl={en:MS},Oa=((PS=globalThis.navigator)==null?void 0:PS.language)||"en",OS=i=>{Oa=i};var VO=i=>{var e,t,s;let[r]=Oa.split("-");return((e=Fl[Oa])==null?void 0:e[i])||((t=Fl[r])==null?void 0:t[i])||((s=Fl.en)==null?void 0:s[i])||i},NS=()=>{let[i]=Oa.split("-");return Fl[Oa]?Oa:Fl[i]?i:"en"},G=(i,e={})=>VO(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);var US=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],FS=(i,e)=>{let t=i===1?G(US[e].singular):G(US[e].plural);return`${i} ${t}`},wn=i=>{if(!Pa(i))return"";let e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0),n=[s.getHours(),s.getMinutes(),s.getSeconds()].map((a,o)=>a&&FS(a,o)).filter(a=>a).join(", ");return t?G("{time} remaining",{time:n}):e===0?FS(0,2):n};function Zi(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}var J4=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}});var Jc=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}},eh=class extends Jc{},th=class extends eh{constructor(){super(...arguments),this.role=null}},j0=class{observe(){}unobserve(){}disconnect(){}},BS={createElement:function(){return new Bl.HTMLElement},createElementNS:function(){return new Bl.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},Bl={ResizeObserver:j0,document:BS,Node:eh,Element:th,HTMLElement:class extends th{constructor(){super(...arguments),this.innerHTML=""}get content(){return new Bl.DocumentFragment}},DocumentFragment:class extends Jc{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},$S="global"in globalThis&&(globalThis==null?void 0:globalThis.global)===globalThis||typeof window=="undefined"||typeof window.customElements=="undefined",HS=Object.keys(Bl).every(i=>i in globalThis),L=$S&&!HS?Bl:globalThis,et=$S&&!HS?BS:globalThis.document;var GS=new WeakMap,z0=i=>{let e=GS.get(i);return e||GS.set(i,e=new Set),e},KS=new L.ResizeObserver(i=>{for(let e of i)for(let t of z0(e.target))t(e)});function tr(i,e){z0(i).add(e),KS.observe(i)}function ir(i,e){let t=z0(i);t.delete(e),t.size||KS.unobserve(i)}function lt(i){let e={};for(let t of i)e[t.name]=t.value;return e}function nt(i){var e;return(e=ih(i))!=null?e:Es(i,"media-controller")}function ih(i){var e;let{MEDIA_CONTROLLER:t}=Le,s=i.getAttribute(t);if(s)return(e=Mn(i))==null?void 0:e.getElementById(s)}var sh=(i,e,t=".value")=>{let s=i.querySelector(t);s&&(s.textContent=e)},qO=(i,e)=>{let t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},rh=(i,e)=>qO(i,e)[0],ni=(i,e)=>!i||!e?!1:i!=null&&i.contains(e)?!0:ni(i,e.getRootNode().host),Es=(i,e)=>{if(!i)return null;let t=i.closest(e);return t||Es(i.getRootNode().host,e)};function $l(i=document){var e;let t=i==null?void 0:i.activeElement;return t?(e=$l(t.shadowRoot))!=null?e:t:null}function Mn(i){var e;let t=(e=i==null?void 0:i.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function nh(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){let n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function VS(i,e,t,s){let r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;let o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function at(i,e){let t=YO(i,s=>s===e);return t||Hl(i,e)}function YO(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(let a of n!=null?n:[])if(e(a.selectorText))return a}}function Hl(i,e){var t,s;let r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r==null?void 0:r[r.length-1];if(!(n!=null&&n.sheet))return console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}};let a=n==null?void 0:n.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length);return(s=n.sheet.cssRules)==null?void 0:s[a]}function De(i,e,t=Number.NaN){let s=i.getAttribute(e);return s!=null?+s:t}function Ue(i,e,t){let s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}De(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function pe(i,e){return i.hasAttribute(e)}function ge(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}pe(i,e)!=t&&i.toggleAttribute(e,t)}function Se(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function Ae(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}let s=`${t}`;Se(i,e,void 0)!==s&&i.setAttribute(e,s)}var WS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ji=(i,e,t)=>(WS(i,e,"read from private field"),t?t.call(i):e.get(i)),jO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},ah=(i,e,t,s)=>(WS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zt;function zO(i){return`
|
|
143
|
+
`).find(s=>!s.trim().startsWith("#")&&s.trim()!=="");return t==null?void 0:t.trim()}async function XA(i){if(!i)return!1;if(/\.m3u8?(\?.*)?$/i.test(i))return!0;if(i.startsWith("blob:"))return!1;try{let t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return xO.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function ZA(i){var e;if(!i||i.startsWith("blob:"))return{videoFormat:void 0,audioFormat:void 0};try{let t=await(await fetch(i)).text(),s=t,r=DO(t);if(r.length>0){let d=new URL(r[0],i).toString();s=await(await fetch(d)).text()}let n=VA(s),a=KA(n),o=kO(t),l=a;if(o)try{let d=new URL(o,i).toString(),u=await(await fetch(d)).text(),c=VA(u);l=(e=KA(c))!=null?e:a}catch(d){console.error("Error while trying to parse the audio rendition playlist",d)}return{videoFormat:a,audioFormat:l}}catch(t){return console.error("Error while trying to parse the manifest playlist",t),{videoFormat:void 0,audioFormat:void 0}}}var Fc=new WA,Zs=new WeakSet,Nt;qA(()=>{var i,e,t,s;if(!((e=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(s=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:s.isAvailable);return}Nt||(Nt=cast.framework,Xs().addEventListener(Nt.CastContextEventType.CAST_STATE_CHANGED,r=>{Fc.forEach(n=>{var a,o;return(o=(a=vs.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),Xs().addEventListener(Nt.CastContextEventType.SESSION_STATE_CHANGED,r=>{Fc.forEach(n=>{var a,o;return(o=(a=vs.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),Fc.forEach(r=>{var n,a;return(a=(n=vs.get(r)).init)==null?void 0:a.call(n)}))});var JA=0,Be,Sa,ri,Qi,In,Rn,Dr,$c,Pl,ot,Sn,eS,tS,H0,iS,G0,sS,K0,Bc=class extends EventTarget{constructor(t){super();fe(this,ot);fe(this,Be);fe(this,Sa);fe(this,ri);fe(this,Qi);fe(this,In,"disconnected");fe(this,Rn,!1);fe(this,Dr,new Set);fe(this,$c,new WeakMap);fe(this,Pl,()=>ze(this,ot,K0).call(this));le(this,Be,t),Fc.add(this),vs.set(this,{init:()=>ze(this,ot,G0).call(this),onCastStateChanged:()=>ze(this,ot,H0).call(this),onSessionStateChanged:()=>ze(this,ot,iS).call(this),getCastPlayer:()=>M(this,ot,Sn)}),ze(this,ot,G0).call(this)}destroy(){var t,s,r;(s=(t=M(this,Be))==null?void 0:t.textTracks)==null||s.removeEventListener("change",M(this,Pl)),M(this,Qi)&&((r=M(this,ri))!=null&&r.controller)&&Object.entries(M(this,Qi)).forEach(([n,a])=>{M(this,ri).controller.removeEventListener(n,a)}),M(this,Be)&&Zs.delete(M(this,Be)),le(this,Sa,!1)}get state(){return M(this,In)}async watchAvailability(t){if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");return M(this,$c).set(t,++JA),M(this,Dr).add(t),queueMicrotask(()=>t(ze(this,ot,tS).call(this))),JA}async cancelWatchAvailability(t){if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");t?M(this,Dr).delete(t):M(this,Dr).clear()}async prompt(){var s,r,n,a;if(M(this,Be).disableRemotePlayback)throw new Aa("disableRemotePlayback attribute is present.");if(!((r=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&r.isAvailable))throw new Nc("The RemotePlayback API is disabled on this platform.");let t=Zs.has(M(this,Be));Zs.add(M(this,Be)),B0(M(this,Be).castOptions),Object.entries(M(this,Qi)).forEach(([o,l])=>{M(this,ri).controller.addEventListener(o,l)});try{await Xs().requestSession()}catch(o){if(t||Zs.delete(M(this,Be)),o==="cancel")return;throw new Error(o)}(a=(n=vs.get(M(this,Be)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};Be=new WeakMap,Sa=new WeakMap,ri=new WeakMap,Qi=new WeakMap,In=new WeakMap,Rn=new WeakMap,Dr=new WeakMap,$c=new WeakMap,Pl=new WeakMap,ot=new WeakSet,Sn=function(){if(Zs.has(M(this,Be)))return M(this,ri)},eS=function(){Zs.has(M(this,Be))&&(Object.entries(M(this,Qi)).forEach(([t,s])=>{M(this,ri).controller.removeEventListener(t,s)}),Zs.delete(M(this,Be)),M(this,Be).muted=M(this,ri).isMuted,M(this,Be).currentTime=M(this,ri).savedPlayerState.currentTime,M(this,ri).savedPlayerState.isPaused===!1&&M(this,Be).play())},tS=function(){var s;let t=(s=Xs())==null?void 0:s.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},H0=function(){let t=Xs().getCastState();if(Zs.has(M(this,Be))&&t==="CONNECTING"&&(le(this,In,"connecting"),this.dispatchEvent(new Event("connecting"))),!M(this,Rn)&&(t!=null&&t.includes("CONNECT"))){le(this,Rn,!0);for(let s of M(this,Dr))s(!0)}else if(M(this,Rn)&&(!t||t==="NO_DEVICES_AVAILABLE")){le(this,Rn,!1);for(let s of M(this,Dr))s(!1)}},iS=async function(){var s;let{SESSION_RESUMED:t}=Nt.SessionState;if(Xs().getSessionState()===t&&M(this,Be).castSrc===((s=Uc())==null?void 0:s.media.contentId)){Zs.add(M(this,Be)),Object.entries(M(this,Qi)).forEach(([r,n])=>{M(this,ri).controller.addEventListener(r,n)});try{await QA(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}M(this,Qi)[Nt.RemotePlayerEventType.IS_PAUSED_CHANGED](),M(this,Qi)[Nt.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},G0=function(){!Nt||M(this,Sa)||(le(this,Sa,!0),B0(M(this,Be).castOptions),M(this,Be).textTracks.addEventListener("change",M(this,Pl)),ze(this,ot,H0).call(this),le(this,ri,new Nt.RemotePlayer),new Nt.RemotePlayerController(M(this,ri)),le(this,Qi,{[Nt.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(le(this,In,"connected"),this.dispatchEvent(new Event("connect"))):(ze(this,ot,eS).call(this),le(this,In,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[Nt.RemotePlayerEventType.DURATION_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("durationchange"))},[Nt.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("volumechange"))},[Nt.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("volumechange"))},[Nt.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=M(this,ot,Sn))!=null&&t.isMediaLoaded&&M(this,Be).dispatchEvent(new Event("timeupdate"))},[Nt.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event("resize"))},[Nt.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{M(this,Be).dispatchEvent(new Event(this.paused?"pause":"play"))},[Nt.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,s;((t=M(this,ot,Sn))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&M(this,Be).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(s=M(this,ot,Sn))==null?void 0:s.playerState]))},[Nt.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=M(this,ot,Sn))!=null&&t.isMediaLoaded&&(await Promise.resolve(),ze(this,ot,sS).call(this))}}))},sS=function(){ze(this,ot,K0).call(this)},K0=async function(){var h,f,m,p,g;if(!M(this,ot,Sn))return;let s=((f=(h=M(this,ri).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...M(this,Be).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=s.map(({language:v,name:E,trackId:b})=>{var _;let{mode:T}=(_=r.find(I=>I.language===v&&I.label===E))!=null?_:{};return T?{mode:T,trackId:b}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),d=(g=(p=(m=Ml())==null?void 0:m.getSessionObj().media[0])==null?void 0:p.activeTrackIds)!=null?g:[],u=d;if(d.length&&(u=u.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(u=[...u,l.trackId]),u=[...new Set(u)],!((v,E)=>v.length===E.length&&v.every(b=>E.includes(b)))(d,u))try{let v=new chrome.cast.media.EditTracksInfoRequest(u);await zA(v)}catch(v){console.error(v)}};var rS=i=>{var e,t,s,r,n,a,o,Ge,nS;return t=class extends i{constructor(){super(...arguments);fe(this,o);fe(this,s,{paused:!1});fe(this,r,$0());fe(this,n);fe(this,a)}get remote(){return M(this,a)?M(this,a):YA()?this.isConnected?(this.disableRemotePlayback||jA(),vs.set(this,{loadOnPrompt:()=>ze(this,o,nS).call(this)}),le(this,a,new Bc(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=M(this,a))==null||h.destroy(),le(this,a,null),vs.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,m){if(super.attributeChangedCallback(h,f,m),h==="cast-receiver"&&m){M(this,r).receiverApplicationId=m;return}if(M(this,o,Ge))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var E,b;if(!M(this,o,Ge))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:T,src:_})=>_&&(T==="subtitles"||T==="captions")),m=[],p=0;if(f.length&&(h.tracks=f.map(T=>{let _=++p;m.length===0&&T.track.mode==="showing"&&m.push(_);let I=new chrome.cast.media.Track(_,chrome.cast.media.TrackType.TEXT);return I.trackContentId=T.src,I.trackContentType="text/vtt",I.subtype=T.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,I.name=T.label,I.language=T.srclang,I})),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 XA(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let{videoFormat:T,audioFormat:_}=await ZA(this.castSrc);(T==null?void 0:T.includes("m4s"))||(T==null?void 0:T.includes("mp4"))||(T==null?void 0:T.includes("m4a"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):_!=null&&_.includes("aac")?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.AAC,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.MPEG2_TS):(T!=null&&T.includes("ts")||_!=null&&_.includes("ts"))&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.MPEG2_TS)}let v=new chrome.cast.media.LoadRequest(h);v.currentTime=(E=super.currentTime)!=null?E:0,v.autoplay=!M(this,s).paused,v.activeTrackIds=m,await((b=Ml())==null?void 0:b.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(M(this,o,Ge)){M(this,o,Ge).isPaused&&((h=M(this,o,Ge).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(M(this,o,Ge)){M(this,o,Ge).isPaused||(h=M(this,o,Ge).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return M(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,E;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(E=(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?E: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 M(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}le(this,n,h)}get readyState(){if(M(this,o,Ge))switch(M(this,o,Ge).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 M(this,o,Ge)?M(this,o,Ge).isPaused:super.paused}get muted(){var h;return M(this,o,Ge)?(h=M(this,o,Ge))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(M(this,o,Ge)){(h&&!M(this,o,Ge).isMuted||!h&&M(this,o,Ge).isMuted)&&((f=M(this,o,Ge).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return M(this,o,Ge)?(f=(h=M(this,o,Ge))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(M(this,o,Ge)){M(this,o,Ge).volumeLevel=+h,(f=M(this,o,Ge).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,m;return M(this,o,Ge)&&((h=M(this,o,Ge))!=null&&h.isMediaLoaded)?(m=(f=M(this,o,Ge))==null?void 0:f.duration)!=null?m:NaN:super.duration}get currentTime(){var h,f,m;return M(this,o,Ge)&&((h=M(this,o,Ge))!=null&&h.isMediaLoaded)?(m=(f=M(this,o,Ge))==null?void 0:f.currentTime)!=null?m:0:super.currentTime}set currentTime(h){var f;if(M(this,o,Ge)){M(this,o,Ge).currentTime=h,(f=M(this,o,Ge).controller)==null||f.seek();return}super.currentTime=h}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,Ge=function(){var h,f;return(f=(h=vs.get(M(this,a)))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},nS=async function(){M(this,s).paused=Jd(t.prototype,this,"paused"),Jd(t.prototype,this,"pause").call(this),this.muted=Jd(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},Oe(t,"observedAttributes",[...(e=i.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var Js=class extends Event{constructor(t,s){super(t);Oe(this,"track");this.track=s.track}};var V0=new WeakMap;function J(i){var e;return(e=V0.get(i))!=null?e:CO(i,{})}function CO(i,e){let t=V0.get(i);return t||V0.set(i,t={}),Object.assign(t,e)}function Hc(i,e){let t=i.videoTracks;J(e).media=new WeakRef(i),J(e).renditionSet||(J(e).renditionSet=new Set);let s=J(t).trackSet;s.add(e);let r=s.size-1;r in xn.prototype||Object.defineProperty(xn.prototype,r,{get(){return[...J(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Js("addtrack",{track:e}))})}function Gc(i){var s,r;let e=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks;if(!e)return;J(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Js("removetrack",{track:i}))})}function aS(i){var s,r,n;let e=(n=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==i&&(a.selected=!1,t=!0);if(t){if(J(e).changeRequested)return;J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var Cr,wr,Mr,Ln,Ol,xn=class extends EventTarget{constructor(){super();fe(this,Ln);fe(this,Cr);fe(this,wr);fe(this,Mr);J(this).trackSet=new Set}[Symbol.iterator](){return M(this,Ln,Ol).values()}get length(){return M(this,Ln,Ol).size}getTrackById(t){var s;return(s=[...M(this,Ln,Ol)].find(r=>r.id===t))!=null?s:null}get selectedIndex(){return[...M(this,Ln,Ol)].findIndex(t=>t.selected)}get onaddtrack(){return M(this,Cr)}set onaddtrack(t){M(this,Cr)&&(this.removeEventListener("addtrack",M(this,Cr)),le(this,Cr,void 0)),typeof t=="function"&&(le(this,Cr,t),this.addEventListener("addtrack",t))}get onremovetrack(){return M(this,wr)}set onremovetrack(t){M(this,wr)&&(this.removeEventListener("removetrack",M(this,wr)),le(this,wr,void 0)),typeof t=="function"&&(le(this,wr,t),this.addEventListener("removetrack",t))}get onchange(){return M(this,Mr)}set onchange(t){M(this,Mr)&&(this.removeEventListener("change",M(this,Mr)),le(this,Mr,void 0)),typeof t=="function"&&(le(this,Mr,t),this.addEventListener("change",t))}};Cr=new WeakMap,wr=new WeakMap,Mr=new WeakMap,Ln=new WeakSet,Ol=function(){return J(this).trackSet};var er=class extends Event{constructor(t,s){super(t);Oe(this,"rendition");this.rendition=s.rendition}};function oS(i,e){var n,a;let t=(a=(n=J(i).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;J(e).media=J(i).media,J(e).track=i;let s=J(i).renditionSet;s.add(e);let r=s.size-1;r in kn.prototype||Object.defineProperty(kn.prototype,r,{get(){return Ia(this)[r]}}),queueMicrotask(()=>{!t||!i.selected||t.dispatchEvent(new er("addrendition",{rendition:e}))})}function lS(i){var r,n;let e=(n=(r=J(i).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=J(i).track;J(t).renditionSet.delete(i),queueMicrotask(()=>{let a=J(i).track;!e||!a.selected||e.dispatchEvent(new er("removerendition",{rendition:i}))})}function dS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.videoRenditions;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,J(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function Ia(i){var t;let e=(t=J(i).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(s=>s.selected).flatMap(s=>[...J(s).renditionSet]):[]}var Pr,Or,Nr,kn=class extends EventTarget{constructor(){super(...arguments);fe(this,Pr);fe(this,Or);fe(this,Nr)}[Symbol.iterator](){return Ia(this).values()}get length(){return Ia(this).length}getRenditionById(t){var s;return(s=Ia(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return Ia(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of Ia(this).entries())r.selected=s===t}get onaddrendition(){return M(this,Pr)}set onaddrendition(t){M(this,Pr)&&(this.removeEventListener("addrendition",M(this,Pr)),le(this,Pr,void 0)),typeof t=="function"&&(le(this,Pr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return M(this,Or)}set onremoverendition(t){M(this,Or)&&(this.removeEventListener("removerendition",M(this,Or)),le(this,Or,void 0)),typeof t=="function"&&(le(this,Or,t),this.addEventListener("removerendition",t))}get onchange(){return M(this,Nr)}set onchange(t){M(this,Nr)&&(this.removeEventListener("change",M(this,Nr)),le(this,Nr,void 0)),typeof t=="function"&&(le(this,Nr,t),this.addEventListener("change",t))}};Pr=new WeakMap,Or=new WeakMap,Nr=new WeakMap;var Ra,Nl=class{constructor(){Oe(this,"src");Oe(this,"id");Oe(this,"width");Oe(this,"height");Oe(this,"bitrate");Oe(this,"frameRate");Oe(this,"codec");fe(this,Ra,!1)}get selected(){return M(this,Ra)}set selected(e){M(this,Ra)!==e&&(le(this,Ra,e),dS(this))}};Ra=new WeakMap;var La,xa=class{constructor(){Oe(this,"id");Oe(this,"kind");Oe(this,"label","");Oe(this,"language","");Oe(this,"sourceBuffer");fe(this,La,!1)}addRendition(e,t,s,r,n,a){let o=new Nl;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,oS(this,o),o}removeRendition(e){lS(e)}get selected(){return M(this,La)}set selected(e){M(this,La)!==e&&(le(this,La,e),e===!0&&aS(this))}};La=new WeakMap;function uS(i,e){var n,a;let t=(a=(n=J(i).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;J(e).media=J(i).media,J(e).track=i;let s=J(i).renditionSet;s.add(e);let r=s.size-1;r in Dn.prototype||Object.defineProperty(Dn.prototype,r,{get(){return ka(this)[r]}}),queueMicrotask(()=>{!t||!i.enabled||t.dispatchEvent(new er("addrendition",{rendition:e}))})}function cS(i){var r,n;let e=(n=(r=J(i).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=J(i).track;J(t).renditionSet.delete(i),queueMicrotask(()=>{let a=J(i).track;!e||!a.enabled||e.dispatchEvent(new er("removerendition",{rendition:i}))})}function hS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.audioRenditions;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,J(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function ka(i){var t;let e=(t=J(i).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(s=>s.enabled).flatMap(s=>[...J(s).renditionSet]):[]}var Ur,Fr,Br,Dn=class extends EventTarget{constructor(){super(...arguments);fe(this,Ur);fe(this,Fr);fe(this,Br)}[Symbol.iterator](){return ka(this).values()}get length(){return ka(this).length}getRenditionById(t){var s;return(s=ka(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return ka(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of ka(this).entries())r.selected=s===t}get onaddrendition(){return M(this,Ur)}set onaddrendition(t){M(this,Ur)&&(this.removeEventListener("addrendition",M(this,Ur)),le(this,Ur,void 0)),typeof t=="function"&&(le(this,Ur,t),this.addEventListener("addrendition",t))}get onremoverendition(){return M(this,Fr)}set onremoverendition(t){M(this,Fr)&&(this.removeEventListener("removerendition",M(this,Fr)),le(this,Fr,void 0)),typeof t=="function"&&(le(this,Fr,t),this.addEventListener("removerendition",t))}get onchange(){return M(this,Br)}set onchange(t){M(this,Br)&&(this.removeEventListener("change",M(this,Br)),le(this,Br,void 0)),typeof t=="function"&&(le(this,Br,t),this.addEventListener("change",t))}};Ur=new WeakMap,Fr=new WeakMap,Br=new WeakMap;var Da,Ul=class{constructor(){Oe(this,"src");Oe(this,"id");Oe(this,"bitrate");Oe(this,"codec");fe(this,Da,!1)}get selected(){return M(this,Da)}set selected(e){M(this,Da)!==e&&(le(this,Da,e),hS(this))}};Da=new WeakMap;function Vc(i,e){let t=i.audioTracks;J(e).media=new WeakRef(i),J(e).renditionSet||(J(e).renditionSet=new Set);let s=J(t).trackSet;s.add(e);let r=s.size-1;r in Cn.prototype||Object.defineProperty(Cn.prototype,r,{get(){return[...J(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Js("addtrack",{track:e}))})}function Wc(i){var s,r;let e=(r=(s=J(i).media)==null?void 0:s.deref())==null?void 0:r.audioTracks;if(!e)return;J(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Js("removetrack",{track:i}))})}function fS(i){var t,s;let e=(s=(t=J(i).media)==null?void 0:t.deref())==null?void 0:s.audioTracks;!e||J(e).changeRequested||(J(e).changeRequested=!0,queueMicrotask(()=>{delete J(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var $r,Hr,Gr,Ca,Kc,Cn=class extends EventTarget{constructor(){super();fe(this,Ca);fe(this,$r);fe(this,Hr);fe(this,Gr);J(this).trackSet=new Set}[Symbol.iterator](){return M(this,Ca,Kc).values()}get length(){return M(this,Ca,Kc).size}getTrackById(t){var s;return(s=[...M(this,Ca,Kc)].find(r=>r.id===t))!=null?s:null}get onaddtrack(){return M(this,$r)}set onaddtrack(t){M(this,$r)&&(this.removeEventListener("addtrack",M(this,$r)),le(this,$r,void 0)),typeof t=="function"&&(le(this,$r,t),this.addEventListener("addtrack",t))}get onremovetrack(){return M(this,Hr)}set onremovetrack(t){M(this,Hr)&&(this.removeEventListener("removetrack",M(this,Hr)),le(this,Hr,void 0)),typeof t=="function"&&(le(this,Hr,t),this.addEventListener("removetrack",t))}get onchange(){return M(this,Gr)}set onchange(t){M(this,Gr)&&(this.removeEventListener("change",M(this,Gr)),le(this,Gr,void 0)),typeof t=="function"&&(le(this,Gr,t),this.addEventListener("change",t))}};$r=new WeakMap,Hr=new WeakMap,Gr=new WeakMap,Ca=new WeakSet,Kc=function(){return J(this).trackSet};var wa,Ma=class{constructor(){Oe(this,"id");Oe(this,"kind");Oe(this,"label","");Oe(this,"language","");Oe(this,"sourceBuffer");fe(this,wa,!1)}addRendition(e,t,s){let r=new Ul;return r.src=e,r.codec=t,r.bitrate=s,uS(this,r),r}removeRendition(e){cS(e)}get enabled(){return M(this,wa)}set enabled(e){M(this,wa)!==e&&(le(this,wa,e),fS(this))}};wa=new WeakMap;var mS=qc(globalThis.HTMLMediaElement,"video"),pS=qc(globalThis.HTMLMediaElement,"audio");function gS(i){if(!(i!=null&&i.prototype))return i;let e=qc(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return wO(this)}});let t=qc(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return MO(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){let l=new xa;return l.kind=n,l.label=a,l.language=o,Hc(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=Gc),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){let l=new Ma;return l.kind=n,l.label=a,l.language=o,Vc(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=Wc),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});let s=n=>{let a=J(n).videoRenditions;return a||(a=new kn,J(a).media=new WeakRef(n),J(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=J(n).audioRenditions;return a||(a=new Dn,J(a).media=new WeakRef(n),J(n).audioRenditions=a),a};return i}function qc(i,e){var t;if(i!=null&&i.prototype)return(t=Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`))==null?void 0:t.get}function wO(i){var t;let e=J(i).videoTracks;if(!e&&(e=new xn,J(i).videoTracks=e,mS)){let s=mS.call((t=i.nativeEl)!=null?t:i);for(let o of s)Hc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof xa)){for(let l of s)Gc(l);return}Hc(i,o.track)},a=o=>{Gc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}function MO(i){var t;let e=J(i).audioTracks;if(!e&&(e=new Cn,J(i).audioTracks=e,pS)){let s=pS.call((t=i.nativeEl)!=null?t:i);for(let o of s)Vc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof Ma)){for(let l of s)Wc(l);return}Vc(i,o.track)},a=o=>{Wc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}var ES=i=>{throw TypeError(i)},yS=(i,e,t)=>e.has(i)||ES("Cannot "+t),bS=(i,e,t)=>(yS(i,e,"read from private field"),t?t.call(i):e.get(i)),TS=(i,e,t)=>e.has(i)?ES("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),_S=(i,e,t,s)=>(yS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends zc{}globalThis.DocumentFragment=i}var q0=class extends zc{},PO=class extends zc{},OO={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(q0)}},Yc,NO=class{constructor(i,e={}){TS(this,Yc),_S(this,Yc,e==null?void 0:e.detail)}get detail(){return bS(this,Yc)}initCustomEvent(){}};Yc=new WeakMap;function UO(i,e){return new q0}var AS={document:{createElement:UO},DocumentFragment,customElements:OO,CustomEvent:NO,EventTarget:zc,HTMLElement:q0,HTMLVideoElement:PO},SS=typeof window=="undefined"||typeof globalThis.customElements=="undefined",W0=SS?AS:globalThis,O4=SS?AS.document:globalThis.document,jc,vS=class extends rS(gS(GA)){constructor(){super(...arguments),TS(this,jc)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):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 i;return(i=bS(this,jc))!=null?i:this.muxCastCustomData}set castCustomData(i){_S(this,jc,i)}};jc=new WeakMap;W0.customElements.get("mux-video")||(W0.customElements.define("mux-video",vS),W0.MuxVideoElement=vS);var Y={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},Le={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Y0={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},IS=Object.entries(Y0),A=IS.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),FO={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},Ri=IS.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...FO}),q4=Object.entries(Ri).reduce((i,[e,t])=>{let s=A[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"}),RS=Object.entries(A).reduce((i,[e,t])=>{let s=Ri[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),hi={SUBTITLES:"subtitles",CAPTIONS:"captions",DESCRIPTIONS:"descriptions",CHAPTERS:"chapters",METADATA:"metadata"},Kr={DISABLED:"disabled",HIDDEN:"hidden",SHOWING:"showing"};var Qc={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},fi={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},Xi={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var LS={INLINE:"inline",FULLSCREEN:"fullscreen",PICTURE_IN_PICTURE:"picture-in-picture"};function xS(i){return i==null?void 0:i.map($O).join(" ")}function kS(i){return i==null?void 0:i.split(/\s+/).map(HO)}function $O(i){if(i){let{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function HO(i){if(i){let[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function DS(i){return i==null?void 0:i.map(GO).join(" ")}function CS(i){return i==null?void 0:i.split(/\s+/).map(KO)}function GO(i){if(i){let{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function KO(i){if(i){let[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function wS(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Pa(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function Xc(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}var Zc=i=>new Promise(e=>setTimeout(e,i));var MS={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it.",hour:"hour",hours:"hours",minute:"minute",minutes:"minutes",second:"second",seconds:"seconds","{time} remaining":"{time} remaining","{currentTime} of {totalTime}":"{currentTime} of {totalTime}","video not loaded, unknown time.":"video not loaded, unknown time."};var PS,Fl={en:MS},Oa=((PS=globalThis.navigator)==null?void 0:PS.language)||"en",OS=i=>{Oa=i};var VO=i=>{var e,t,s;let[r]=Oa.split("-");return((e=Fl[Oa])==null?void 0:e[i])||((t=Fl[r])==null?void 0:t[i])||((s=Fl.en)==null?void 0:s[i])||i},NS=()=>{let[i]=Oa.split("-");return Fl[Oa]?Oa:Fl[i]?i:"en"},G=(i,e={})=>VO(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);var US=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],FS=(i,e)=>{let t=i===1?G(US[e].singular):G(US[e].plural);return`${i} ${t}`},wn=i=>{if(!Pa(i))return"";let e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0),n=[s.getHours(),s.getMinutes(),s.getSeconds()].map((a,o)=>a&&FS(a,o)).filter(a=>a).join(", ");return t?G("{time} remaining",{time:n}):e===0?FS(0,2):n};function Zi(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}var J4=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}});var Jc=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}},eh=class extends Jc{},th=class extends eh{constructor(){super(...arguments),this.role=null}},j0=class{observe(){}unobserve(){}disconnect(){}},BS={createElement:function(){return new Bl.HTMLElement},createElementNS:function(){return new Bl.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},Bl={ResizeObserver:j0,document:BS,Node:eh,Element:th,HTMLElement:class extends th{constructor(){super(...arguments),this.innerHTML=""}get content(){return new Bl.DocumentFragment}},DocumentFragment:class extends Jc{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},$S="global"in globalThis&&(globalThis==null?void 0:globalThis.global)===globalThis||typeof window=="undefined"||typeof window.customElements=="undefined",HS=Object.keys(Bl).every(i=>i in globalThis),L=$S&&!HS?Bl:globalThis,et=$S&&!HS?BS:globalThis.document;var GS=new WeakMap,z0=i=>{let e=GS.get(i);return e||GS.set(i,e=new Set),e},KS=new L.ResizeObserver(i=>{for(let e of i)for(let t of z0(e.target))t(e)});function tr(i,e){z0(i).add(e),KS.observe(i)}function ir(i,e){let t=z0(i);t.delete(e),t.size||KS.unobserve(i)}function lt(i){let e={};for(let t of i)e[t.name]=t.value;return e}function nt(i){var e;return(e=ih(i))!=null?e:Es(i,"media-controller")}function ih(i){var e;let{MEDIA_CONTROLLER:t}=Le,s=i.getAttribute(t);if(s)return(e=Mn(i))==null?void 0:e.getElementById(s)}var sh=(i,e,t=".value")=>{let s=i.querySelector(t);s&&(s.textContent=e)},qO=(i,e)=>{let t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},rh=(i,e)=>qO(i,e)[0],ni=(i,e)=>!i||!e?!1:i!=null&&i.contains(e)?!0:ni(i,e.getRootNode().host),Es=(i,e)=>{if(!i)return null;let t=i.closest(e);return t||Es(i.getRootNode().host,e)};function $l(i=document){var e;let t=i==null?void 0:i.activeElement;return t?(e=$l(t.shadowRoot))!=null?e:t:null}function Mn(i){var e;let t=(e=i==null?void 0:i.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function nh(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){let n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function VS(i,e,t,s){let r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;let o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function at(i,e){let t=YO(i,s=>s===e);return t||Hl(i,e)}function YO(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(let a of n!=null?n:[])if(e(a.selectorText))return a}}function Hl(i,e){var t,s;let r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r==null?void 0:r[r.length-1];if(!(n!=null&&n.sheet))return console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}};let a=n==null?void 0:n.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length);return(s=n.sheet.cssRules)==null?void 0:s[a]}function De(i,e,t=Number.NaN){let s=i.getAttribute(e);return s!=null?+s:t}function Ue(i,e,t){let s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}De(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function pe(i,e){return i.hasAttribute(e)}function ge(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}pe(i,e)!=t&&i.toggleAttribute(e,t)}function Se(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function Ae(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}let s=`${t}`;Se(i,e,void 0)!==s&&i.setAttribute(e,s)}var WS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ji=(i,e,t)=>(WS(i,e,"read from private field"),t?t.call(i):e.get(i)),jO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},ah=(i,e,t,s)=>(WS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zt;function zO(i){return`
|
|
144
144
|
<style>
|
|
145
145
|
:host {
|
|
146
146
|
display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));
|
|
@@ -298,7 +298,7 @@ Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
298
298
|
<slot part="bottom chrome"></slot>
|
|
299
299
|
</span>
|
|
300
300
|
<slot name="dialog" part="layer dialog-layer"></slot>
|
|
301
|
-
`}var ZO=Object.values(A),JO="sm:384 md:576 lg:768 xl:960";function eN(i){jS(i.target,i.contentRect.width)}function jS(i,e){var t;if(!i.isConnected)return;let s=(t=i.getAttribute(he.BREAKPOINTS))!=null?t:JO,r=tN(s),n=iN(r,e),a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){let o=new CustomEvent(Ri.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(Ri.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function tN(i){let e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function iN(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}var Pn=class extends L.HTMLElement{constructor(){if(super(),ai(this,X0),ai(this,Z0),ai(this,Kl),ai(this,hh),ai(this,Ha),ai(this,Gl,void 0),ai(this,uh,0),ai(this,Ua,null),ai(this,$a,null),ai(this,Ba,void 0),this.breakpointsComputed=!1,ai(this,Q0,e=>{let t=this.media;for(let s of e){if(s.type!=="childList")continue;let r=s.removedNodes;for(let n of r){if(n.slot!="media"||s.target!=this)continue;let a=s.previousSibling&&s.previousSibling.previousElementSibling;if(!a||!t)this.mediaUnsetCallback(n);else{let o=a.slot!=="media";for(;(a=a.previousSibling)!==null;)a.slot=="media"&&(o=!1);o&&this.mediaUnsetCallback(n)}}if(t)for(let n of s.addedNodes)n===t&&this.handleMediaUpdated(t)}}),ai(this,Fa,!1),ai(this,lh,e=>{It(this,Fa)||(setTimeout(()=>{eN(e),es(this,Fa,!1)},0),es(this,Fa,!0))}),ai(this,Vr,void 0),ai(this,dh,()=>{if(!It(this,Vr).assignedElements({flatten:!0}).length){It(this,Ua)&&this.mediaUnsetCallback(It(this,Ua));return}this.handleMediaUpdated(this.media)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=lt(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t}es(this,Gl,new MutationObserver(It(this,Q0)))}static get observedAttributes(){return[he.AUTOHIDE,he.GESTURES_DISABLED].concat(ZO).filter(e=>![A.MEDIA_RENDITION_LIST,A.MEDIA_AUDIO_TRACK_LIST,A.MEDIA_CHAPTERS_CUES,A.MEDIA_WIDTH,A.MEDIA_HEIGHT,A.MEDIA_ERROR,A.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==he.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return(e==null?void 0:e.nodeName)=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(es(this,Ua,e),e.localName.includes("-")&&await L.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;It(this,Gl).observe(this,{childList:!0,subtree:!0}),tr(this,It(this,lh));let s=this.getAttribute(he.AUDIO)!=null?G("audio player"):G("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(he.USER_INACTIVE,""),jS(this,this.getBoundingClientRect().width);let r=this.querySelector(":scope > slot[slot=media]");r&&(es(this,Vr,r),It(this,Vr).addEventListener("slotchange",It(this,dh))),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=L.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;ir(this,It(this,lh)),clearTimeout(It(this,$a)),It(this,Gl).disconnect(),this.media&&this.mediaUnsetCallback(this.media),(e=L.window)==null||e.removeEventListener("mouseup",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointermove",this),this.removeEventListener("pointerup",this),this.removeEventListener("mouseleave",this),this.removeEventListener("keyup",this),It(this,Vr)&&(It(this,Vr).removeEventListener("slotchange",It(this,dh)),es(this,Vr,null)),es(this,Fa,!1)}mediaSetCallback(e){}mediaUnsetCallback(e){es(this,Ua,null)}handleEvent(e){switch(e.type){case"pointerdown":es(this,uh,e.timeStamp);break;case"pointermove":ts(this,X0,qS).call(this,e);break;case"pointerup":ts(this,Z0,YS).call(this,e);break;case"mouseleave":ts(this,Kl,ch).call(this);break;case"mouseup":this.removeAttribute(he.KEYBOARD_CONTROL);break;case"keyup":ts(this,Ha,Vl).call(this),this.setAttribute(he.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);es(this,Ba,isNaN(t)?0:t)}get autohide(){return(It(this,Ba)===void 0?2:It(this,Ba)).toString()}get breakpoints(){return Se(this,he.BREAKPOINTS)}set breakpoints(e){Ae(this,he.BREAKPOINTS,e)}get audio(){return pe(this,he.AUDIO)}set audio(e){ge(this,he.AUDIO,e)}get gesturesDisabled(){return pe(this,he.GESTURES_DISABLED)}set gesturesDisabled(e){ge(this,he.GESTURES_DISABLED,e)}get keyboardControl(){return pe(this,he.KEYBOARD_CONTROL)}set keyboardControl(e){ge(this,he.KEYBOARD_CONTROL,e)}get noAutohide(){return pe(this,he.NO_AUTOHIDE)}set noAutohide(e){ge(this,he.NO_AUTOHIDE,e)}get autohideOverControls(){return pe(this,he.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){ge(this,he.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return pe(this,he.USER_INACTIVE)}set userInteractive(e){ge(this,he.USER_INACTIVE,e)}};Gl=new WeakMap;uh=new WeakMap;Ua=new WeakMap;$a=new WeakMap;Ba=new WeakMap;Q0=new WeakMap;Fa=new WeakMap;lh=new WeakMap;X0=new WeakSet;qS=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-It(this,uh)<250)return;ts(this,hh,ev).call(this),clearTimeout(It(this,$a));let e=this.hasAttribute(he.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&ts(this,Ha,Vl).call(this)};Z0=new WeakSet;YS=function(i){if(i.pointerType==="touch"){let e=!this.hasAttribute(he.USER_INACTIVE);[this,this.media].includes(i.target)&&e?ts(this,Kl,ch).call(this):ts(this,Ha,Vl).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e==null?void 0:e.localName))&&ts(this,Ha,Vl).call(this)};Kl=new WeakSet;ch=function(){if(It(this,Ba)<0||this.hasAttribute(he.USER_INACTIVE))return;this.setAttribute(he.USER_INACTIVE,"");let i=new L.CustomEvent(Ri.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};hh=new WeakSet;ev=function(){if(!this.hasAttribute(he.USER_INACTIVE))return;this.removeAttribute(he.USER_INACTIVE);let i=new L.CustomEvent(Ri.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};Ha=new WeakSet;Vl=function(){ts(this,hh,ev).call(this),clearTimeout(It(this,$a));let i=parseInt(this.autohide);i<0||es(this,$a,setTimeout(()=>{ts(this,Kl,ch).call(this)},i*1e3))};Vr=new WeakMap;dh=new WeakMap;Pn.shadowRootOptions={mode:"open"};Pn.getTemplateHTML=XO;L.customElements.get("media-container")||L.customElements.define("media-container",Pn);var zS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Kt=(i,e,t)=>(zS(i,e,"read from private field"),t?t.call(i):e.get(i)),Wl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},fh=(i,e,t,s)=>(zS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ga,Ka,mh,On,sr,Wr,qr=class{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){Wl(this,sr),Wl(this,Ga,void 0),Wl(this,Ka,void 0),Wl(this,mh,void 0),Wl(this,On,new Set),fh(this,Ga,e),fh(this,Ka,t),fh(this,mh,new Set(s))}[Symbol.iterator](){return Kt(this,sr,Wr).values()}get length(){return Kt(this,sr,Wr).size}get value(){var e;return(e=[...Kt(this,sr,Wr)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(fh(this,On,new Set),this.add(...(t=e==null?void 0:e.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...Kt(this,sr,Wr)][e]}values(){return Kt(this,sr,Wr).values()}forEach(e,t){Kt(this,sr,Wr).forEach(e,t)}add(...e){var t,s;e.forEach(r=>Kt(this,On).add(r)),!(this.value===""&&!((t=Kt(this,Ga))!=null&&t.hasAttribute(`${Kt(this,Ka)}`)))&&((s=Kt(this,Ga))==null||s.setAttribute(`${Kt(this,Ka)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>Kt(this,On).delete(s)),(t=Kt(this,Ga))==null||t.setAttribute(`${Kt(this,Ka)}`,`${this.value}`)}contains(e){return Kt(this,sr,Wr).has(e)}toggle(e,t){return typeof t!="undefined"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){return this.remove(e),this.add(t),e===t}};Ga=new WeakMap;Ka=new WeakMap;mh=new WeakMap;On=new WeakMap;sr=new WeakSet;Wr=function(){return Kt(this,On).size?Kt(this,On):Kt(this,mh)};var sN=(i="")=>i.split(/\s+/),QS=(i="")=>{let[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?hi.CAPTIONS:hi.SUBTITLES,language:t,label:r}},Nn=(i="",e={})=>sN(i).map(t=>{let s=QS(t);return{...e,...s}}),tv=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?QS(e):e):typeof i=="string"?Nn(i):[i]:[],ph=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,rr=(i=[])=>Array.prototype.map.call(i,ph).join(" "),rN=(i,e)=>t=>t[i]===e,XS=i=>{let e=Object.entries(i).map(([t,s])=>rN(t,s));return t=>e.every(s=>s(t))},Un=(i,e=[],t=[])=>{let s=tv(t).map(XS),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},Fn=(i,e=()=>!0)=>{if(!(i!=null&&i.textTracks))return[];let t=typeof e=="function"?e:XS(e);return Array.from(i.textTracks).filter(t)},gh=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(A.MEDIA_SUBTITLES_SHOWING)};var JS=i=>{var e;let{media:t,fullscreenElement:s}=i;try{let r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){let n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t!=null&&t.webkitEnterFullscreen?t.webkitEnterFullscreen():t!=null&&t.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},ZS="exitFullscreen"in et?"exitFullscreen":"webkitExitFullscreen"in et?"webkitExitFullscreen":"webkitCancelFullScreen"in et?"webkitCancelFullScreen":void 0,e1=i=>{var e;let{documentElement:t}=i;if(ZS){let s=(e=t==null?void 0:t[ZS])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},ql="fullscreenElement"in et?"fullscreenElement":"webkitFullscreenElement"in et?"webkitFullscreenElement":void 0,nN=i=>{let{documentElement:e,media:t}=i,s=e==null?void 0:e[ql];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===LS.FULLSCREEN?t:s},t1=i=>{var e;let{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;let n=nN(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(ql in a))return ni(n,r);for(;a!=null&&a[ql];){if(a[ql]===r)return!0;a=(e=a[ql])==null?void 0:e.shadowRoot}}return!1},aN="fullscreenEnabled"in et?"fullscreenEnabled":"webkitFullscreenEnabled"in et?"webkitFullscreenEnabled":void 0,i1=i=>{let{documentElement:e,media:t}=i;return!!(e!=null&&e[aN])||t&&"webkitSupportsFullscreen"in t};var vh,iv=()=>{var i,e;return vh||(vh=(e=(i=et)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),vh)},s1=async(i=iv())=>{if(!i)return!1;let e=i.volume;i.volume=e/2+.1;let t=new AbortController,s=await Promise.race([oN(i,t.signal),lN(i,e)]);return t.abort(),s},oN=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),lN=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await Zc(10)}return i.volume!==e},dN=/.*Version\/.*Safari\/.*/.test(L.navigator.userAgent),sv=(i=iv())=>L.matchMedia("(display-mode: standalone)").matches&&dN?!1:typeof(i==null?void 0:i.requestPictureInPicture)=="function",rv=(i=iv())=>i1({documentElement:et,media:i}),r1=rv(),n1=sv(),a1=!!L.WebKitPlaybackTargetAvailabilityEvent,o1=!!L.chrome;var Va=i=>Fn(i.media,e=>[hi.SUBTITLES,hi.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),nv=i=>Fn(i.media,e=>e.mode===Kr.SHOWING&&[hi.SUBTITLES,hi.CAPTIONS].includes(e.kind)),Eh=(i,e)=>{let t=Va(i),s=nv(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)Un(Kr.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0],{options:a}=i;if(!(a!=null&&a.noSubtitlesLangPref)){let u=L.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...L.navigator.languages]:L.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}let{language:o,label:l,kind:d}=n;Un(Kr.DISABLED,t,s),Un(Kr.SHOWING,t,[{language:o,label:l,kind:d}])}}},yh=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?uN(i,e):Object.entries(i).every(([t,s])=>t in e&&yh(s,e[t])),uN=(i,e)=>{let t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>yh(r,e[n])):!0};var cN=Object.values(Xi),bh,hN=s1().then(i=>(bh=i,bh)),l1=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof L.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let s=L.customElements.get(t);s&&e instanceof s||(await L.customElements.whenDefined(t),L.customElements.upgrade(e))}))},fN=new L.DOMParser,mN=i=>i&&(fN.parseFromString(i,"text/html").body.textContent||i),Wa={mediaError:{get(i,e){let{media:t}=i;if((e==null?void 0:e.type)!=="playing")return t==null?void 0:t.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;let{media:s}=i;if((e==null?void 0:e.type)!=="playing")return(t=s==null?void 0:s.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;let{media:r}=i;if((e==null?void 0:e.type)!=="playing")return(s=(t=r==null?void 0:r.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.paused)!=null?e:!0},set(i,e){var t;let{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){let{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.playbackRate)!=null?e:1},set(i,e){let{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.muted)!=null?e:!1},set(i,e){let{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{let r=L.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&L.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;L.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{let r=L.localStorage.getItem("media-chrome-pref-muted")==="true";Wa.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){let{media:e}=i;return e==null?void 0:e.loop},set(i,e){let{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.volume)!=null?e:1},set(i,e){let{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?L.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&L.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:s}=e;if(!s)return;let r=L.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Wa.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){let{media:e}=i;return typeof(e==null?void 0:e.volume)=="undefined"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.currentTime)!=null?e:0},set(i,e){let{media:t}=e;!t||!Pa(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata","seeking"]},mediaDuration:{get(i){let{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e==null?void 0:e.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){let{media:e}=i;return(e==null?void 0:e.readyState)<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;let{media:t}=i;if(!((e=t==null?void 0:t.seekable)!=null&&e.length))return;let s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;let{media:t}=i,s=(e=t==null?void 0:t.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){let{media:e,options:{defaultStreamType:t}={}}=i,s=[Xi.LIVE,Xi.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;let{streamType:r}=e;if(cN.includes(r))return r===Xi.UNKNOWN?s:r;let n=e.duration;return n===1/0?Xi.LIVE:Number.isFinite(n)?Xi.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){let{media:e}=i;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,s=Wa.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===Xi.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){let{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Wa.mediaStreamType.get(i)===Xi.LIVE))return!1;let r=e.seekable;if(!r)return!0;if(!r.length)return!1;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return Va(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return nv(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![hi.CAPTIONS,hi.SUBTITLES].includes((l=o==null?void 0:o.track)==null?void 0:l.kind)||Eh(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;let{media:t}=i;if(!t)return[];let[s]=Fn(t,{kind:hi.CHAPTERS});return Array.from((e=s==null?void 0:s.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:mN(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;if(!s)return;let r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r==null||r.addEventListener("load",i),n==null||n.addEventListener("load",i),()=>{r==null||r.removeEventListener("load",i),n==null||n.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;let{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?ni(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n!=null&&n.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){let{media:t}=e;if(t)if(i){if(!et.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else et.pictureInPictureElement&&et.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;let{media:r}=i;return(s=(t=r==null?void 0:r.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.videoRenditions)){console.warn("MediaController: Rendition selection not supported by this media.");return}let s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;let{media:s}=i;return(t=[...(e=s==null?void 0:s.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.audioTracks)){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let s=i;for(let r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return t1(i)},set(i,e,t){var s,r;i?(JS(e),t.detail&&!((s=e.media)!=null&&s.inert)&&((r=e.media)==null||r.focus())):e1(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;let{media:t}=i;return!(t!=null&&t.remote)||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:t.remote.state==="connected"},set(i,e){var t,s;let{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&L.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){let{media:e}=i;if(!r1||!rv(e))return fi.UNSUPPORTED}},mediaPipUnavailable:{get(i){let{media:e}=i;if(!n1||!sv(e))return fi.UNSUPPORTED;if(e!=null&&e.disablePictureInPicture)return fi.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){let{media:e}=i;if(bh===!1||(e==null?void 0:e.volume)==null)return fi.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{bh==null&&hN.then(e=>i(e?void 0:fi.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;let{media:s}=i;if(!o1||!((t=s==null?void 0:s.remote)!=null&&t.state))return fi.UNSUPPORTED;if(!(e==null||e==="available"))return fi.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!a1)return fi.UNSUPPORTED;if((e==null?void 0:e.availability)==="not-available")return fi.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;let{media:t}=i;if(!(t!=null&&t.videoRenditions))return fi.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return fi.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;let{media:s}=i;if(!(s!=null&&s.audioTracks))return fi.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return fi.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){let{options:{mediaLang:e}={}}=i;return e!=null?e:"en"}}};var d1={[Y.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;let{media:a}=e,o=t!=null?t:void 0,l,d;if(a&&o!=null){let[f]=Fn(a,{kind:hi.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f==null?void 0:f.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a==null?void 0:a.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(b=>+b),l=g.href}}let u=i.mediaDuration.get(e),h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[Y.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[Y.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;let a="mediaPaused",l=i.mediaStreamType.get(e)===Xi.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){let c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[Y.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){let s="mediaPlaybackRate",r=t;i[s].set(r,e)},[Y.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[Y.MEDIA_UNMUTE_REQUEST](i,e){let t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[Y.MEDIA_LOOP_REQUEST](i,e,{detail:t}){let s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[Y.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){let s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[Y.MEDIA_SEEK_REQUEST](i,e,{detail:t}){let s="mediaCurrentTime",r=t;i[s].set(r,e)},[Y.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;let n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[Y.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;let{options:r}=e,n=Va(e),a=tv(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&L.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Un(Kr.SHOWING,n,a)},[Y.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){let s=Va(e),r=t!=null?t:[];Un(Kr.DISABLED,s,r)},[Y.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){Eh(e,t)},[Y.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){let s="mediaRenditionSelected",r=t;i[s].set(r,e)},[Y.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){let s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[Y.MEDIA_ENTER_PIP_REQUEST](i,e){let t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Y.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[Y.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){let s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[Y.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[Y.MEDIA_ENTER_CAST_REQUEST](i,e){let t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Y.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[Y.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}};var u1=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Wa,requestMap:r=d1,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),u=p=>{p!=null&&(yh(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{let p=Object.entries(s).reduce((g,[v,{get:b}])=>(g[v]=b(l),g),{});u(p)},h={},f,m=async(p,g)=>{var v,b,E,T,_,I,S,x,k,R,D,w,N,$,H,O;let F=!!f;if(f={...l,...f!=null?f:{},...p},F)return;await l1(...Object.values(p));let B=o.length>0&&g===0&&a,W=l.media!==f.media,Z=((v=l.media)==null?void 0:v.textTracks)!==((b=f.media)==null?void 0:b.textTracks),K=((E=l.media)==null?void 0:E.videoRenditions)!==((T=f.media)==null?void 0:T.videoRenditions),q=((_=l.media)==null?void 0:_.audioTracks)!==((I=f.media)==null?void 0:I.audioTracks),ce=((S=l.media)==null?void 0:S.remote)!==((x=f.media)==null?void 0:x.remote),se=l.documentElement!==f.documentElement,ye=!!l.media&&(W||B),ue=!!((k=l.media)!=null&&k.textTracks)&&(Z||B),Ce=!!((R=l.media)!=null&&R.videoRenditions)&&(K||B),Te=!!((D=l.media)!=null&&D.audioTracks)&&(q||B),Ne=!!((w=l.media)!=null&&w.remote)&&(ce||B),mt=!!l.documentElement&&(se||B),Ft=ye||ue||Ce||Te||Ne||mt,Zt=o.length===0&&g===1&&a,Xe=!!f.media&&(W||Zt),ei=!!((N=f.media)!=null&&N.textTracks)&&(Z||Zt),yi=!!(($=f.media)!=null&&$.videoRenditions)&&(K||Zt),ie=!!((H=f.media)!=null&&H.audioTracks)&&(q||Zt),xe=!!((O=f.media)!=null&&O.remote)&&(ce||Zt),we=!!f.documentElement&&(se||Zt),pt=Xe||ei||yi||ie||xe||we;if(!(Ft||pt)){Object.entries(f).forEach(([Ie,Wt])=>{l[Ie]=Wt}),c(),f=void 0;return}Object.entries(s).forEach(([Ie,{get:Wt,mediaEvents:Gs=[],textTracksEvents:Pt=[],videoRenditionsEvents:qt=[],audioTracksEvents:di=[],remoteEvents:ti=[],rootEvents:Bt=[],stateOwnersUpdateHandlers:ls=[]}])=>{h[Ie]||(h[Ie]={});let vt=ct=>{let xt=Wt(l,ct);u({[Ie]:xt})},je;je=h[Ie].mediaEvents,Gs.forEach(ct=>{je&&ye&&(l.media.removeEventListener(ct,je),h[Ie].mediaEvents=void 0),Xe&&(f.media.addEventListener(ct,vt),h[Ie].mediaEvents=vt)}),je=h[Ie].textTracksEvents,Pt.forEach(ct=>{var xt,$i;je&&ue&&((xt=l.media.textTracks)==null||xt.removeEventListener(ct,je),h[Ie].textTracksEvents=void 0),ei&&(($i=f.media.textTracks)==null||$i.addEventListener(ct,vt),h[Ie].textTracksEvents=vt)}),je=h[Ie].videoRenditionsEvents,qt.forEach(ct=>{var xt,$i;je&&Ce&&((xt=l.media.videoRenditions)==null||xt.removeEventListener(ct,je),h[Ie].videoRenditionsEvents=void 0),yi&&(($i=f.media.videoRenditions)==null||$i.addEventListener(ct,vt),h[Ie].videoRenditionsEvents=vt)}),je=h[Ie].audioTracksEvents,di.forEach(ct=>{var xt,$i;je&&Te&&((xt=l.media.audioTracks)==null||xt.removeEventListener(ct,je),h[Ie].audioTracksEvents=void 0),ie&&(($i=f.media.audioTracks)==null||$i.addEventListener(ct,vt),h[Ie].audioTracksEvents=vt)}),je=h[Ie].remoteEvents,ti.forEach(ct=>{var xt,$i;je&&Ne&&((xt=l.media.remote)==null||xt.removeEventListener(ct,je),h[Ie].remoteEvents=void 0),xe&&(($i=f.media.remote)==null||$i.addEventListener(ct,vt),h[Ie].remoteEvents=vt)}),je=h[Ie].rootEvents,Bt.forEach(ct=>{je&&mt&&(l.documentElement.removeEventListener(ct,je),h[Ie].rootEvents=void 0),we&&(f.documentElement.addEventListener(ct,vt),h[Ie].rootEvents=vt)});let un=h[Ie].stateOwnersUpdateHandlers;if(un&&Ft&&(Array.isArray(un)?un:[un]).forEach(xt=>{typeof xt=="function"&&xt()}),pt){let ct=ls.map(xt=>xt(vt,f)).filter(xt=>typeof xt=="function");h[Ie].stateOwnersUpdateHandlers=ct.length===1?ct[0]:ct}else Ft&&(h[Ie].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([Ie,Wt])=>{l[Ie]=Wt}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v!=null?v:{}).forEach(([b,E])=>{l.options[b]=E}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var uv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},de=(i,e,t)=>(uv(i,e,"read from private field"),t?t.call(i):e.get(i)),Pi=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},is=(i,e,t,s)=>(uv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Yl=(i,e,t)=>(uv(i,e,"access private method"),t),nr,jl,Fe,bs,zl,ys,Th,Ql,_h,av,$n,Ah,ov,lv,v1,E1=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],c1=10,h1=.025,f1=.25,pN=.25,gN=2,j={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"},Sh=class extends Pn{constructor(){super(),Pi(this,_h),Pi(this,Ah),Pi(this,lv),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,Pi(this,nr,new qr(this,j.HOTKEYS)),Pi(this,jl,void 0),Pi(this,Fe,void 0),Pi(this,bs,null),Pi(this,zl,void 0),Pi(this,ys,void 0),Pi(this,Th,t=>{var s;(s=de(this,Fe))==null||s.dispatch(t)}),Pi(this,Ql,void 0),Pi(this,$n,t=>{let{key:s,shiftKey:r}=t;if(!(r&&(s==="/"||s==="?")||E1.includes(s))){this.removeEventListener("keyup",de(this,$n));return}this.keyboardShortcutHandler(t)}),this.associateElement(this);let e={};is(this,zl,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);let n=s.toLowerCase(),a=new L.CustomEvent(RS[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t})}static get observedAttributes(){return super.observedAttributes.concat(j.NO_HOTKEYS,j.HOTKEYS,j.DEFAULT_STREAM_TYPE,j.DEFAULT_SUBTITLES,j.DEFAULT_DURATION,j.NO_MUTED_PREF,j.NO_VOLUME_PREF,j.LANG,j.LOOP,j.LIVE_EDGE_OFFSET,j.SEEK_TO_LIVE_OFFSET,j.NO_AUTO_SEEK_TO_LIVE)}get mediaStore(){return de(this,Fe)}set mediaStore(e){var t,s;if(de(this,Fe)&&((t=de(this,ys))==null||t.call(this),is(this,ys,void 0)),is(this,Fe,e),!de(this,Fe)&&!this.hasAttribute(j.NO_DEFAULT_STORE)){Yl(this,_h,av).call(this);return}is(this,ys,(s=de(this,Fe))==null?void 0:s.subscribe(de(this,zl)))}get fullscreenElement(){var e;return(e=de(this,jl))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(j.FULLSCREEN_ELEMENT)&&this.removeAttribute(j.FULLSCREEN_ELEMENT),is(this,jl,e),(t=de(this,Fe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return pe(this,j.DEFAULT_SUBTITLES)}set defaultSubtitles(e){ge(this,j.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return Se(this,j.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){Ae(this,j.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return De(this,j.DEFAULT_DURATION)}set defaultDuration(e){Ue(this,j.DEFAULT_DURATION,e)}get noHotkeys(){return pe(this,j.NO_HOTKEYS)}set noHotkeys(e){ge(this,j.NO_HOTKEYS,e)}get keysUsed(){return Se(this,j.KEYS_USED)}set keysUsed(e){Ae(this,j.KEYS_USED,e)}get liveEdgeOffset(){return De(this,j.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Ue(this,j.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return pe(this,j.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){ge(this,j.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return pe(this,j.NO_VOLUME_PREF)}set noVolumePref(e){ge(this,j.NO_VOLUME_PREF,e)}get noMutedPref(){return pe(this,j.NO_MUTED_PREF)}set noMutedPref(e){ge(this,j.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return pe(this,j.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){ge(this,j.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return pe(this,j.NO_DEFAULT_STORE)}set noDefaultStore(e){ge(this,j.NO_DEFAULT_STORE,e)}get resolvedLang(){return NS()}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===j.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(j.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===j.HOTKEYS)de(this,nr).value=s;else if(e===j.DEFAULT_SUBTITLES&&s!==t)(r=de(this,Fe))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(j.DEFAULT_SUBTITLES)}});else if(e===j.DEFAULT_STREAM_TYPE)(a=de(this,Fe))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(j.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===j.LIVE_EDGE_OFFSET&&s!==t)(o=de(this,Fe))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0}});else if(e===j.SEEK_TO_LIVE_OFFSET&&s!==t)(l=de(this,Fe))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0}});else if(e===j.NO_AUTO_SEEK_TO_LIVE)(d=de(this,Fe))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(j.NO_AUTO_SEEK_TO_LIVE)}});else if(e===j.FULLSCREEN_ELEMENT){let g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;is(this,jl,g),(c=de(this,Fe))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===j.LANG&&s!==t?(OS(s),(h=de(this,Fe))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===j.LOOP&&s!==t?(f=de(this,Fe))==null||f.dispatch({type:Y.MEDIA_LOOP_REQUEST,detail:s!=null}):e===j.NO_VOLUME_PREF&&s!==t?(m=de(this,Fe))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(j.NO_VOLUME_PREF)}}):e===j.NO_MUTED_PREF&&s!==t&&((p=de(this,Fe))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(j.NO_MUTED_PREF)}}))}connectedCallback(){var e,t,s;this.associateElement(this),!de(this,Fe)&&!this.hasAttribute(j.NO_DEFAULT_STORE)&&Yl(this,_h,av).call(this),(e=de(this,Fe))==null||e.dispatch({type:"documentelementchangerequest",detail:et}),(t=de(this,Fe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement}),super.connectedCallback(),de(this,Fe)&&!de(this,ys)&&is(this,ys,(s=de(this,Fe))==null?void 0:s.subscribe(de(this,zl))),de(this,Ql)!==void 0&&de(this,Fe)&&this.media&&setTimeout(()=>{var r,n,a;(n=(r=this.media)==null?void 0:r.textTracks)!=null&&n.length&&((a=de(this,Fe))==null||a.dispatch({type:Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:de(this,Ql)}))},0),this.hasAttribute(j.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n,a;if((e=super.disconnectedCallback)==null||e.call(this),this.disableHotkeys(),de(this,Fe)){let o=de(this,Fe).getState();is(this,Ql,!!((t=o.mediaSubtitlesShowing)!=null&&t.length)),(s=de(this,Fe))==null||s.dispatch({type:"fullscreenelementchangerequest",detail:void 0}),(r=de(this,Fe))==null||r.dispatch({type:"documentelementchangerequest",detail:void 0}),(n=de(this,Fe))==null||n.dispatch({type:Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}de(this,ys)&&((a=de(this,ys))==null||a.call(this),is(this,ys,void 0)),this.unassociateElement(this),de(this,bs)&&(de(this,bs).remove(),is(this,bs,null))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=de(this,Fe))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=de(this,Fe))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){g1(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=_N(e,s,r);Object.values(Y).forEach(a=>{e.addEventListener(a,de(this,Th))}),t.set(e,n)}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(Y).forEach(r=>{e.removeEventListener(r,de(this,Th))})}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),de(this,Fe)&&Object.entries(de(this,Fe).getState()).forEach(([r,n])=>{g1([e],r,n)}))}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",Yl(this,Ah,ov))}disableHotkeys(){this.removeEventListener("keydown",Yl(this,Ah,ov)),this.removeEventListener("keyup",de(this,$n))}get hotkeys(){return de(this,nr)}set hotkeys(e){Ae(this,j.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;let c=e.target;if(((r=(s=(t=c.getAttribute(j.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c==null?void 0:c.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(de(this,nr).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&de(this,nr).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&de(this,nr).contains("noshift+/")))switch(e.key){case" ":case"k":f=de(this,Fe).getState().mediaPaused?Y.MEDIA_PLAY_REQUEST:Y.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?Y.MEDIA_UNMUTE_REQUEST:Y.MEDIA_MUTE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?Y.MEDIA_EXIT_FULLSCREEN_REQUEST:Y.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new L.CustomEvent(Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{let v=this.hasAttribute(j.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(j.KEYBOARD_BACKWARD_SEEK_OFFSET):c1;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new L.CustomEvent(Y.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{let v=this.hasAttribute(j.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(j.KEYBOARD_FORWARD_SEEK_OFFSET):c1;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new L.CustomEvent(Y.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{let v=this.hasAttribute(j.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(j.KEYBOARD_UP_VOLUME_STEP):h1;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new L.CustomEvent(Y.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{let v=this.hasAttribute(j.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(j.KEYBOARD_DOWN_VOLUME_STEP):h1;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new L.CustomEvent(Y.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{let v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-f1,pN).toFixed(2),p=new L.CustomEvent(Y.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{let v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+f1,gN).toFixed(2),p=new L.CustomEvent(Y.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&Yl(this,lv,v1).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?Y.MEDIA_EXIT_PIP_REQUEST:Y.MEDIA_ENTER_PIP_REQUEST,p=new L.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}default:break}}};nr=new WeakMap;jl=new WeakMap;Fe=new WeakMap;bs=new WeakMap;zl=new WeakMap;ys=new WeakMap;Th=new WeakMap;Ql=new WeakMap;_h=new WeakSet;av=function(){var i;this.mediaStore=u1({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(j.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(j.DEFAULT_DURATION)?+this.getAttribute(j.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(j.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(j.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(j.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(j.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(j.NO_SUBTITLES_LANG_PREF)}})};$n=new WeakMap;Ah=new WeakSet;ov=function(i){var e;let{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=de(this,bs))!=null&&e.open)){this.removeEventListener("keyup",de(this,$n));return}if(t||s||!a&&!E1.includes(r)){this.removeEventListener("keyup",de(this,$n));return}let o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(de(this,nr).contains(`no${r.toLowerCase()}`)||r===" "&&de(this,nr).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",de(this,$n),{once:!0})};lv=new WeakSet;v1=function(){de(this,bs)||(is(this,bs,et.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(de(this,bs))),de(this,bs).open=!0};var vN=Object.values(A),EN=Object.values(Y0),y1=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(L.customElements.upgrade(i),{observedAttributes:n}=i.constructor);let a=(r=(s=(t=i==null?void 0:i.getAttribute)==null?void 0:t.call(i,Le.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>vN.includes(o)):[]},yN=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&L.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof L.customElements.get(i.nodeName.toLowerCase()))&&L.customElements.upgrade(i),EN.some(s=>s in i)},dv=i=>yN(i)||!!y1(i).length,m1=i=>{var e;return(e=i==null?void 0:i.join)==null?void 0:e.call(i,":")},p1={[A.MEDIA_SUBTITLES_LIST]:rr,[A.MEDIA_SUBTITLES_SHOWING]:rr,[A.MEDIA_SEEKABLE]:m1,[A.MEDIA_BUFFERED]:i=>i==null?void 0:i.map(m1).join(" "),[A.MEDIA_PREVIEW_COORDS]:i=>i==null?void 0:i.join(" "),[A.MEDIA_RENDITION_LIST]:xS,[A.MEDIA_AUDIO_TRACK_LIST]:DS},bN=async(i,e,t)=>{var s,r;if(i.isConnected||await Zc(0),typeof t=="boolean"||t==null)return ge(i,e,t);if(typeof t=="number")return Ue(i,e,t);if(typeof t=="string")return Ae(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);let n=(r=(s=p1[e])==null?void 0:s.call(p1,t))!=null?r:t;return i.setAttribute(e,n)},TN=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},Bn=(i,e)=>{if(TN(i))return;let t=(r,n)=>{var a,o;dv(r)&&n(r);let{children:l=[]}=r!=null?r:{},d=(o=(a=r==null?void 0:r.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>Bn(c,n))},s=i==null?void 0:i.nodeName.toLowerCase();if(s.includes("-")&&!dv(i)){L.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},g1=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}let r=y1(s),n=e.toLowerCase();r.includes(n)&&bN(s,n,t)})},_N=(i,e,t)=>{Bn(i,e);let s=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(Y.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(Y.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=u=>{u.forEach(c=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>Bn(v,e)),Array.prototype.forEach.call(f,v=>Bn(v,t))):m==="attributes"&&g===Le.MEDIA_CHROME_ATTRIBUTES&&(dv(p)?e(p):t(p))})},a=[],o=u=>{let c=u.target;c.name!=="media"&&(a.forEach(h=>Bn(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>Bn(h,e)))};i.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{Bn(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(Y.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(Y.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};L.customElements.get("media-controller")||L.customElements.define("media-controller",Sh);var cv=Sh;var qa={PLACEMENT:"placement",BOUNDS:"bounds"};function AN(i){return`
|
|
301
|
+
`}var ZO=Object.values(A),JO="sm:384 md:576 lg:768 xl:960";function eN(i){jS(i.target,i.contentRect.width)}function jS(i,e){var t;if(!i.isConnected)return;let s=(t=i.getAttribute(he.BREAKPOINTS))!=null?t:JO,r=tN(s),n=iN(r,e),a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){let o=new CustomEvent(Ri.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(Ri.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function tN(i){let e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function iN(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}var Pn=class extends L.HTMLElement{constructor(){if(super(),ai(this,X0),ai(this,Z0),ai(this,Kl),ai(this,hh),ai(this,Ha),ai(this,Gl,void 0),ai(this,uh,0),ai(this,Ua,null),ai(this,$a,null),ai(this,Ba,void 0),this.breakpointsComputed=!1,ai(this,Q0,e=>{let t=this.media;for(let s of e){if(s.type!=="childList")continue;let r=s.removedNodes;for(let n of r){if(n.slot!="media"||s.target!=this)continue;let a=s.previousSibling&&s.previousSibling.previousElementSibling;if(!a||!t)this.mediaUnsetCallback(n);else{let o=a.slot!=="media";for(;(a=a.previousSibling)!==null;)a.slot=="media"&&(o=!1);o&&this.mediaUnsetCallback(n)}}if(t)for(let n of s.addedNodes)n===t&&this.handleMediaUpdated(t)}}),ai(this,Fa,!1),ai(this,lh,e=>{It(this,Fa)||(setTimeout(()=>{eN(e),es(this,Fa,!1)},0),es(this,Fa,!0))}),ai(this,Vr,void 0),ai(this,dh,()=>{if(!It(this,Vr).assignedElements({flatten:!0}).length){It(this,Ua)&&this.mediaUnsetCallback(It(this,Ua));return}this.handleMediaUpdated(this.media)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=lt(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t}es(this,Gl,new MutationObserver(It(this,Q0)))}static get observedAttributes(){return[he.AUTOHIDE,he.GESTURES_DISABLED].concat(ZO).filter(e=>![A.MEDIA_RENDITION_LIST,A.MEDIA_AUDIO_TRACK_LIST,A.MEDIA_CHAPTERS_CUES,A.MEDIA_WIDTH,A.MEDIA_HEIGHT,A.MEDIA_ERROR,A.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==he.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return(e==null?void 0:e.nodeName)=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(es(this,Ua,e),e.localName.includes("-")&&await L.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;It(this,Gl).observe(this,{childList:!0,subtree:!0}),tr(this,It(this,lh));let s=this.getAttribute(he.AUDIO)!=null?G("audio player"):G("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(he.USER_INACTIVE,""),jS(this,this.getBoundingClientRect().width);let r=this.querySelector(":scope > slot[slot=media]");r&&(es(this,Vr,r),It(this,Vr).addEventListener("slotchange",It(this,dh))),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=L.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;ir(this,It(this,lh)),clearTimeout(It(this,$a)),It(this,Gl).disconnect(),this.media&&this.mediaUnsetCallback(this.media),(e=L.window)==null||e.removeEventListener("mouseup",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointermove",this),this.removeEventListener("pointerup",this),this.removeEventListener("mouseleave",this),this.removeEventListener("keyup",this),It(this,Vr)&&(It(this,Vr).removeEventListener("slotchange",It(this,dh)),es(this,Vr,null)),es(this,Fa,!1)}mediaSetCallback(e){}mediaUnsetCallback(e){es(this,Ua,null)}handleEvent(e){switch(e.type){case"pointerdown":es(this,uh,e.timeStamp);break;case"pointermove":ts(this,X0,qS).call(this,e);break;case"pointerup":ts(this,Z0,YS).call(this,e);break;case"mouseleave":ts(this,Kl,ch).call(this);break;case"mouseup":this.removeAttribute(he.KEYBOARD_CONTROL);break;case"keyup":ts(this,Ha,Vl).call(this),this.setAttribute(he.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);es(this,Ba,isNaN(t)?0:t)}get autohide(){return(It(this,Ba)===void 0?2:It(this,Ba)).toString()}get breakpoints(){return Se(this,he.BREAKPOINTS)}set breakpoints(e){Ae(this,he.BREAKPOINTS,e)}get audio(){return pe(this,he.AUDIO)}set audio(e){ge(this,he.AUDIO,e)}get gesturesDisabled(){return pe(this,he.GESTURES_DISABLED)}set gesturesDisabled(e){ge(this,he.GESTURES_DISABLED,e)}get keyboardControl(){return pe(this,he.KEYBOARD_CONTROL)}set keyboardControl(e){ge(this,he.KEYBOARD_CONTROL,e)}get noAutohide(){return pe(this,he.NO_AUTOHIDE)}set noAutohide(e){ge(this,he.NO_AUTOHIDE,e)}get autohideOverControls(){return pe(this,he.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){ge(this,he.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return pe(this,he.USER_INACTIVE)}set userInteractive(e){ge(this,he.USER_INACTIVE,e)}};Gl=new WeakMap;uh=new WeakMap;Ua=new WeakMap;$a=new WeakMap;Ba=new WeakMap;Q0=new WeakMap;Fa=new WeakMap;lh=new WeakMap;X0=new WeakSet;qS=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-It(this,uh)<250)return;ts(this,hh,ev).call(this),clearTimeout(It(this,$a));let e=this.hasAttribute(he.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&ts(this,Ha,Vl).call(this)};Z0=new WeakSet;YS=function(i){if(i.pointerType==="touch"){let e=!this.hasAttribute(he.USER_INACTIVE);[this,this.media].includes(i.target)&&e?ts(this,Kl,ch).call(this):ts(this,Ha,Vl).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e==null?void 0:e.localName))&&ts(this,Ha,Vl).call(this)};Kl=new WeakSet;ch=function(){if(It(this,Ba)<0||this.hasAttribute(he.USER_INACTIVE))return;this.setAttribute(he.USER_INACTIVE,"");let i=new L.CustomEvent(Ri.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};hh=new WeakSet;ev=function(){if(!this.hasAttribute(he.USER_INACTIVE))return;this.removeAttribute(he.USER_INACTIVE);let i=new L.CustomEvent(Ri.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};Ha=new WeakSet;Vl=function(){ts(this,hh,ev).call(this),clearTimeout(It(this,$a));let i=parseInt(this.autohide);i<0||es(this,$a,setTimeout(()=>{ts(this,Kl,ch).call(this)},i*1e3))};Vr=new WeakMap;dh=new WeakMap;Pn.shadowRootOptions={mode:"open"};Pn.getTemplateHTML=XO;L.customElements.get("media-container")||L.customElements.define("media-container",Pn);var zS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Kt=(i,e,t)=>(zS(i,e,"read from private field"),t?t.call(i):e.get(i)),Wl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},fh=(i,e,t,s)=>(zS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ga,Ka,mh,On,sr,Wr,qr=class{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){Wl(this,sr),Wl(this,Ga,void 0),Wl(this,Ka,void 0),Wl(this,mh,void 0),Wl(this,On,new Set),fh(this,Ga,e),fh(this,Ka,t),fh(this,mh,new Set(s))}[Symbol.iterator](){return Kt(this,sr,Wr).values()}get length(){return Kt(this,sr,Wr).size}get value(){var e;return(e=[...Kt(this,sr,Wr)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(fh(this,On,new Set),this.add(...(t=e==null?void 0:e.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...Kt(this,sr,Wr)][e]}values(){return Kt(this,sr,Wr).values()}forEach(e,t){Kt(this,sr,Wr).forEach(e,t)}add(...e){var t,s;e.forEach(r=>Kt(this,On).add(r)),!(this.value===""&&!((t=Kt(this,Ga))!=null&&t.hasAttribute(`${Kt(this,Ka)}`)))&&((s=Kt(this,Ga))==null||s.setAttribute(`${Kt(this,Ka)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>Kt(this,On).delete(s)),(t=Kt(this,Ga))==null||t.setAttribute(`${Kt(this,Ka)}`,`${this.value}`)}contains(e){return Kt(this,sr,Wr).has(e)}toggle(e,t){return typeof t!="undefined"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){return this.remove(e),this.add(t),e===t}};Ga=new WeakMap;Ka=new WeakMap;mh=new WeakMap;On=new WeakMap;sr=new WeakSet;Wr=function(){return Kt(this,On).size?Kt(this,On):Kt(this,mh)};var sN=(i="")=>i.split(/\s+/),QS=(i="")=>{let[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?hi.CAPTIONS:hi.SUBTITLES,language:t,label:r}},Nn=(i="",e={})=>sN(i).map(t=>{let s=QS(t);return{...e,...s}}),tv=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?QS(e):e):typeof i=="string"?Nn(i):[i]:[],ph=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,rr=(i=[])=>Array.prototype.map.call(i,ph).join(" "),rN=(i,e)=>t=>t[i]===e,XS=i=>{let e=Object.entries(i).map(([t,s])=>rN(t,s));return t=>e.every(s=>s(t))},Un=(i,e=[],t=[])=>{let s=tv(t).map(XS),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},Fn=(i,e=()=>!0)=>{if(!(i!=null&&i.textTracks))return[];let t=typeof e=="function"?e:XS(e);return Array.from(i.textTracks).filter(t)},gh=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(A.MEDIA_SUBTITLES_SHOWING)};var JS=i=>{var e;let{media:t,fullscreenElement:s}=i;try{let r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){let n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t!=null&&t.webkitEnterFullscreen?t.webkitEnterFullscreen():t!=null&&t.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},ZS="exitFullscreen"in et?"exitFullscreen":"webkitExitFullscreen"in et?"webkitExitFullscreen":"webkitCancelFullScreen"in et?"webkitCancelFullScreen":void 0,e1=i=>{var e;let{documentElement:t}=i;if(ZS){let s=(e=t==null?void 0:t[ZS])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},ql="fullscreenElement"in et?"fullscreenElement":"webkitFullscreenElement"in et?"webkitFullscreenElement":void 0,nN=i=>{let{documentElement:e,media:t}=i,s=e==null?void 0:e[ql];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===LS.FULLSCREEN?t:s},t1=i=>{var e;let{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;let n=nN(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(ql in a))return ni(n,r);for(;a!=null&&a[ql];){if(a[ql]===r)return!0;a=(e=a[ql])==null?void 0:e.shadowRoot}}return!1},aN="fullscreenEnabled"in et?"fullscreenEnabled":"webkitFullscreenEnabled"in et?"webkitFullscreenEnabled":void 0,i1=i=>{let{documentElement:e,media:t}=i;return!!(e!=null&&e[aN])||t&&"webkitSupportsFullscreen"in t};var vh,iv=()=>{var i,e;return vh||(vh=(e=(i=et)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),vh)},s1=async(i=iv())=>{if(!i)return!1;let e=i.volume;i.volume=e/2+.1;let t=new AbortController,s=await Promise.race([oN(i,t.signal),lN(i,e)]);return t.abort(),s},oN=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),lN=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await Zc(10)}return i.volume!==e},dN=/.*Version\/.*Safari\/.*/.test(L.navigator.userAgent),sv=(i=iv())=>L.matchMedia("(display-mode: standalone)").matches&&dN?!1:typeof(i==null?void 0:i.requestPictureInPicture)=="function",rv=(i=iv())=>i1({documentElement:et,media:i}),r1=rv(),n1=sv(),a1=!!L.WebKitPlaybackTargetAvailabilityEvent,o1=!!L.chrome;var Va=i=>Fn(i.media,e=>[hi.SUBTITLES,hi.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),nv=i=>Fn(i.media,e=>e.mode===Kr.SHOWING&&[hi.SUBTITLES,hi.CAPTIONS].includes(e.kind)),Eh=(i,e)=>{let t=Va(i),s=nv(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)Un(Kr.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0],{options:a}=i;if(!(a!=null&&a.noSubtitlesLangPref)){let u=L.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...L.navigator.languages]:L.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}let{language:o,label:l,kind:d}=n;Un(Kr.DISABLED,t,s),Un(Kr.SHOWING,t,[{language:o,label:l,kind:d}])}}},yh=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?uN(i,e):Object.entries(i).every(([t,s])=>t in e&&yh(s,e[t])),uN=(i,e)=>{let t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>yh(r,e[n])):!0};var cN=Object.values(Xi),bh,hN=s1().then(i=>(bh=i,bh)),l1=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof L.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let s=L.customElements.get(t);s&&e instanceof s||(await L.customElements.whenDefined(t),L.customElements.upgrade(e))}))},fN=new L.DOMParser,mN=i=>i&&(fN.parseFromString(i,"text/html").body.textContent||i),Wa={mediaError:{get(i,e){let{media:t}=i;if((e==null?void 0:e.type)!=="playing")return t==null?void 0:t.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;let{media:s}=i;if((e==null?void 0:e.type)!=="playing")return(t=s==null?void 0:s.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;let{media:r}=i;if((e==null?void 0:e.type)!=="playing")return(s=(t=r==null?void 0:r.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.paused)!=null?e:!0},set(i,e){var t;let{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){let{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.playbackRate)!=null?e:1},set(i,e){let{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.muted)!=null?e:!1},set(i,e){let{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{let r=L.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&L.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;L.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{let r=L.localStorage.getItem("media-chrome-pref-muted")==="true";Wa.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){let{media:e}=i;return e==null?void 0:e.loop},set(i,e){let{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.volume)!=null?e:1},set(i,e){let{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?L.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&L.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:s}=e;if(!s)return;let r=L.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Wa.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){let{media:e}=i;return typeof(e==null?void 0:e.volume)=="undefined"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.currentTime)!=null?e:0},set(i,e){let{media:t}=e;!t||!Pa(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata","seeking"]},mediaDuration:{get(i){let{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e==null?void 0:e.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){let{media:e}=i;return(e==null?void 0:e.readyState)<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;let{media:t}=i;if(!((e=t==null?void 0:t.seekable)!=null&&e.length))return;let s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;let{media:t}=i,s=(e=t==null?void 0:t.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){let{media:e,options:{defaultStreamType:t}={}}=i,s=[Xi.LIVE,Xi.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;let{streamType:r}=e;if(cN.includes(r))return r===Xi.UNKNOWN?s:r;let n=e.duration;return n===1/0?Xi.LIVE:Number.isFinite(n)?Xi.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){let{media:e}=i;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,s=Wa.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===Xi.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){let{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Wa.mediaStreamType.get(i)===Xi.LIVE))return!1;let r=e.seekable;if(!r)return!0;if(!r.length)return!1;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return Va(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return nv(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![hi.CAPTIONS,hi.SUBTITLES].includes((l=o==null?void 0:o.track)==null?void 0:l.kind)||Eh(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;let{media:t}=i;if(!t)return[];let[s]=Fn(t,{kind:hi.CHAPTERS});return Array.from((e=s==null?void 0:s.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:mN(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;if(!s)return;let r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r==null||r.addEventListener("load",i),n==null||n.addEventListener("load",i),()=>{r==null||r.removeEventListener("load",i),n==null||n.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;let{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?ni(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n!=null&&n.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){let{media:t}=e;if(t)if(i){if(!et.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else et.pictureInPictureElement&&et.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;let{media:r}=i;return(s=(t=r==null?void 0:r.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.videoRenditions)){console.warn("MediaController: Rendition selection not supported by this media.");return}let s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;let{media:s}=i;return(t=[...(e=s==null?void 0:s.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.audioTracks)){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let s=i;for(let r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return t1(i)},set(i,e,t){var s,r;i?(JS(e),t.detail&&!((s=e.media)!=null&&s.inert)&&((r=e.media)==null||r.focus())):e1(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;let{media:t}=i;return!(t!=null&&t.remote)||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:t.remote.state==="connected"},set(i,e){var t,s;let{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&L.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){let{media:e}=i;if(!r1||!rv(e))return fi.UNSUPPORTED}},mediaPipUnavailable:{get(i){let{media:e}=i;if(!n1||!sv(e))return fi.UNSUPPORTED;if(e!=null&&e.disablePictureInPicture)return fi.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){let{media:e}=i;if(bh===!1||(e==null?void 0:e.volume)==null)return fi.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{bh==null&&hN.then(e=>i(e?void 0:fi.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;let{media:s}=i;if(!o1||!((t=s==null?void 0:s.remote)!=null&&t.state))return fi.UNSUPPORTED;if(!(e==null||e==="available"))return fi.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!a1)return fi.UNSUPPORTED;if((e==null?void 0:e.availability)==="not-available")return fi.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;let{media:t}=i;if(!(t!=null&&t.videoRenditions))return fi.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return fi.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;let{media:s}=i;if(!(s!=null&&s.audioTracks))return fi.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return fi.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){let{options:{mediaLang:e}={}}=i;return e!=null?e:"en"}}};var d1={[Y.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;let{media:a}=e,o=t!=null?t:void 0,l,d;if(a&&o!=null){let[f]=Fn(a,{kind:hi.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f==null?void 0:f.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a==null?void 0:a.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(E=>+E),l=g.href}}let u=i.mediaDuration.get(e),h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[Y.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[Y.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;let a="mediaPaused",l=i.mediaStreamType.get(e)===Xi.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){let c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[Y.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){let s="mediaPlaybackRate",r=t;i[s].set(r,e)},[Y.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[Y.MEDIA_UNMUTE_REQUEST](i,e){let t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[Y.MEDIA_LOOP_REQUEST](i,e,{detail:t}){let s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[Y.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){let s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[Y.MEDIA_SEEK_REQUEST](i,e,{detail:t}){let s="mediaCurrentTime",r=t;i[s].set(r,e)},[Y.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;let n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[Y.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;let{options:r}=e,n=Va(e),a=tv(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&L.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Un(Kr.SHOWING,n,a)},[Y.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){let s=Va(e),r=t!=null?t:[];Un(Kr.DISABLED,s,r)},[Y.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){Eh(e,t)},[Y.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){let s="mediaRenditionSelected",r=t;i[s].set(r,e)},[Y.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){let s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[Y.MEDIA_ENTER_PIP_REQUEST](i,e){let t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Y.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[Y.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){let s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[Y.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[Y.MEDIA_ENTER_CAST_REQUEST](i,e){let t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Y.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[Y.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}};var u1=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Wa,requestMap:r=d1,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),u=p=>{p!=null&&(yh(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{let p=Object.entries(s).reduce((g,[v,{get:E}])=>(g[v]=E(l),g),{});u(p)},h={},f,m=async(p,g)=>{var v,E,b,T,_,I,S,x,k,R,D,w,N,$,H,O;let F=!!f;if(f={...l,...f!=null?f:{},...p},F)return;await l1(...Object.values(p));let B=o.length>0&&g===0&&a,W=l.media!==f.media,Z=((v=l.media)==null?void 0:v.textTracks)!==((E=f.media)==null?void 0:E.textTracks),K=((b=l.media)==null?void 0:b.videoRenditions)!==((T=f.media)==null?void 0:T.videoRenditions),q=((_=l.media)==null?void 0:_.audioTracks)!==((I=f.media)==null?void 0:I.audioTracks),ce=((S=l.media)==null?void 0:S.remote)!==((x=f.media)==null?void 0:x.remote),re=l.documentElement!==f.documentElement,ye=!!l.media&&(W||B),ue=!!((k=l.media)!=null&&k.textTracks)&&(Z||B),Ce=!!((R=l.media)!=null&&R.videoRenditions)&&(K||B),Te=!!((D=l.media)!=null&&D.audioTracks)&&(q||B),Ne=!!((w=l.media)!=null&&w.remote)&&(ce||B),mt=!!l.documentElement&&(re||B),Ft=ye||ue||Ce||Te||Ne||mt,Zt=o.length===0&&g===1&&a,Xe=!!f.media&&(W||Zt),ei=!!((N=f.media)!=null&&N.textTracks)&&(Z||Zt),yi=!!(($=f.media)!=null&&$.videoRenditions)&&(K||Zt),ie=!!((H=f.media)!=null&&H.audioTracks)&&(q||Zt),xe=!!((O=f.media)!=null&&O.remote)&&(ce||Zt),we=!!f.documentElement&&(re||Zt),pt=Xe||ei||yi||ie||xe||we;if(!(Ft||pt)){Object.entries(f).forEach(([Ie,Wt])=>{l[Ie]=Wt}),c(),f=void 0;return}Object.entries(s).forEach(([Ie,{get:Wt,mediaEvents:Gs=[],textTracksEvents:Pt=[],videoRenditionsEvents:qt=[],audioTracksEvents:di=[],remoteEvents:ti=[],rootEvents:Bt=[],stateOwnersUpdateHandlers:ls=[]}])=>{h[Ie]||(h[Ie]={});let vt=ct=>{let xt=Wt(l,ct);u({[Ie]:xt})},je;je=h[Ie].mediaEvents,Gs.forEach(ct=>{je&&ye&&(l.media.removeEventListener(ct,je),h[Ie].mediaEvents=void 0),Xe&&(f.media.addEventListener(ct,vt),h[Ie].mediaEvents=vt)}),je=h[Ie].textTracksEvents,Pt.forEach(ct=>{var xt,$i;je&&ue&&((xt=l.media.textTracks)==null||xt.removeEventListener(ct,je),h[Ie].textTracksEvents=void 0),ei&&(($i=f.media.textTracks)==null||$i.addEventListener(ct,vt),h[Ie].textTracksEvents=vt)}),je=h[Ie].videoRenditionsEvents,qt.forEach(ct=>{var xt,$i;je&&Ce&&((xt=l.media.videoRenditions)==null||xt.removeEventListener(ct,je),h[Ie].videoRenditionsEvents=void 0),yi&&(($i=f.media.videoRenditions)==null||$i.addEventListener(ct,vt),h[Ie].videoRenditionsEvents=vt)}),je=h[Ie].audioTracksEvents,di.forEach(ct=>{var xt,$i;je&&Te&&((xt=l.media.audioTracks)==null||xt.removeEventListener(ct,je),h[Ie].audioTracksEvents=void 0),ie&&(($i=f.media.audioTracks)==null||$i.addEventListener(ct,vt),h[Ie].audioTracksEvents=vt)}),je=h[Ie].remoteEvents,ti.forEach(ct=>{var xt,$i;je&&Ne&&((xt=l.media.remote)==null||xt.removeEventListener(ct,je),h[Ie].remoteEvents=void 0),xe&&(($i=f.media.remote)==null||$i.addEventListener(ct,vt),h[Ie].remoteEvents=vt)}),je=h[Ie].rootEvents,Bt.forEach(ct=>{je&&mt&&(l.documentElement.removeEventListener(ct,je),h[Ie].rootEvents=void 0),we&&(f.documentElement.addEventListener(ct,vt),h[Ie].rootEvents=vt)});let un=h[Ie].stateOwnersUpdateHandlers;if(un&&Ft&&(Array.isArray(un)?un:[un]).forEach(xt=>{typeof xt=="function"&&xt()}),pt){let ct=ls.map(xt=>xt(vt,f)).filter(xt=>typeof xt=="function");h[Ie].stateOwnersUpdateHandlers=ct.length===1?ct[0]:ct}else Ft&&(h[Ie].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([Ie,Wt])=>{l[Ie]=Wt}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v!=null?v:{}).forEach(([E,b])=>{l.options[E]=b}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var uv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},de=(i,e,t)=>(uv(i,e,"read from private field"),t?t.call(i):e.get(i)),Pi=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},is=(i,e,t,s)=>(uv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Yl=(i,e,t)=>(uv(i,e,"access private method"),t),nr,jl,Fe,bs,zl,ys,Th,Ql,_h,av,$n,Ah,ov,lv,v1,E1=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],c1=10,h1=.025,f1=.25,pN=.25,gN=2,j={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"},Sh=class extends Pn{constructor(){super(),Pi(this,_h),Pi(this,Ah),Pi(this,lv),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,Pi(this,nr,new qr(this,j.HOTKEYS)),Pi(this,jl,void 0),Pi(this,Fe,void 0),Pi(this,bs,null),Pi(this,zl,void 0),Pi(this,ys,void 0),Pi(this,Th,t=>{var s;(s=de(this,Fe))==null||s.dispatch(t)}),Pi(this,Ql,void 0),Pi(this,$n,t=>{let{key:s,shiftKey:r}=t;if(!(r&&(s==="/"||s==="?")||E1.includes(s))){this.removeEventListener("keyup",de(this,$n));return}this.keyboardShortcutHandler(t)}),this.associateElement(this);let e={};is(this,zl,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);let n=s.toLowerCase(),a=new L.CustomEvent(RS[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t})}static get observedAttributes(){return super.observedAttributes.concat(j.NO_HOTKEYS,j.HOTKEYS,j.DEFAULT_STREAM_TYPE,j.DEFAULT_SUBTITLES,j.DEFAULT_DURATION,j.NO_MUTED_PREF,j.NO_VOLUME_PREF,j.LANG,j.LOOP,j.LIVE_EDGE_OFFSET,j.SEEK_TO_LIVE_OFFSET,j.NO_AUTO_SEEK_TO_LIVE)}get mediaStore(){return de(this,Fe)}set mediaStore(e){var t,s;if(de(this,Fe)&&((t=de(this,ys))==null||t.call(this),is(this,ys,void 0)),is(this,Fe,e),!de(this,Fe)&&!this.hasAttribute(j.NO_DEFAULT_STORE)){Yl(this,_h,av).call(this);return}is(this,ys,(s=de(this,Fe))==null?void 0:s.subscribe(de(this,zl)))}get fullscreenElement(){var e;return(e=de(this,jl))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(j.FULLSCREEN_ELEMENT)&&this.removeAttribute(j.FULLSCREEN_ELEMENT),is(this,jl,e),(t=de(this,Fe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return pe(this,j.DEFAULT_SUBTITLES)}set defaultSubtitles(e){ge(this,j.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return Se(this,j.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){Ae(this,j.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return De(this,j.DEFAULT_DURATION)}set defaultDuration(e){Ue(this,j.DEFAULT_DURATION,e)}get noHotkeys(){return pe(this,j.NO_HOTKEYS)}set noHotkeys(e){ge(this,j.NO_HOTKEYS,e)}get keysUsed(){return Se(this,j.KEYS_USED)}set keysUsed(e){Ae(this,j.KEYS_USED,e)}get liveEdgeOffset(){return De(this,j.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Ue(this,j.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return pe(this,j.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){ge(this,j.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return pe(this,j.NO_VOLUME_PREF)}set noVolumePref(e){ge(this,j.NO_VOLUME_PREF,e)}get noMutedPref(){return pe(this,j.NO_MUTED_PREF)}set noMutedPref(e){ge(this,j.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return pe(this,j.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){ge(this,j.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return pe(this,j.NO_DEFAULT_STORE)}set noDefaultStore(e){ge(this,j.NO_DEFAULT_STORE,e)}get resolvedLang(){return NS()}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===j.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(j.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===j.HOTKEYS)de(this,nr).value=s;else if(e===j.DEFAULT_SUBTITLES&&s!==t)(r=de(this,Fe))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(j.DEFAULT_SUBTITLES)}});else if(e===j.DEFAULT_STREAM_TYPE)(a=de(this,Fe))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(j.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===j.LIVE_EDGE_OFFSET&&s!==t)(o=de(this,Fe))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0}});else if(e===j.SEEK_TO_LIVE_OFFSET&&s!==t)(l=de(this,Fe))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0}});else if(e===j.NO_AUTO_SEEK_TO_LIVE)(d=de(this,Fe))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(j.NO_AUTO_SEEK_TO_LIVE)}});else if(e===j.FULLSCREEN_ELEMENT){let g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;is(this,jl,g),(c=de(this,Fe))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===j.LANG&&s!==t?(OS(s),(h=de(this,Fe))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===j.LOOP&&s!==t?(f=de(this,Fe))==null||f.dispatch({type:Y.MEDIA_LOOP_REQUEST,detail:s!=null}):e===j.NO_VOLUME_PREF&&s!==t?(m=de(this,Fe))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(j.NO_VOLUME_PREF)}}):e===j.NO_MUTED_PREF&&s!==t&&((p=de(this,Fe))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(j.NO_MUTED_PREF)}}))}connectedCallback(){var e,t,s;this.associateElement(this),!de(this,Fe)&&!this.hasAttribute(j.NO_DEFAULT_STORE)&&Yl(this,_h,av).call(this),(e=de(this,Fe))==null||e.dispatch({type:"documentelementchangerequest",detail:et}),(t=de(this,Fe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement}),super.connectedCallback(),de(this,Fe)&&!de(this,ys)&&is(this,ys,(s=de(this,Fe))==null?void 0:s.subscribe(de(this,zl))),de(this,Ql)!==void 0&&de(this,Fe)&&this.media&&setTimeout(()=>{var r,n,a;(n=(r=this.media)==null?void 0:r.textTracks)!=null&&n.length&&((a=de(this,Fe))==null||a.dispatch({type:Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:de(this,Ql)}))},0),this.hasAttribute(j.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n,a;if((e=super.disconnectedCallback)==null||e.call(this),this.disableHotkeys(),de(this,Fe)){let o=de(this,Fe).getState();is(this,Ql,!!((t=o.mediaSubtitlesShowing)!=null&&t.length)),(s=de(this,Fe))==null||s.dispatch({type:"fullscreenelementchangerequest",detail:void 0}),(r=de(this,Fe))==null||r.dispatch({type:"documentelementchangerequest",detail:void 0}),(n=de(this,Fe))==null||n.dispatch({type:Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}de(this,ys)&&((a=de(this,ys))==null||a.call(this),is(this,ys,void 0)),this.unassociateElement(this),de(this,bs)&&(de(this,bs).remove(),is(this,bs,null))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=de(this,Fe))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=de(this,Fe))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){g1(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=_N(e,s,r);Object.values(Y).forEach(a=>{e.addEventListener(a,de(this,Th))}),t.set(e,n)}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(Y).forEach(r=>{e.removeEventListener(r,de(this,Th))})}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),de(this,Fe)&&Object.entries(de(this,Fe).getState()).forEach(([r,n])=>{g1([e],r,n)}))}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",Yl(this,Ah,ov))}disableHotkeys(){this.removeEventListener("keydown",Yl(this,Ah,ov)),this.removeEventListener("keyup",de(this,$n))}get hotkeys(){return de(this,nr)}set hotkeys(e){Ae(this,j.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;let c=e.target;if(((r=(s=(t=c.getAttribute(j.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c==null?void 0:c.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(de(this,nr).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&de(this,nr).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&de(this,nr).contains("noshift+/")))switch(e.key){case" ":case"k":f=de(this,Fe).getState().mediaPaused?Y.MEDIA_PLAY_REQUEST:Y.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?Y.MEDIA_UNMUTE_REQUEST:Y.MEDIA_MUTE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?Y.MEDIA_EXIT_FULLSCREEN_REQUEST:Y.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new L.CustomEvent(Y.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{let v=this.hasAttribute(j.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(j.KEYBOARD_BACKWARD_SEEK_OFFSET):c1;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new L.CustomEvent(Y.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{let v=this.hasAttribute(j.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(j.KEYBOARD_FORWARD_SEEK_OFFSET):c1;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new L.CustomEvent(Y.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{let v=this.hasAttribute(j.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(j.KEYBOARD_UP_VOLUME_STEP):h1;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new L.CustomEvent(Y.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{let v=this.hasAttribute(j.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(j.KEYBOARD_DOWN_VOLUME_STEP):h1;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new L.CustomEvent(Y.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{let v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-f1,pN).toFixed(2),p=new L.CustomEvent(Y.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{let v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+f1,gN).toFixed(2),p=new L.CustomEvent(Y.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&Yl(this,lv,v1).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?Y.MEDIA_EXIT_PIP_REQUEST:Y.MEDIA_ENTER_PIP_REQUEST,p=new L.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}default:break}}};nr=new WeakMap;jl=new WeakMap;Fe=new WeakMap;bs=new WeakMap;zl=new WeakMap;ys=new WeakMap;Th=new WeakMap;Ql=new WeakMap;_h=new WeakSet;av=function(){var i;this.mediaStore=u1({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(j.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(j.DEFAULT_DURATION)?+this.getAttribute(j.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(j.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(j.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(j.SEEK_TO_LIVE_OFFSET):this.hasAttribute(j.LIVE_EDGE_OFFSET)?+this.getAttribute(j.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(j.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(j.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(j.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(j.NO_SUBTITLES_LANG_PREF)}})};$n=new WeakMap;Ah=new WeakSet;ov=function(i){var e;let{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=de(this,bs))!=null&&e.open)){this.removeEventListener("keyup",de(this,$n));return}if(t||s||!a&&!E1.includes(r)){this.removeEventListener("keyup",de(this,$n));return}let o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(de(this,nr).contains(`no${r.toLowerCase()}`)||r===" "&&de(this,nr).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",de(this,$n),{once:!0})};lv=new WeakSet;v1=function(){de(this,bs)||(is(this,bs,et.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(de(this,bs))),de(this,bs).open=!0};var vN=Object.values(A),EN=Object.values(Y0),y1=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(L.customElements.upgrade(i),{observedAttributes:n}=i.constructor);let a=(r=(s=(t=i==null?void 0:i.getAttribute)==null?void 0:t.call(i,Le.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>vN.includes(o)):[]},yN=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&L.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof L.customElements.get(i.nodeName.toLowerCase()))&&L.customElements.upgrade(i),EN.some(s=>s in i)},dv=i=>yN(i)||!!y1(i).length,m1=i=>{var e;return(e=i==null?void 0:i.join)==null?void 0:e.call(i,":")},p1={[A.MEDIA_SUBTITLES_LIST]:rr,[A.MEDIA_SUBTITLES_SHOWING]:rr,[A.MEDIA_SEEKABLE]:m1,[A.MEDIA_BUFFERED]:i=>i==null?void 0:i.map(m1).join(" "),[A.MEDIA_PREVIEW_COORDS]:i=>i==null?void 0:i.join(" "),[A.MEDIA_RENDITION_LIST]:xS,[A.MEDIA_AUDIO_TRACK_LIST]:DS},bN=async(i,e,t)=>{var s,r;if(i.isConnected||await Zc(0),typeof t=="boolean"||t==null)return ge(i,e,t);if(typeof t=="number")return Ue(i,e,t);if(typeof t=="string")return Ae(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);let n=(r=(s=p1[e])==null?void 0:s.call(p1,t))!=null?r:t;return i.setAttribute(e,n)},TN=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},Bn=(i,e)=>{if(TN(i))return;let t=(r,n)=>{var a,o;dv(r)&&n(r);let{children:l=[]}=r!=null?r:{},d=(o=(a=r==null?void 0:r.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>Bn(c,n))},s=i==null?void 0:i.nodeName.toLowerCase();if(s.includes("-")&&!dv(i)){L.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},g1=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}let r=y1(s),n=e.toLowerCase();r.includes(n)&&bN(s,n,t)})},_N=(i,e,t)=>{Bn(i,e);let s=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(Y.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(Y.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=u=>{u.forEach(c=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>Bn(v,e)),Array.prototype.forEach.call(f,v=>Bn(v,t))):m==="attributes"&&g===Le.MEDIA_CHROME_ATTRIBUTES&&(dv(p)?e(p):t(p))})},a=[],o=u=>{let c=u.target;c.name!=="media"&&(a.forEach(h=>Bn(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>Bn(h,e)))};i.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{Bn(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(Y.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(Y.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};L.customElements.get("media-controller")||L.customElements.define("media-controller",Sh);var cv=Sh;var qa={PLACEMENT:"placement",BOUNDS:"bounds"};function AN(i){return`
|
|
302
302
|
<style>
|
|
303
303
|
:host {
|
|
304
304
|
--_tooltip-background-color: var(--media-tooltip-background-color, var(--media-secondary-color, rgba(20, 20, 30, .7)));
|
|
@@ -1289,7 +1289,7 @@ Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1289
1289
|
}
|
|
1290
1290
|
</style>
|
|
1291
1291
|
<img crossorigin loading="eager" decoding="async">
|
|
1292
|
-
`}var to=class extends L.HTMLElement{constructor(){if(super(),B2(this,Ds,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=lt(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[Le.MEDIA_CONTROLLER,A.MEDIA_PREVIEW_IMAGE,A.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,s;let r=this.getAttribute(Le.MEDIA_CONTROLLER);r&&(sf(this,Ds,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=tf(this,Ds))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=tf(this,Ds))==null?void 0:e.unassociateElement)==null||t.call(e,this),sf(this,Ds,null)}attributeChangedCallback(e,t,s){var r,n,a,o,l;[A.MEDIA_PREVIEW_IMAGE,A.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===Le.MEDIA_CONTROLLER&&(t&&((n=(r=tf(this,Ds))==null?void 0:r.unassociateElement)==null||n.call(r,this),sf(this,Ds,null)),s&&this.isConnected&&(sf(this,Ds,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=tf(this,Ds))==null?void 0:o.associateElement)==null||l.call(o,this)))}get mediaPreviewImage(){return Se(this,A.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){Ae(this,A.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewCoords(){let e=this.getAttribute(A.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(A.MEDIA_PREVIEW_COORDS);return}this.setAttribute(A.MEDIA_PREVIEW_COORDS,e.join(" "))}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[s,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:u,minWidth:c,minHeight:h}=l,f=l.getPropertyValue("--media-preview-thumbnail-object-fit").trim()||"contain",m,p;if(f==="fill"){let I=parseInt(d)/n,S=parseInt(u)/a,x=parseInt(c)/n,k=parseInt(h)/a;m=I<1?I:Math.max(I,x),p=S<1?S:Math.max(S,k)}else{let I=Math.min(parseInt(d)/n,parseInt(u)/a),S=Math.max(parseInt(c)/n,parseInt(h)/a),k=I<1?I:S>1?S:1;m=k,p=k}let{style:g}=at(this.shadowRoot,":host"),v=at(this.shadowRoot,"img").style,
|
|
1292
|
+
`}var to=class extends L.HTMLElement{constructor(){if(super(),B2(this,Ds,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=lt(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[Le.MEDIA_CONTROLLER,A.MEDIA_PREVIEW_IMAGE,A.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,s;let r=this.getAttribute(Le.MEDIA_CONTROLLER);r&&(sf(this,Ds,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=tf(this,Ds))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=tf(this,Ds))==null?void 0:e.unassociateElement)==null||t.call(e,this),sf(this,Ds,null)}attributeChangedCallback(e,t,s){var r,n,a,o,l;[A.MEDIA_PREVIEW_IMAGE,A.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===Le.MEDIA_CONTROLLER&&(t&&((n=(r=tf(this,Ds))==null?void 0:r.unassociateElement)==null||n.call(r,this),sf(this,Ds,null)),s&&this.isConnected&&(sf(this,Ds,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=tf(this,Ds))==null?void 0:o.associateElement)==null||l.call(o,this)))}get mediaPreviewImage(){return Se(this,A.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){Ae(this,A.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewCoords(){let e=this.getAttribute(A.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(A.MEDIA_PREVIEW_COORDS);return}this.setAttribute(A.MEDIA_PREVIEW_COORDS,e.join(" "))}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[s,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:u,minWidth:c,minHeight:h}=l,f=l.getPropertyValue("--media-preview-thumbnail-object-fit").trim()||"contain",m,p;if(f==="fill"){let I=parseInt(d)/n,S=parseInt(u)/a,x=parseInt(c)/n,k=parseInt(h)/a;m=I<1?I:Math.max(I,x),p=S<1?S:Math.max(S,k)}else{let I=Math.min(parseInt(d)/n,parseInt(u)/a),S=Math.max(parseInt(c)/n,parseInt(h)/a),k=I<1?I:S>1?S:1;m=k,p=k}let{style:g}=at(this.shadowRoot,":host"),v=at(this.shadowRoot,"img").style,E=this.shadowRoot.querySelector("img"),T=Math.min(m,p)<1?"min":"max";g.setProperty(`${T}-width`,"initial","important"),g.setProperty(`${T}-height`,"initial","important"),g.width=`${n*m}px`,g.height=`${a*p}px`;let _=()=>{v.width=`${this.imgWidth*m}px`,v.height=`${this.imgHeight*p}px`,v.display="block"};E.src!==o&&(E.onload=()=>{this.imgWidth=E.naturalWidth,this.imgHeight=E.naturalHeight,_(),E.onload=null},E.src=o,_()),_(),v.transform=`translate(-${s*m}px, -${r*p}px)`}};Ds=new WeakMap;to.shadowRootOptions={mode:"open"};to.getTemplateHTML=$2;L.customElements.get("media-preview-thumbnail")||L.customElements.define("media-preview-thumbnail",to);var rf=to;var nI=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},rI=(i,e,t)=>(nI(i,e,"read from private field"),t?t.call(i):e.get(i)),H2=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},G2=(i,e,t,s)=>(nI(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),md,Pv=class extends mi{constructor(){super(),H2(this,md,void 0),G2(this,md,this.shadowRoot.querySelector("slot")),rI(this,md).textContent=Zi(0)}static get observedAttributes(){return[...super.observedAttributes,A.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===A.MEDIA_PREVIEW_TIME&&s!=null&&(rI(this,md).textContent=Zi(parseFloat(s)))}get mediaPreviewTime(){return De(this,A.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Ue(this,A.MEDIA_PREVIEW_TIME,e)}};md=new WeakMap;L.customElements.get("media-preview-time-display")||L.customElements.define("media-preview-time-display",Pv);var io={SEEK_OFFSET:"seekoffset"},Ov=30,K2=i=>`
|
|
1293
1293
|
<svg aria-hidden="true" viewBox="0 0 20 24">
|
|
1294
1294
|
<defs>
|
|
1295
1295
|
<style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
|
|
@@ -2028,7 +2028,7 @@ Schedule: ${l.map(p=>Ti(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
2028
2028
|
min-height: var(--media-control-height, 24px);
|
|
2029
2029
|
}
|
|
2030
2030
|
</style>
|
|
2031
|
-
`}var Po=class extends xi{};Po.shadowRootOptions={mode:"open"};Po.getTemplateHTML=Z3;L.customElements.get("media-context-menu-item")||L.customElements.define("media-context-menu-item",Po);var pR=i=>{throw TypeError(i)},XE=(i,e,t)=>e.has(i)||pR("Cannot "+t),_e=(i,e,t)=>(XE(i,e,"read from private field"),t?t.call(i):e.get(i)),Mt=(i,e,t)=>e.has(i)?pR("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ei=(i,e,t,s)=>(XE(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Lt=(i,e,t)=>(XE(i,e,"access private method"),t),Im=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Im{}globalThis.DocumentFragment=i}var ZE=class extends Im{},J3=class extends Im{},eU={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(ZE)}},fm,tU=class{constructor(i,e={}){Mt(this,fm),Ei(this,fm,e==null?void 0:e.detail)}get detail(){return _e(this,fm)}initCustomEvent(){}};fm=new WeakMap;function iU(i,e){return new ZE}var gR={document:{createElement:iU},DocumentFragment,customElements:eU,CustomEvent:tU,EventTarget:Im,HTMLElement:ZE,HTMLVideoElement:J3},vR=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Hs=vR?gR:globalThis,Em=vR?gR.document:globalThis.document;function sU(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${YE(t)}: ${s}; `)}),e?e.trim():void 0}function YE(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function ER(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Jt(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function yR(i){let e=rU(i).toString();return e?"?"+e:""}function rU(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var bR=(i,e)=>!i||!e?!1:i.contains(e)?!0:bR(i,e.getRootNode().host),TR="mux.com",nU=()=>{try{return"3.14.0"}catch{}return"UNKNOWN"},aU=nU(),_R=()=>aU,oU=(i,{token:e,customDomain:t=TR,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=xr(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${yR({token:e,time:a,program_time:r})}`},lU=(i,{token:e,customDomain:t=TR,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=xr(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${yR({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},JE=i=>{if(i){if([He.LIVE,He.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return He.LIVE}},dU={crossorigin:"crossOrigin",playsinline:"playsInline"};function uU(i){var e;return(e=dU[i])!=null?e:ER(i)}var Oo,No,gi,cU=class{constructor(i,e){Mt(this,Oo),Mt(this,No),Mt(this,gi,[]),Ei(this,Oo,i),Ei(this,No,e)}[Symbol.iterator](){return _e(this,gi).values()}get length(){return _e(this,gi).length}get value(){var i;return(i=_e(this,gi).join(" "))!=null?i:""}set value(i){var e;i!==this.value&&(Ei(this,gi,[]),this.add(...(e=i==null?void 0:i.split(" "))!=null?e:[]))}toString(){return this.value}item(i){return _e(this,gi)[i]}values(){return _e(this,gi).values()}keys(){return _e(this,gi).keys()}forEach(i){_e(this,gi).forEach(i)}add(...i){var e,t;i.forEach(s=>{this.contains(s)||_e(this,gi).push(s)}),!(this.value===""&&!((e=_e(this,Oo))!=null&&e.hasAttribute(`${_e(this,No)}`)))&&((t=_e(this,Oo))==null||t.setAttribute(`${_e(this,No)}`,`${this.value}`))}remove(...i){var e;i.forEach(t=>{_e(this,gi).splice(_e(this,gi).indexOf(t),1)}),(e=_e(this,Oo))==null||e.setAttribute(`${_e(this,No)}`,`${this.value}`)}contains(i){return _e(this,gi).includes(i)}toggle(i,e){return typeof e!="undefined"?e?(this.add(i),!0):(this.remove(i),!1):this.contains(i)?(this.remove(i),!1):(this.add(i),!0)}replace(i,e){this.remove(i),this.add(e)}};Oo=new WeakMap,No=new WeakMap,gi=new WeakMap;var AR=`[mux-player ${_R()}]`;function mr(...i){console.warn(AR,...i)}function vi(...i){console.error(AR,...i)}function tR(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${
|
|
2031
|
+
`}var Po=class extends xi{};Po.shadowRootOptions={mode:"open"};Po.getTemplateHTML=Z3;L.customElements.get("media-context-menu-item")||L.customElements.define("media-context-menu-item",Po);var pR=i=>{throw TypeError(i)},XE=(i,e,t)=>e.has(i)||pR("Cannot "+t),_e=(i,e,t)=>(XE(i,e,"read from private field"),t?t.call(i):e.get(i)),Mt=(i,e,t)=>e.has(i)?pR("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ei=(i,e,t,s)=>(XE(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Lt=(i,e,t)=>(XE(i,e,"access private method"),t),Im=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Im{}globalThis.DocumentFragment=i}var ZE=class extends Im{},J3=class extends Im{},eU={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(ZE)}},fm,tU=class{constructor(i,e={}){Mt(this,fm),Ei(this,fm,e==null?void 0:e.detail)}get detail(){return _e(this,fm)}initCustomEvent(){}};fm=new WeakMap;function iU(i,e){return new ZE}var gR={document:{createElement:iU},DocumentFragment,customElements:eU,CustomEvent:tU,EventTarget:Im,HTMLElement:ZE,HTMLVideoElement:J3},vR=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Hs=vR?gR:globalThis,Em=vR?gR.document:globalThis.document;function sU(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${YE(t)}: ${s}; `)}),e?e.trim():void 0}function YE(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function ER(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Jt(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function yR(i){let e=rU(i).toString();return e?"?"+e:""}function rU(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var bR=(i,e)=>!i||!e?!1:i.contains(e)?!0:bR(i,e.getRootNode().host),TR="mux.com",nU=()=>{try{return"3.14.0"}catch{}return"UNKNOWN"},aU=nU(),_R=()=>aU,oU=(i,{token:e,customDomain:t=TR,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=xr(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${yR({token:e,time:a,program_time:r})}`},lU=(i,{token:e,customDomain:t=TR,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=xr(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${yR({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},JE=i=>{if(i){if([He.LIVE,He.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return He.LIVE}},dU={crossorigin:"crossOrigin",playsinline:"playsInline"};function uU(i){var e;return(e=dU[i])!=null?e:ER(i)}var Oo,No,gi,cU=class{constructor(i,e){Mt(this,Oo),Mt(this,No),Mt(this,gi,[]),Ei(this,Oo,i),Ei(this,No,e)}[Symbol.iterator](){return _e(this,gi).values()}get length(){return _e(this,gi).length}get value(){var i;return(i=_e(this,gi).join(" "))!=null?i:""}set value(i){var e;i!==this.value&&(Ei(this,gi,[]),this.add(...(e=i==null?void 0:i.split(" "))!=null?e:[]))}toString(){return this.value}item(i){return _e(this,gi)[i]}values(){return _e(this,gi).values()}keys(){return _e(this,gi).keys()}forEach(i){_e(this,gi).forEach(i)}add(...i){var e,t;i.forEach(s=>{this.contains(s)||_e(this,gi).push(s)}),!(this.value===""&&!((e=_e(this,Oo))!=null&&e.hasAttribute(`${_e(this,No)}`)))&&((t=_e(this,Oo))==null||t.setAttribute(`${_e(this,No)}`,`${this.value}`))}remove(...i){var e;i.forEach(t=>{_e(this,gi).splice(_e(this,gi).indexOf(t),1)}),(e=_e(this,Oo))==null||e.setAttribute(`${_e(this,No)}`,`${this.value}`)}contains(i){return _e(this,gi).includes(i)}toggle(i,e){return typeof e!="undefined"?e?(this.add(i),!0):(this.remove(i),!1):this.contains(i)?(this.remove(i),!1):(this.add(i),!0)}replace(i,e){this.remove(i),this.add(e)}};Oo=new WeakMap,No=new WeakMap,gi=new WeakMap;var AR=`[mux-player ${_R()}]`;function mr(...i){console.warn(AR,...i)}function vi(...i){console.error(AR,...i)}function tR(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${se("Read more: ")}
|
|
2032
2032
|
https://github.com/muxinc/elements/blob/main/errors/${i.file}`),mr(t)}var Xt={AUTOPLAY:"autoplay",CROSSORIGIN:"crossorigin",LOOP:"loop",MUTED:"muted",PLAYSINLINE:"playsinline",PRELOAD:"preload"},dn={VOLUME:"volume",PLAYBACKRATE:"playbackrate",MUTED:"muted"},FH={...Xt,...dn},iR=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}}),hU=Object.values(Xt).filter(i=>Xt.PLAYSINLINE!==i),fU=Object.values(dn),mU=[...hU,...fU],pU=class extends Hs.HTMLElement{static get observedAttributes(){return mU}constructor(){super()}attributeChangedCallback(i,e,t){var s,r;switch(i){case dn.MUTED:{this.media&&(this.media.muted=t!=null,this.media.defaultMuted=t!=null);return}case dn.VOLUME:{let n=(s=Jt(t))!=null?s:1;this.media&&(this.media.volume=n);return}case dn.PLAYBACKRATE:{let n=(r=Jt(t))!=null?r:1;this.media&&(this.media.playbackRate=n,this.media.defaultPlaybackRate=n);return}}}play(){var i,e;return(e=(i=this.media)==null?void 0:i.play())!=null?e:Promise.reject()}pause(){var i;(i=this.media)==null||i.pause()}load(){var i;(i=this.media)==null||i.load()}get media(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("mux-video")}get audioTracks(){return this.media.audioTracks}get videoTracks(){return this.media.videoTracks}get audioRenditions(){return this.media.audioRenditions}get videoRenditions(){return this.media.videoRenditions}get paused(){var i,e;return(e=(i=this.media)==null?void 0:i.paused)!=null?e:!0}get duration(){var i,e;return(e=(i=this.media)==null?void 0:i.duration)!=null?e:NaN}get ended(){var i,e;return(e=(i=this.media)==null?void 0:i.ended)!=null?e:!1}get buffered(){var i,e;return(e=(i=this.media)==null?void 0:i.buffered)!=null?e:iR}get seekable(){var i,e;return(e=(i=this.media)==null?void 0:i.seekable)!=null?e:iR}get readyState(){var i,e;return(e=(i=this.media)==null?void 0:i.readyState)!=null?e:0}get videoWidth(){var i,e;return(e=(i=this.media)==null?void 0:i.videoWidth)!=null?e:0}get videoHeight(){var i,e;return(e=(i=this.media)==null?void 0:i.videoHeight)!=null?e:0}get currentSrc(){var i,e;return(e=(i=this.media)==null?void 0:i.currentSrc)!=null?e:""}get currentTime(){var i,e;return(e=(i=this.media)==null?void 0:i.currentTime)!=null?e:0}set currentTime(i){this.media&&(this.media.currentTime=Number(i))}get volume(){var i,e;return(e=(i=this.media)==null?void 0:i.volume)!=null?e:1}set volume(i){this.media&&(this.media.volume=Number(i))}get playbackRate(){var i,e;return(e=(i=this.media)==null?void 0:i.playbackRate)!=null?e:1}set playbackRate(i){this.media&&(this.media.playbackRate=Number(i))}get defaultPlaybackRate(){var i;return(i=Jt(this.getAttribute(dn.PLAYBACKRATE)))!=null?i:1}set defaultPlaybackRate(i){i!=null?this.setAttribute(dn.PLAYBACKRATE,`${i}`):this.removeAttribute(dn.PLAYBACKRATE)}get crossOrigin(){return Yd(this,Xt.CROSSORIGIN)}set crossOrigin(i){this.setAttribute(Xt.CROSSORIGIN,`${i}`)}get autoplay(){return Yd(this,Xt.AUTOPLAY)!=null}set autoplay(i){i?this.setAttribute(Xt.AUTOPLAY,typeof i=="string"?i:""):this.removeAttribute(Xt.AUTOPLAY)}get loop(){return Yd(this,Xt.LOOP)!=null}set loop(i){i?this.setAttribute(Xt.LOOP,""):this.removeAttribute(Xt.LOOP)}get muted(){var i,e;return(e=(i=this.media)==null?void 0:i.muted)!=null?e:!1}set muted(i){this.media&&(this.media.muted=!!i)}get defaultMuted(){return Yd(this,Xt.MUTED)!=null}set defaultMuted(i){i?this.setAttribute(Xt.MUTED,""):this.removeAttribute(Xt.MUTED)}get playsInline(){return Yd(this,Xt.PLAYSINLINE)!=null}set playsInline(i){vi("playsInline is set to true by default and is not currently supported as a setter.")}get preload(){return this.media?this.media.preload:this.getAttribute("preload")}set preload(i){["","none","metadata","auto"].includes(i)?this.setAttribute(Xt.PRELOAD,i):this.removeAttribute(Xt.PRELOAD)}};function Yd(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var sR=pU,gU=`:host {
|
|
2033
2033
|
--media-control-display: var(--controls);
|
|
2034
2034
|
--media-loading-indicator-display: var(--loading-indicator);
|
|
@@ -2185,7 +2185,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2185
2185
|
${gU}
|
|
2186
2186
|
</style>
|
|
2187
2187
|
${MU(i)}
|
|
2188
|
-
`,DU=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return JE(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},CU={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},wU=Object.values(CU).join(", "),MU=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,b,
|
|
2188
|
+
`,DU=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return JE(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},CU={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},wU=Object.values(CU).join(", "),MU=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,E,b,T,_,I,S,x,k,R,D,w,N,$,H,O,F,B,W,Z,K,q,ce,re,ye,ue;return mm`
|
|
2189
2189
|
<media-theme
|
|
2190
2190
|
template="${i.themeTemplate||!1}"
|
|
2191
2191
|
defaultstreamtype="${(e=i.defaultStreamType)!=null?e:!1}"
|
|
@@ -2216,8 +2216,8 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2216
2216
|
stream-type="${(g=JE(i.streamType))!=null?g:!1}"
|
|
2217
2217
|
crossorigin="${(v=i.crossOrigin)!=null?v:""}"
|
|
2218
2218
|
playsinline
|
|
2219
|
-
autoplay="${(
|
|
2220
|
-
muted="${(
|
|
2219
|
+
autoplay="${(E=i.autoplay)!=null?E:!1}"
|
|
2220
|
+
muted="${(b=i.muted)!=null?b:!1}"
|
|
2221
2221
|
loop="${(T=i.loop)!=null?T:!1}"
|
|
2222
2222
|
preload="${(_=i.preload)!=null?_:!1}"
|
|
2223
2223
|
debug="${(I=i.debug)!=null?I:!1}"
|
|
@@ -2243,7 +2243,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2243
2243
|
exportparts="video"
|
|
2244
2244
|
disable-pseudo-ended="${(q=i.disablePseudoEnded)!=null?q:!1}"
|
|
2245
2245
|
max-reconnect-retries="${(ce=i.maxReconnectRetries)!=null?ce:!1}"
|
|
2246
|
-
max-auto-resolution="${(
|
|
2246
|
+
max-auto-resolution="${(re=i.maxAutoResolution)!=null?re:!1}"
|
|
2247
2247
|
cap-rendition-to-player-size="${(ye=i.capRenditionToPlayerSize)!=null?ye:!1}"
|
|
2248
2248
|
>
|
|
2249
2249
|
${i.storyboard?mm`<track label="thumbnails" default kind="metadata" src="${i.storyboard}" />`:mm``}
|
|
@@ -2258,7 +2258,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2258
2258
|
></media-poster-image>
|
|
2259
2259
|
</slot>
|
|
2260
2260
|
</media-theme>
|
|
2261
|
-
`},RR=i=>i.charAt(0).toUpperCase()+i.slice(1),PU=(i,e=!1)=>{var t,s;if(i.muxCode){let r=RR((t=i.errorCategory)!=null?t:"video"),n=Il((s=i.errorCategory)!=null?s:qe.VIDEO);if(i.muxCode===oe.NETWORK_OFFLINE)return
|
|
2261
|
+
`},RR=i=>i.charAt(0).toUpperCase()+i.slice(1),PU=(i,e=!1)=>{var t,s;if(i.muxCode){let r=RR((t=i.errorCategory)!=null?t:"video"),n=Il((s=i.errorCategory)!=null?s:qe.VIDEO);if(i.muxCode===oe.NETWORK_OFFLINE)return se("Your device appears to be offline",e);if(i.muxCode===oe.NETWORK_RECONNECTING)return se("Reconnecting...",e);if(i.muxCode===oe.NETWORK_TOKEN_EXPIRED)return se("{category} URL has expired",e).format({category:r});if([oe.NETWORK_TOKEN_SUB_MISMATCH,oe.NETWORK_TOKEN_AUD_MISMATCH,oe.NETWORK_TOKEN_AUD_MISSING,oe.NETWORK_TOKEN_MALFORMED].includes(i.muxCode))return se("{category} URL is formatted incorrectly",e).format({category:r});if(i.muxCode===oe.NETWORK_TOKEN_MISSING)return se("Invalid {categoryName} URL",e).format({categoryName:n});if(i.muxCode===oe.NETWORK_NOT_FOUND)return se("{category} does not exist",e).format({category:r});if(i.muxCode===oe.NETWORK_NOT_READY){let a=i.streamType==="live"?"Live stream":"Video";return se("{mediaType} is not currently available",e).format({mediaType:a})}}if(i.code){if(i.code===X.MEDIA_ERR_NETWORK)return se("Network Error",e);if(i.code===X.MEDIA_ERR_DECODE)return se("Media Error",e);if(i.code===X.MEDIA_ERR_SRC_NOT_SUPPORTED)return se("Source Not Supported",e)}return se("Error",e)},OU=(i,e=!1)=>{var t,s;if(i.reload)return'Try again later or <a href="#" data-mux-reload style="color: #4a90e2;">click here to retry</a>';if(i.muxCode){let r=RR((t=i.errorCategory)!=null?t:"video"),n=Il((s=i.errorCategory)!=null?s:qe.VIDEO);return i.muxCode===oe.NETWORK_OFFLINE?se("Check your internet connection and try reloading this video.",e):i.muxCode===oe.NETWORK_RECONNECTING?se("Your connection was interrupted. Attempting to resume playback...",e):i.muxCode===oe.NETWORK_TOKEN_EXPIRED?se("The video\u2019s secured {tokenNamePrefix}-token has expired.",e).format({tokenNamePrefix:n}):i.muxCode===oe.NETWORK_TOKEN_SUB_MISMATCH?se("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",e).format({tokenNamePrefix:n}):i.muxCode===oe.NETWORK_TOKEN_MALFORMED?se("{category} URL is formatted incorrectly",e).format({category:r}):[oe.NETWORK_TOKEN_AUD_MISMATCH,oe.NETWORK_TOKEN_AUD_MISSING].includes(i.muxCode)?se("The {tokenNamePrefix}-token is formatted with incorrect information.",e).format({tokenNamePrefix:n}):[oe.NETWORK_TOKEN_MISSING,oe.NETWORK_INVALID_URL].includes(i.muxCode)?se("The video URL or {tokenNamePrefix}-token are formatted with incorrect or incomplete information.",e).format({tokenNamePrefix:n}):i.muxCode===oe.NETWORK_NOT_FOUND?"":i.message}return i.code&&(i.code===X.MEDIA_ERR_NETWORK||i.code===X.MEDIA_ERR_DECODE||(i.code,X.MEDIA_ERR_SRC_NOT_SUPPORTED)),i.message},NU=(i,e=!1)=>{let t=PU(i,e).toString(),s=OU(i,e).toString();return{title:t,message:s}},UU=i=>{if(i.muxCode){if(i.muxCode===oe.NETWORK_TOKEN_EXPIRED)return"403-expired-token.md";if(i.muxCode===oe.NETWORK_TOKEN_MALFORMED)return"403-malformatted-token.md";if([oe.NETWORK_TOKEN_AUD_MISMATCH,oe.NETWORK_TOKEN_AUD_MISSING].includes(i.muxCode))return"403-incorrect-aud-value.md";if(i.muxCode===oe.NETWORK_TOKEN_SUB_MISMATCH)return"403-playback-id-mismatch.md";if(i.muxCode===oe.NETWORK_TOKEN_MISSING)return"missing-signed-tokens.md";if(i.muxCode===oe.NETWORK_NOT_FOUND)return"404-not-found.md";if(i.muxCode===oe.NETWORK_NOT_READY)return"412-not-playable.md"}if(i.code){if(i.code===X.MEDIA_ERR_NETWORK)return"";if(i.code===X.MEDIA_ERR_DECODE)return"media-decode-error.md";if(i.code===X.MEDIA_ERR_SRC_NOT_SUPPORTED)return"media-src-not-supported.md"}return""},LR=(i,e)=>{let t=UU(i);return{message:i.message,context:i.context,file:t}},FU=`<template id="media-theme-gerwig">
|
|
2262
2262
|
<style>
|
|
2263
2263
|
@keyframes pre-play-hide {
|
|
2264
2264
|
0% {
|
|
@@ -3398,11 +3398,11 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
3398
3398
|
href="${s.linkUrl}"
|
|
3399
3399
|
target="_blank"
|
|
3400
3400
|
rel="external noopener"
|
|
3401
|
-
aria-label="${(e=s.linkText)!=null?e:""} ${
|
|
3401
|
+
aria-label="${(e=s.linkText)!=null?e:""} ${se("(opens in a new window)")}"
|
|
3402
3402
|
>${(t=s.linkText)!=null?t:s.linkUrl}</a
|
|
3403
3403
|
>`:""}
|
|
3404
3404
|
</p>`:""}
|
|
3405
|
-
`}return HU(i)};function GU(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=Hs.customElements.get(s);if(n!=null&&n.template)return n.template}}function KU(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function zd(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var VU=Object.values(C),WU=Object.values(pr),qU=Object.values(V),lR=_R(),dR="mux-player",uR={isDialogOpen:!1},YU={redundant_streams:!0},pm,Qd,gm,sa,vm,Xd,ym,bm,Uo,Tm,_m,Am,Zd,Fo,Sm,bt,gr,kR,QE,ra,cR,hR,fR,mR,jU=class extends sR{constructor(){super(),Mt(this,bt),Mt(this,pm),Mt(this,Qd,!1),Mt(this,gm,{}),Mt(this,sa,!0),Mt(this,vm,new cU(this,"hotkeys")),Mt(this,Xd),Mt(this,ym,()=>Lt(this,bt,ra).call(this)),Mt(this,bm,()=>Lt(this,bt,ra).call(this)),Mt(this,Uo,()=>Lt(this,bt,ra).call(this)),Mt(this,Tm,i=>{i.composedPath().find(e=>{var t;return(t=e==null?void 0:e.hasAttribute)==null?void 0:t.call(e,"data-mux-reload")})&&(i.preventDefault(),window.location.reload())}),Mt(this,_m,i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&Lt(this,bt,QE).call(this,{isDialogOpen:!1})}),Mt(this,Am,i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&(bR(this,Em.activeElement)||i.preventDefault())}),Mt(this,Zd),Mt(this,Fo,{...uR}),Mt(this,Sm,i=>{var e;let t=(e=this.media)==null?void 0:e.error;if(!(t instanceof X)){let{message:r,code:n}=t!=null?t:{};t=new X(r,n)}if(!(t!=null&&t.fatal)){mr(t),t.data&&mr(`${t.name} data:`,t.data);return}let s=LR(t,!1);s.message&&tR(s),vi(t),t.data&&vi(`${t.name} data:`,t.data),Lt(this,bt,QE).call(this,{isDialogOpen:!0})}),Ei(this,pm,Ac()),this.attachShadow({mode:"open"}),Lt(this,bt,kR).call(this),this.isConnected&&Lt(this,bt,gr).call(this)}static get NAME(){return dR}static get VERSION(){return lR}static get observedAttributes(){var i;return[...(i=sR.observedAttributes)!=null?i:[],...WU,...VU,...qU]}setAttribute(i,e){super.setAttribute(i,e),i.startsWith("metadata-")&&this.media&&(this.media.metadata=zd(this))}removeAttribute(i){super.removeAttribute(i),i.startsWith("metadata-")&&this.media&&(this.media.metadata=zd(this))}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){Lt(this,bt,gr).call(this);let i=this.media;i&&(i.metadata=zd(this))}disconnectedCallback(){var i,e,t,s,r,n,a,o,l,d;(i=_e(this,Xd))==null||i.disconnect(),(e=this.media)==null||e.removeEventListener("streamtypechange",_e(this,ym)),(t=this.media)==null||t.removeEventListener("loadstart",_e(this,bm)),this.removeEventListener("error",_e(this,Sm)),this.removeEventListener("click",_e(this,Tm)),(s=this.mediaTheme)==null||s.removeEventListener("close",_e(this,_m)),(r=this.mediaTheme)==null||r.removeEventListener("focusin",_e(this,Am)),this.media&&(this.media.errorTranslator=void 0),(a=(n=this.media)==null?void 0:n.textTracks)==null||a.removeEventListener("addtrack",_e(this,Uo)),(l=(o=this.media)==null?void 0:o.textTracks)==null||l.removeEventListener("removetrack",_e(this,Uo)),(d=_e(this,Zd))==null||d.call(this),Ei(this,Zd,void 0),Ei(this,Qd,!1)}attributeChangedCallback(i,e,t){switch(Lt(this,bt,gr).call(this),super.attributeChangedCallback(i,e,t),i){case V.HOTKEYS:_e(this,vm).value=t;break;case V.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&mr(ne("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case V.THUMBNAIL_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.THUMBNAIL;r!==n&&mr(ne("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case V.STORYBOARD_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.STORYBOARD;r!==n&&mr(ne("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case V.DRM_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.DRM;r!==n&&mr(ne("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case C.PLAYBACK_ID:{t!=null&&t.includes("?token")&&vi(ne("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case C.STREAM_TYPE:{t&&![He.LIVE,He.ON_DEMAND,He.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:tR({file:"invalid-stream-type.md",message:ne("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===He.LIVE?this.getAttribute(V.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case V.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=Em.getElementById(t),r=s==null?void 0:s.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}case C.CAP_RENDITION_TO_PLAYER_SIZE:{(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0);break}case C.MAX_RECONNECT_RETRIES:{(t==null||t!==e)&&(this.maxReconnectRetries=Number(t));break}}[C.PLAYBACK_ID,pr.SRC,V.PLAYBACK_TOKEN].includes(i)&&e!==t&&Ei(this,Fo,{..._e(this,Fo),...uR}),Lt(this,bt,ra).call(this,{[uU(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(A.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new Hs.CustomEvent(Y.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(Ri.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(A.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new Hs.CustomEvent(Y.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(Ri.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(C.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?_a.includes(i)?this.setAttribute(C.PREFER_CMCD,i):mr(`Invalid value for preferCmcd. Must be one of ${_a.join()}`):this.removeAttribute(C.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(A.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(A.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(V.THEME))!=null?i:BU}set theme(i){this.setAttribute(V.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(zE.includes(t))continue;let s=i.getAttribute(t);e[ER(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;Lt(this,bt,gr).call(this);let s={...this.themeProps,...i};for(let r in s){if(zE.includes(r))continue;let n=i==null?void 0:i[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(YE(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(YE(r),n)}}get playbackId(){var i;return(i=this.getAttribute(C.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(C.PLAYBACK_ID,i):this.removeAttribute(C.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=$s(this,pr.SRC))!=null?i:void 0:(e=this.getAttribute(pr.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(pr.SRC,i):this.removeAttribute(pr.SRC)}get poster(){var i;let e=this.getAttribute(pr.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){mr("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return oU(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(pr.POSTER,i):this.removeAttribute(pr.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(V.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(V.STORYBOARD_SRC,i):this.removeAttribute(V.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[He.LIVE,He.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return lU(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(V.AUDIO)}set audio(i){if(!i){this.removeAttribute(V.AUDIO);return}this.setAttribute(V.AUDIO,"")}get hotkeys(){return _e(this,vm)}get nohotkeys(){return this.hasAttribute(V.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(V.NOHOTKEYS);return}this.setAttribute(V.NOHOTKEYS,"")}get thumbnailTime(){return Jt(this.getAttribute(V.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(V.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(V.VIDEO_TITLE))!=null?i:this.getAttribute(V.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(V.VIDEO_TITLE,i):this.removeAttribute(V.VIDEO_TITLE))}get placeholder(){var i;return(i=$s(this,V.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(V.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(V.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(V.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(V.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(V.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(V.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(V.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(V.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(V.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(V.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(V.PLAYBACK_RATES))return this.getAttribute(V.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(V.PLAYBACK_RATES);return}this.setAttribute(V.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=Jt(this.getAttribute(V.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(V.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=Jt(this.getAttribute(V.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(V.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(V.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(V.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(V.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return Jt(this.getAttribute(V.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(V.DEFAULT_DURATION):this.setAttribute(V.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?Jt(this.getAttribute(C.PLAYER_INIT_TIME)):_e(this,pm)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_NAME))!=null?i:dR}get playerSoftwareVersion(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_VERSION))!=null?i:lR}get beaconCollectionDomain(){var i;return(i=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(C.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(C.MAX_RESOLUTION,i):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(C.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(C.MIN_RESOLUTION,i):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(C.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(C.RENDITION_ORDER,i):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){return Jt(this.getAttribute(C.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return Jt(this.getAttribute(C.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return Jt(this.getAttribute(C.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${i}`)}get assetEndTime(){return Jt(this.getAttribute(C.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(V.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(V.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):YU}set extraSourceParams(i){i==null?this.removeAttribute(V.EXTRA_SOURCE_PARAMS):this.setAttribute(V.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(C.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(C.CUSTOM_DOMAIN,i):this.removeAttribute(C.CUSTOM_DOMAIN))}get envKey(){var i;return(i=$s(this,C.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(C.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(V.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(V.NO_VOLUME_PREF,""):this.removeAttribute(V.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(V.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(V.NO_MUTED_PREF,""):this.removeAttribute(V.NO_MUTED_PREF)}get debug(){return $s(this,C.DEBUG)!=null}set debug(i){i?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG)}get disableTracking(){return $s(this,C.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(C.DISABLE_TRACKING,!!i)}get disableCookies(){return $s(this,C.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(C.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:He.UNKNOWN}set streamType(i){this.setAttribute(C.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?t:He.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(V.DEFAULT_STREAM_TYPE,i):this.removeAttribute(V.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(V.TARGET_LIVE_WINDOW)?+this.getAttribute(V.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(V.TARGET_LIVE_WINDOW):this.setAttribute(V.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return Jt($s(this,C.START_TIME))}set startTime(i){this.setAttribute(C.START_TIME,`${i}`)}get initialBandwidthEstimateKbps(){return Jt($s(this,C.INITIAL_BANDWIDTH_ESTIMATE_KBPS))}set initialBandwidthEstimateKbps(i){i==null?this.removeAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`)}get initialEstimateSegments(){return Jt($s(this,C.INITIAL_ESTIMATE_SEGMENTS))}set initialEstimateSegments(i){i==null?this.removeAttribute(C.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(C.INITIAL_ESTIMATE_SEGMENTS,`${i}`)}get minPreloadSegments(){return Jt($s(this,C.MIN_PRELOAD_SEGMENTS))}set minPreloadSegments(i){i==null?this.removeAttribute(C.MIN_PRELOAD_SEGMENTS):this.setAttribute(C.MIN_PRELOAD_SEGMENTS,`${i}`)}get preferPlayback(){let i=this.getAttribute(C.PREFER_PLAYBACK);if(i===wi.MSE||i===wi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===wi.MSE||i===wi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,i):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...zd(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(V.PLAYBACK_TOKEN),e=this.getAttribute(V.DRM_TOKEN),t=this.getAttribute(V.THUMBNAIL_TOKEN),s=this.getAttribute(V.STORYBOARD_TOKEN);return{..._e(this,gm),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){Ei(this,gm,i!=null?i:{})}get playbackToken(){var i;return(i=this.getAttribute(V.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(V.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(V.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(V.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(V.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(V.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(V.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(V.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return Tc(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return sA(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(V.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(V.CAST_RECEIVER,i):this.removeAttribute(V.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){vi("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(V.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(V.NO_TOOLTIPS);return}this.setAttribute(V.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(V.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(V.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(V.PROUDLY_DISPLAY_MUX_BADGE)}get capRenditionToPlayerSize(){var i;return(i=this.media)==null?void 0:i.capRenditionToPlayerSize}set capRenditionToPlayerSize(i){if(!this.media){vi("underlying media element missing when trying to set capRenditionToPlayerSize");return}this.media.capRenditionToPlayerSize=i}get maxReconnectRetries(){var i;return(i=this.media)==null?void 0:i.maxReconnectRetries}set maxReconnectRetries(i){if(!this.media){vi("underlying media element missing when trying to set maxReconnectRetries");return}this.media.maxReconnectRetries=i}};pm=new WeakMap,Qd=new WeakMap,gm=new WeakMap,sa=new WeakMap,vm=new WeakMap,Xd=new WeakMap,ym=new WeakMap,bm=new WeakMap,Uo=new WeakMap,Tm=new WeakMap,_m=new WeakMap,Am=new WeakMap,Zd=new WeakMap,Fo=new WeakMap,Sm=new WeakMap,bt=new WeakSet,gr=function(){var i,e,t,s;if(!_e(this,Qd)){Ei(this,Qd,!0),Lt(this,bt,ra).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof Hs.HTMLElement))throw""}catch{vi("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{vi("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof cv))throw""}catch{vi("<media-controller> failed to upgrade!")}Lt(this,bt,cR).call(this),Lt(this,bt,hR).call(this),Lt(this,bt,fR).call(this),Ei(this,sa,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(he.USER_INACTIVE))!=null?e:!0),Lt(this,bt,mR).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",_e(this,ym)),(s=this.media)==null||s.addEventListener("loadstart",_e(this,bm)),this.media&&(this.media.metadata=zd(this))}},kR=function(){var i,e;try{(i=window==null?void 0:window.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window==null?void 0:window.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},QE=function(i){Object.assign(_e(this,Fo),i),Lt(this,bt,ra).call(this)},ra=function(i={}){LU(kU($U(this,{..._e(this,Fo),...i})),this.shadowRoot)},cR=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(zE.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};Ei(this,Xd,new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)})),_e(this,Xd).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},hR=function(){var i,e;this.addEventListener("error",_e(this,Sm)),this.addEventListener("click",_e(this,Tm)),(i=this.mediaTheme)==null||i.addEventListener("close",_e(this,_m)),(e=this.mediaTheme)==null||e.addEventListener("focusin",_e(this,Am)),this.media&&(this.media.errorTranslator=(t={})=>{var s,r,n;if(!(((s=this.media)==null?void 0:s.error)instanceof X))return t;let a=LR((r=this.media)==null?void 0:r.error,!1);return{player_error_code:(n=this.media)==null?void 0:n.error.code,player_error_message:a.message?String(a.message):t.player_error_message,player_error_context:a.context?String(a.context):t.player_error_context}})},fR=function(){var i,e,t,s;(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",_e(this,Uo)),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",_e(this,Uo))},mR=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===He.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(d,u,c=!1)=>{r()||Array.from(d&&d.activeCues||[]).forEach(h=>{if(!(!h.snapToLines||h.line<-5||h.line>=0&&h.line<10))if(!u||this.paused){let f=h.text.split(`
|
|
3405
|
+
`}return HU(i)};function GU(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=Hs.customElements.get(s);if(n!=null&&n.template)return n.template}}function KU(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function zd(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var VU=Object.values(C),WU=Object.values(pr),qU=Object.values(V),lR=_R(),dR="mux-player",uR={isDialogOpen:!1},YU={redundant_streams:!0},pm,Qd,gm,sa,vm,Xd,ym,bm,Uo,Tm,_m,Am,Zd,Fo,Sm,bt,gr,kR,QE,ra,cR,hR,fR,mR,jU=class extends sR{constructor(){super(),Mt(this,bt),Mt(this,pm),Mt(this,Qd,!1),Mt(this,gm,{}),Mt(this,sa,!0),Mt(this,vm,new cU(this,"hotkeys")),Mt(this,Xd),Mt(this,ym,()=>Lt(this,bt,ra).call(this)),Mt(this,bm,()=>Lt(this,bt,ra).call(this)),Mt(this,Uo,()=>Lt(this,bt,ra).call(this)),Mt(this,Tm,i=>{i.composedPath().find(e=>{var t;return(t=e==null?void 0:e.hasAttribute)==null?void 0:t.call(e,"data-mux-reload")})&&(i.preventDefault(),window.location.reload())}),Mt(this,_m,i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&Lt(this,bt,QE).call(this,{isDialogOpen:!1})}),Mt(this,Am,i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&(bR(this,Em.activeElement)||i.preventDefault())}),Mt(this,Zd),Mt(this,Fo,{...uR}),Mt(this,Sm,i=>{var e;let t=(e=this.media)==null?void 0:e.error;if(!(t instanceof X)){let{message:r,code:n}=t!=null?t:{};t=new X(r,n)}if(!(t!=null&&t.fatal)){mr(t),t.data&&mr(`${t.name} data:`,t.data);return}let s=LR(t,!1);s.message&&tR(s),vi(t),t.data&&vi(`${t.name} data:`,t.data),Lt(this,bt,QE).call(this,{isDialogOpen:!0})}),Ei(this,pm,Ac()),this.attachShadow({mode:"open"}),Lt(this,bt,kR).call(this),this.isConnected&&Lt(this,bt,gr).call(this)}static get NAME(){return dR}static get VERSION(){return lR}static get observedAttributes(){var i;return[...(i=sR.observedAttributes)!=null?i:[],...WU,...VU,...qU]}setAttribute(i,e){super.setAttribute(i,e),i.startsWith("metadata-")&&this.media&&(this.media.metadata=zd(this))}removeAttribute(i){super.removeAttribute(i),i.startsWith("metadata-")&&this.media&&(this.media.metadata=zd(this))}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){Lt(this,bt,gr).call(this);let i=this.media;i&&(i.metadata=zd(this))}disconnectedCallback(){var i,e,t,s,r,n,a,o,l,d;(i=_e(this,Xd))==null||i.disconnect(),(e=this.media)==null||e.removeEventListener("streamtypechange",_e(this,ym)),(t=this.media)==null||t.removeEventListener("loadstart",_e(this,bm)),this.removeEventListener("error",_e(this,Sm)),this.removeEventListener("click",_e(this,Tm)),(s=this.mediaTheme)==null||s.removeEventListener("close",_e(this,_m)),(r=this.mediaTheme)==null||r.removeEventListener("focusin",_e(this,Am)),this.media&&(this.media.errorTranslator=void 0),(a=(n=this.media)==null?void 0:n.textTracks)==null||a.removeEventListener("addtrack",_e(this,Uo)),(l=(o=this.media)==null?void 0:o.textTracks)==null||l.removeEventListener("removetrack",_e(this,Uo)),(d=_e(this,Zd))==null||d.call(this),Ei(this,Zd,void 0),Ei(this,Qd,!1)}attributeChangedCallback(i,e,t){switch(Lt(this,bt,gr).call(this),super.attributeChangedCallback(i,e,t),i){case V.HOTKEYS:_e(this,vm).value=t;break;case V.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&mr(se("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case V.THUMBNAIL_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.THUMBNAIL;r!==n&&mr(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case V.STORYBOARD_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.STORYBOARD;r!==n&&mr(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case V.DRM_TOKEN:{if(t){let s=xr(t);if(s){let{aud:r}=s,n=Ta.DRM;r!==n&&mr(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case C.PLAYBACK_ID:{t!=null&&t.includes("?token")&&vi(se("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case C.STREAM_TYPE:{t&&![He.LIVE,He.ON_DEMAND,He.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:tR({file:"invalid-stream-type.md",message:se("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===He.LIVE?this.getAttribute(V.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case V.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=Em.getElementById(t),r=s==null?void 0:s.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}case C.CAP_RENDITION_TO_PLAYER_SIZE:{(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0);break}case C.MAX_RECONNECT_RETRIES:{(t==null||t!==e)&&(this.maxReconnectRetries=Number(t));break}}[C.PLAYBACK_ID,pr.SRC,V.PLAYBACK_TOKEN].includes(i)&&e!==t&&Ei(this,Fo,{..._e(this,Fo),...uR}),Lt(this,bt,ra).call(this,{[uU(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(A.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new Hs.CustomEvent(Y.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(Ri.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(A.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new Hs.CustomEvent(Y.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(Ri.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(C.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?_a.includes(i)?this.setAttribute(C.PREFER_CMCD,i):mr(`Invalid value for preferCmcd. Must be one of ${_a.join()}`):this.removeAttribute(C.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(A.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(A.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(V.THEME))!=null?i:BU}set theme(i){this.setAttribute(V.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(zE.includes(t))continue;let s=i.getAttribute(t);e[ER(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;Lt(this,bt,gr).call(this);let s={...this.themeProps,...i};for(let r in s){if(zE.includes(r))continue;let n=i==null?void 0:i[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(YE(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(YE(r),n)}}get playbackId(){var i;return(i=this.getAttribute(C.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(C.PLAYBACK_ID,i):this.removeAttribute(C.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=$s(this,pr.SRC))!=null?i:void 0:(e=this.getAttribute(pr.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(pr.SRC,i):this.removeAttribute(pr.SRC)}get poster(){var i;let e=this.getAttribute(pr.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){mr("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return oU(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(pr.POSTER,i):this.removeAttribute(pr.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(V.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(V.STORYBOARD_SRC,i):this.removeAttribute(V.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[He.LIVE,He.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return lU(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(V.AUDIO)}set audio(i){if(!i){this.removeAttribute(V.AUDIO);return}this.setAttribute(V.AUDIO,"")}get hotkeys(){return _e(this,vm)}get nohotkeys(){return this.hasAttribute(V.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(V.NOHOTKEYS);return}this.setAttribute(V.NOHOTKEYS,"")}get thumbnailTime(){return Jt(this.getAttribute(V.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(V.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(V.VIDEO_TITLE))!=null?i:this.getAttribute(V.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(V.VIDEO_TITLE,i):this.removeAttribute(V.VIDEO_TITLE))}get placeholder(){var i;return(i=$s(this,V.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(V.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(V.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(V.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(V.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(V.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(V.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Hs.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(V.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(V.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(V.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(V.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(V.PLAYBACK_RATES))return this.getAttribute(V.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(V.PLAYBACK_RATES);return}this.setAttribute(V.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=Jt(this.getAttribute(V.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(V.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=Jt(this.getAttribute(V.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(V.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(V.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(V.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(V.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return Jt(this.getAttribute(V.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(V.DEFAULT_DURATION):this.setAttribute(V.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?Jt(this.getAttribute(C.PLAYER_INIT_TIME)):_e(this,pm)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_NAME))!=null?i:dR}get playerSoftwareVersion(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_VERSION))!=null?i:lR}get beaconCollectionDomain(){var i;return(i=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(C.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(C.MAX_RESOLUTION,i):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(C.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(C.MIN_RESOLUTION,i):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(C.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(C.RENDITION_ORDER,i):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){return Jt(this.getAttribute(C.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return Jt(this.getAttribute(C.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return Jt(this.getAttribute(C.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${i}`)}get assetEndTime(){return Jt(this.getAttribute(C.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(V.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(V.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):YU}set extraSourceParams(i){i==null?this.removeAttribute(V.EXTRA_SOURCE_PARAMS):this.setAttribute(V.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(C.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(C.CUSTOM_DOMAIN,i):this.removeAttribute(C.CUSTOM_DOMAIN))}get envKey(){var i;return(i=$s(this,C.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(C.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(V.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(V.NO_VOLUME_PREF,""):this.removeAttribute(V.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(V.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(V.NO_MUTED_PREF,""):this.removeAttribute(V.NO_MUTED_PREF)}get debug(){return $s(this,C.DEBUG)!=null}set debug(i){i?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG)}get disableTracking(){return $s(this,C.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(C.DISABLE_TRACKING,!!i)}get disableCookies(){return $s(this,C.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(C.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:He.UNKNOWN}set streamType(i){this.setAttribute(C.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?t:He.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(V.DEFAULT_STREAM_TYPE,i):this.removeAttribute(V.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(V.TARGET_LIVE_WINDOW)?+this.getAttribute(V.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(V.TARGET_LIVE_WINDOW):this.setAttribute(V.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return Jt($s(this,C.START_TIME))}set startTime(i){this.setAttribute(C.START_TIME,`${i}`)}get initialBandwidthEstimateKbps(){return Jt($s(this,C.INITIAL_BANDWIDTH_ESTIMATE_KBPS))}set initialBandwidthEstimateKbps(i){i==null?this.removeAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(C.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`)}get initialEstimateSegments(){return Jt($s(this,C.INITIAL_ESTIMATE_SEGMENTS))}set initialEstimateSegments(i){i==null?this.removeAttribute(C.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(C.INITIAL_ESTIMATE_SEGMENTS,`${i}`)}get minPreloadSegments(){return Jt($s(this,C.MIN_PRELOAD_SEGMENTS))}set minPreloadSegments(i){i==null?this.removeAttribute(C.MIN_PRELOAD_SEGMENTS):this.setAttribute(C.MIN_PRELOAD_SEGMENTS,`${i}`)}get preferPlayback(){let i=this.getAttribute(C.PREFER_PLAYBACK);if(i===wi.MSE||i===wi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===wi.MSE||i===wi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,i):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...zd(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(Lt(this,bt,gr).call(this),!this.media){vi("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(V.PLAYBACK_TOKEN),e=this.getAttribute(V.DRM_TOKEN),t=this.getAttribute(V.THUMBNAIL_TOKEN),s=this.getAttribute(V.STORYBOARD_TOKEN);return{..._e(this,gm),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){Ei(this,gm,i!=null?i:{})}get playbackToken(){var i;return(i=this.getAttribute(V.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(V.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(V.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(V.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(V.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(V.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(V.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(V.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return Tc(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return sA(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(V.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(V.CAST_RECEIVER,i):this.removeAttribute(V.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){vi("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(V.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(V.NO_TOOLTIPS);return}this.setAttribute(V.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(V.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(V.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(V.PROUDLY_DISPLAY_MUX_BADGE)}get capRenditionToPlayerSize(){var i;return(i=this.media)==null?void 0:i.capRenditionToPlayerSize}set capRenditionToPlayerSize(i){if(!this.media){vi("underlying media element missing when trying to set capRenditionToPlayerSize");return}this.media.capRenditionToPlayerSize=i}get maxReconnectRetries(){var i;return(i=this.media)==null?void 0:i.maxReconnectRetries}set maxReconnectRetries(i){if(!this.media){vi("underlying media element missing when trying to set maxReconnectRetries");return}this.media.maxReconnectRetries=i}};pm=new WeakMap,Qd=new WeakMap,gm=new WeakMap,sa=new WeakMap,vm=new WeakMap,Xd=new WeakMap,ym=new WeakMap,bm=new WeakMap,Uo=new WeakMap,Tm=new WeakMap,_m=new WeakMap,Am=new WeakMap,Zd=new WeakMap,Fo=new WeakMap,Sm=new WeakMap,bt=new WeakSet,gr=function(){var i,e,t,s;if(!_e(this,Qd)){Ei(this,Qd,!0),Lt(this,bt,ra).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof Hs.HTMLElement))throw""}catch{vi("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{vi("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof cv))throw""}catch{vi("<media-controller> failed to upgrade!")}Lt(this,bt,cR).call(this),Lt(this,bt,hR).call(this),Lt(this,bt,fR).call(this),Ei(this,sa,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(he.USER_INACTIVE))!=null?e:!0),Lt(this,bt,mR).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",_e(this,ym)),(s=this.media)==null||s.addEventListener("loadstart",_e(this,bm)),this.media&&(this.media.metadata=zd(this))}},kR=function(){var i,e;try{(i=window==null?void 0:window.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window==null?void 0:window.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},QE=function(i){Object.assign(_e(this,Fo),i),Lt(this,bt,ra).call(this)},ra=function(i={}){LU(kU($U(this,{..._e(this,Fo),...i})),this.shadowRoot)},cR=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(zE.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};Ei(this,Xd,new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)})),_e(this,Xd).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},hR=function(){var i,e;this.addEventListener("error",_e(this,Sm)),this.addEventListener("click",_e(this,Tm)),(i=this.mediaTheme)==null||i.addEventListener("close",_e(this,_m)),(e=this.mediaTheme)==null||e.addEventListener("focusin",_e(this,Am)),this.media&&(this.media.errorTranslator=(t={})=>{var s,r,n;if(!(((s=this.media)==null?void 0:s.error)instanceof X))return t;let a=LR((r=this.media)==null?void 0:r.error,!1);return{player_error_code:(n=this.media)==null?void 0:n.error.code,player_error_message:a.message?String(a.message):t.player_error_message,player_error_context:a.context?String(a.context):t.player_error_context}})},fR=function(){var i,e,t,s;(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",_e(this,Uo)),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",_e(this,Uo))},mR=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===He.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(d,u,c=!1)=>{r()||Array.from(d&&d.activeCues||[]).forEach(h=>{if(!(!h.snapToLines||h.line<-5||h.line>=0&&h.line<10))if(!u||this.paused){let f=h.text.split(`
|
|
3406
3406
|
`).length,m=-3;this.streamType===He.LIVE&&(m=-2);let p=m-f;if(h.line===p&&!c)return;s.has(h)||s.set(h,h.line),h.line=p}else setTimeout(()=>{h.line=s.get(h)||"auto"},500)})},a=()=>{var d,u;n(t,(u=(d=this.mediaController)==null?void 0:d.hasAttribute(he.USER_INACTIVE))!=null?u:!1)},o=()=>{var d,u;let c=Array.from(((u=(d=this.mediaController)==null?void 0:d.media)==null?void 0:u.textTracks)||[]).filter(h=>["subtitles","captions"].includes(h.kind)&&h.mode==="showing")[0];c!==t&&(t==null||t.removeEventListener("cuechange",a)),t=c,t==null||t.addEventListener("cuechange",a),n(t,_e(this,sa))};o(),(i=this.textTracks)==null||i.addEventListener("change",o),(e=this.textTracks)==null||e.addEventListener("addtrack",o);let l=()=>{var d,u;let c=(u=(d=this.mediaController)==null?void 0:d.hasAttribute(he.USER_INACTIVE))!=null?u:!0;_e(this,sa)!==c&&(Ei(this,sa,c),n(t,_e(this,sa)))};this.addEventListener("userinactivechange",l),Ei(this,Zd,()=>{var d,u;t==null||t.removeEventListener("cuechange",a),(d=this.textTracks)==null||d.removeEventListener("change",o),(u=this.textTracks)==null||u.removeEventListener("addtrack",o),this.removeEventListener("userinactivechange",l)})};function $s(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var Rm=jU;eu.customElements.get("mux-player")||(eu.customElements.define("mux-player",Rm),eu.MuxPlayerElement=Rm);var rG=Rm;})();
|
|
3407
3407
|
/*! Bundled license information:
|
|
3408
3408
|
|