@vouchfor/embeds 6.0.0 → 6.1.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.
@@ -1,4 +1,4 @@
1
- var playerEmbed=function(ct){"use strict";/**
1
+ var playerEmbed=function(at){"use strict";/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: BSD-3-Clause
@@ -62,7 +62,7 @@ var playerEmbed=function(ct){"use strict";/**
62
62
  * @license
63
63
  * Copyright 2020 Google LLC
64
64
  * SPDX-License-Identifier: BSD-3-Clause
65
- */const xt=()=>new dp;let dp=class{};const ga=new WeakMap,Qt=kr(class extends wc{render(r){return ut}update(r,[e]){var i;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(i=r.options)==null?void 0:i.host,this.rt(this.ct=r.element)),ut}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=ga.get(e);t===void 0&&(t=new WeakMap,ga.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){var r,e;return typeof this.G=="function"?(r=ga.get(this.ht??globalThis))==null?void 0:r.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function fp(r,e,t){function i(n){t.dispatchEvent(new CustomEvent(n.type,n))}return e.addEventListener(r,i),()=>{e.removeEventListener(r,i)}}class gp{constructor(e,t){this._events=[],this._cleanup=[],this._forwardElementRef=xt(),this.host=e,this._events=t,e.addController(this)}register(){return Qt(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(e=>{this._forwardElementRef.value&&this._cleanup.push(fp(e,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(e=>{e()}),this._cleanup=[]}}/**
65
+ */const Qt=()=>new dp;let dp=class{};const ga=new WeakMap,_t=kr(class extends wc{render(r){return ut}update(r,[e]){var i;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(i=r.options)==null?void 0:i.host,this.rt(this.ct=r.element)),ut}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=ga.get(e);t===void 0&&(t=new WeakMap,ga.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){var r,e;return typeof this.G=="function"?(r=ga.get(this.ht??globalThis))==null?void 0:r.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function fp(r,e,t){function i(n){t.dispatchEvent(new CustomEvent(n.type,n))}return e.addEventListener(r,i),()=>{e.removeEventListener(r,i)}}class gp{constructor(e,t){this._events=[],this._cleanup=[],this._forwardElementRef=Qt(),this.host=e,this._events=t,e.addController(this)}register(){return _t(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(e=>{this._forwardElementRef.value&&this._cleanup.push(fp(e,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(e=>{e()}),this._cleanup=[]}}/**
66
66
  * @license
67
67
  * Copyright 2019 Google LLC
68
68
  * SPDX-License-Identifier: BSD-3-Clause
@@ -105,12 +105,12 @@ ${e}`,Mm=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Fm=Objec
105
105
  `+e.join(`
106
106
  `)+`
107
107
  ----------`);var c=new Function("compile",e.join(`
108
- `));return c(dE.bind(void 0,r))}var gE=fE,pE=gE;function mE(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function EE(r){var e=new mE;e.pre=r.pre,e.body=r.body,e.post=r.post;var t=r.args.slice(0);e.argTypes=t;for(var i=0;i<t.length;++i){var n=t[i];if(n==="array"||typeof n=="object"&&n.blockIndices){if(e.argTypes[i]="array",e.arrayArgs.push(i),e.arrayBlockIndices.push(n.blockIndices?n.blockIndices:0),e.shimArgs.push("array"+i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array args");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array args")}else if(n==="scalar")e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if(n==="index"){if(e.indexArgs.push(i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array index");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array index");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array index")}else if(n==="shape"){if(e.shapeArgs.push(i),i<e.pre.args.length&&e.pre.args[i].lvalue)throw new Error("cwise: pre() block may not write to array shape");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array shape");if(i<e.post.args.length&&e.post.args[i].lvalue)throw new Error("cwise: post() block may not write to array shape")}else if(typeof n=="object"&&n.offset)e.argTypes[i]="offset",e.offsetArgs.push({array:n.array,offset:n.offset}),e.offsetArgIndex.push(i);else throw new Error("cwise: Unknown argument type "+t[i])}if(e.arrayArgs.length<=0)throw new Error("cwise: No array arguments specified");if(e.pre.args.length>t.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>t.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>t.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!r.printCode||!!r.debug,e.funcName=r.funcName||"cwise",e.blockSize=r.blockSize||64,pE(e)}var IE=EE;(function(r){var e=IE,t={body:"",args:[],thisVars:[],localVars:[]};function i(h){if(!h)return t;for(var d=0;d<h.args.length;++d){var f=h.args[d];d===0?h.args[d]={name:f,lvalue:!0,rvalue:!!h.rvalue,count:h.count||1}:h.args[d]={name:f,lvalue:!1,rvalue:!0,count:1}}return h.thisVars||(h.thisVars=[]),h.localVars||(h.localVars=[]),h}function n(h){return e({args:h.args,pre:i(h.pre),body:i(h.body),post:i(h.proc),funcName:h.funcName})}function s(h){for(var d=[],f=0;f<h.args.length;++f)d.push("a"+f);var g=new Function("P",["return function ",h.funcName,"_ndarrayops(",d.join(","),") {P(",d.join(","),");return a0}"].join(""));return g(n(h))}var o={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};(function(){for(var h in o){var d=o[h];r[h]=s({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+d+"c"},funcName:h}),r[h+"eq"]=s({args:["array","array"],body:{args:["a","b"],body:"a"+d+"=b"},funcName:h+"eq"}),r[h+"s"]=s({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+d+"s"},funcName:h+"s"}),r[h+"seq"]=s({args:["array","scalar"],body:{args:["a","s"],body:"a"+d+"=s"},funcName:h+"seq"})}})();var a={not:"!",bnot:"~",neg:"-",recip:"1.0/"};(function(){for(var h in a){var d=a[h];r[h]=s({args:["array","array"],body:{args:["a","b"],body:"a="+d+"b"},funcName:h}),r[h+"eq"]=s({args:["array"],body:{args:["a"],body:"a="+d+"a"},funcName:h+"eq"})}})();var l={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};(function(){for(var h in l){var d=l[h];r[h]=s({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+d+"c"},funcName:h}),r[h+"s"]=s({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+d+"s"},funcName:h+"s"}),r[h+"eq"]=s({args:["array","array"],body:{args:["a","b"],body:"a=a"+d+"b"},funcName:h+"eq"}),r[h+"seq"]=s({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+d+"s"},funcName:h+"seq"})}})();var A=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];(function(){for(var h=0;h<A.length;++h){var d=A[h];r[d]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:d}),r[d+"eq"]=s({args:["array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},funcName:d+"eq"})}})();var u=["max","min","atan2","pow"];(function(){for(var h=0;h<u.length;++h){var d=u[h];r[d]=s({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:d}),r[d+"s"]=s({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:d+"s"}),r[d+"eq"]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},funcName:d+"eq"}),r[d+"seq"]=s({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},funcName:d+"seq"})}})();var c=["atan2","pow"];(function(){for(var h=0;h<c.length;++h){var d=c[h];r[d+"op"]=s({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:d+"op"}),r[d+"ops"]=s({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:d+"ops"}),r[d+"opeq"]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},funcName:d+"opeq"}),r[d+"opseq"]=s({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},funcName:d+"opseq"})}})(),r.any=e({args:["array"],pre:t,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"}),r.all=e({args:["array"],pre:t,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"}),r.sum=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"}),r.prod=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"}),r.norm2squared=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"}),r.norm2=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"}),r.norminf=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=e({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=e({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.argmin=e({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.argmax=e({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=s({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=s({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=s({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=e({args:["array","array"],pre:t,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})})(du);var Pe={},at={},Fa=32;at.INT_BITS=Fa,at.INT_MAX=2147483647,at.INT_MIN=-1<<Fa-1,at.sign=function(r){return(r>0)-(r<0)},at.abs=function(r){var e=r>>Fa-1;return(r^e)-e},at.min=function(r,e){return e^(r^e)&-(r<e)},at.max=function(r,e){return r^(r^e)&-(r<e)},at.isPow2=function(r){return!(r&r-1)&&!!r},at.log2=function(r){var e,t;return e=(r>65535)<<4,r>>>=e,t=(r>255)<<3,r>>>=t,e|=t,t=(r>15)<<2,r>>>=t,e|=t,t=(r>3)<<1,r>>>=t,e|=t,e|r>>1},at.log10=function(r){return r>=1e9?9:r>=1e8?8:r>=1e7?7:r>=1e6?6:r>=1e5?5:r>=1e4?4:r>=1e3?3:r>=100?2:r>=10?1:0},at.popCount=function(r){return r=r-(r>>>1&1431655765),r=(r&858993459)+(r>>>2&858993459),(r+(r>>>4)&252645135)*16843009>>>24};function gu(r){var e=32;return r&=-r,r&&e--,r&65535&&(e-=16),r&16711935&&(e-=8),r&252645135&&(e-=4),r&858993459&&(e-=2),r&1431655765&&(e-=1),e}at.countTrailingZeros=gu,at.nextPow2=function(r){return r+=r===0,--r,r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r+1},at.prevPow2=function(r){return r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r-(r>>>1)},at.parity=function(r){return r^=r>>>16,r^=r>>>8,r^=r>>>4,r&=15,27030>>>r&1};var Rn=new Array(256);(function(r){for(var e=0;e<256;++e){var t=e,i=e,n=7;for(t>>>=1;t;t>>>=1)i<<=1,i|=t&1,--n;r[e]=i<<n&255}})(Rn),at.reverse=function(r){return Rn[r&255]<<24|Rn[r>>>8&255]<<16|Rn[r>>>16&255]<<8|Rn[r>>>24&255]},at.interleave2=function(r,e){return r&=65535,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e&=65535,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1},at.deinterleave2=function(r,e){return r=r>>>e&1431655765,r=(r|r>>>1)&858993459,r=(r|r>>>2)&252645135,r=(r|r>>>4)&16711935,r=(r|r>>>16)&65535,r<<16>>16},at.interleave3=function(r,e,t){return r&=1023,r=(r|r<<16)&4278190335,r=(r|r<<8)&251719695,r=(r|r<<4)&3272356035,r=(r|r<<2)&1227133513,e&=1023,e=(e|e<<16)&4278190335,e=(e|e<<8)&251719695,e=(e|e<<4)&3272356035,e=(e|e<<2)&1227133513,r|=e<<1,t&=1023,t=(t|t<<16)&4278190335,t=(t|t<<8)&251719695,t=(t|t<<4)&3272356035,t=(t|t<<2)&1227133513,r|t<<2},at.deinterleave3=function(r,e){return r=r>>>e&1227133513,r=(r|r>>>2)&3272356035,r=(r|r>>>4)&251719695,r=(r|r>>>8)&4278190335,r=(r|r>>>16)&1023,r<<22>>22},at.nextCombination=function(r){var e=r|r-1;return e+1|(~e&-~e)-1>>>gu(r)+1};function pu(r,e,t){var i=r[t]|0;if(i<=0)return[];var n=new Array(i),s;if(t===r.length-1)for(s=0;s<i;++s)n[s]=e;else for(s=0;s<i;++s)n[s]=pu(r,e,t+1);return n}function vE(r,e){var t,i;for(t=new Array(r),i=0;i<r;++i)t[i]=e;return t}function yE(r,e){switch(typeof e>"u"&&(e=0),typeof r){case"number":if(r>0)return vE(r|0,e);break;case"object":if(typeof r.length=="number")return pu(r,e,0);break}return[]}var CE=yE,mu={},Os={};Os.byteLength=SE,Os.toByteArray=xE,Os.fromByteArray=wE;for(var oi=[],Yt=[],BE=typeof Uint8Array<"u"?Uint8Array:Array,Pa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Mr=0,TE=Pa.length;Mr<TE;++Mr)oi[Mr]=Pa[Mr],Yt[Pa.charCodeAt(Mr)]=Mr;Yt[45]=62,Yt[95]=63;function Eu(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function SE(r){var e=Eu(r),t=e[0],i=e[1];return(t+i)*3/4-i}function bE(r,e,t){return(e+t)*3/4-t}function xE(r){var e,t=Eu(r),i=t[0],n=t[1],s=new BE(bE(r,i,n)),o=0,a=n>0?i-4:i,l;for(l=0;l<a;l+=4)e=Yt[r.charCodeAt(l)]<<18|Yt[r.charCodeAt(l+1)]<<12|Yt[r.charCodeAt(l+2)]<<6|Yt[r.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return n===2&&(e=Yt[r.charCodeAt(l)]<<2|Yt[r.charCodeAt(l+1)]>>4,s[o++]=e&255),n===1&&(e=Yt[r.charCodeAt(l)]<<10|Yt[r.charCodeAt(l+1)]<<4|Yt[r.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function QE(r){return oi[r>>18&63]+oi[r>>12&63]+oi[r>>6&63]+oi[r&63]}function _E(r,e,t){for(var i,n=[],s=e;s<t;s+=3)i=(r[s]<<16&16711680)+(r[s+1]<<8&65280)+(r[s+2]&255),n.push(QE(i));return n.join("")}function wE(r){for(var e,t=r.length,i=t%3,n=[],s=16383,o=0,a=t-i;o<a;o+=s)n.push(_E(r,o,o+s>a?a:o+s));return i===1?(e=r[t-1],n.push(oi[e>>2]+oi[e<<4&63]+"==")):i===2&&(e=(r[t-2]<<8)+r[t-1],n.push(oi[e>>10]+oi[e>>4&63]+oi[e<<2&63]+"=")),n.join("")}var Na={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Na.read=function(r,e,t,i,n){var s,o,a=n*8-i-1,l=(1<<a)-1,A=l>>1,u=-7,c=t?n-1:0,h=t?-1:1,d=r[e+c];for(c+=h,s=d&(1<<-u)-1,d>>=-u,u+=a;u>0;s=s*256+r[e+c],c+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+r[e+c],c+=h,u-=8);if(s===0)s=1-A;else{if(s===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-A}return(d?-1:1)*o*Math.pow(2,s-i)},Na.write=function(r,e,t,i,n,s){var o,a,l,A=s*8-n-1,u=(1<<A)-1,c=u>>1,h=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:s-1,f=i?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+c>=1?e+=h/l:e+=h*Math.pow(2,1-c),e*l>=2&&(o++,l/=2),o+c>=u?(a=0,o=u):o+c>=1?(a=(e*l-1)*Math.pow(2,n),o=o+c):(a=e*Math.pow(2,c-1)*Math.pow(2,n),o=0));n>=8;r[t+d]=a&255,d+=f,a/=256,n-=8);for(o=o<<n|a,A+=n;A>0;r[t+d]=o&255,d+=f,o/=256,A-=8);r[t+d-f]|=g*128};/*!
108
+ `));return c(dE.bind(void 0,r))}var gE=fE,pE=gE;function mE(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function EE(r){var e=new mE;e.pre=r.pre,e.body=r.body,e.post=r.post;var t=r.args.slice(0);e.argTypes=t;for(var i=0;i<t.length;++i){var n=t[i];if(n==="array"||typeof n=="object"&&n.blockIndices){if(e.argTypes[i]="array",e.arrayArgs.push(i),e.arrayBlockIndices.push(n.blockIndices?n.blockIndices:0),e.shimArgs.push("array"+i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array args");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array args")}else if(n==="scalar")e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if(n==="index"){if(e.indexArgs.push(i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array index");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array index");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array index")}else if(n==="shape"){if(e.shapeArgs.push(i),i<e.pre.args.length&&e.pre.args[i].lvalue)throw new Error("cwise: pre() block may not write to array shape");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array shape");if(i<e.post.args.length&&e.post.args[i].lvalue)throw new Error("cwise: post() block may not write to array shape")}else if(typeof n=="object"&&n.offset)e.argTypes[i]="offset",e.offsetArgs.push({array:n.array,offset:n.offset}),e.offsetArgIndex.push(i);else throw new Error("cwise: Unknown argument type "+t[i])}if(e.arrayArgs.length<=0)throw new Error("cwise: No array arguments specified");if(e.pre.args.length>t.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>t.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>t.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!r.printCode||!!r.debug,e.funcName=r.funcName||"cwise",e.blockSize=r.blockSize||64,pE(e)}var IE=EE;(function(r){var e=IE,t={body:"",args:[],thisVars:[],localVars:[]};function i(h){if(!h)return t;for(var d=0;d<h.args.length;++d){var f=h.args[d];d===0?h.args[d]={name:f,lvalue:!0,rvalue:!!h.rvalue,count:h.count||1}:h.args[d]={name:f,lvalue:!1,rvalue:!0,count:1}}return h.thisVars||(h.thisVars=[]),h.localVars||(h.localVars=[]),h}function n(h){return e({args:h.args,pre:i(h.pre),body:i(h.body),post:i(h.proc),funcName:h.funcName})}function s(h){for(var d=[],f=0;f<h.args.length;++f)d.push("a"+f);var g=new Function("P",["return function ",h.funcName,"_ndarrayops(",d.join(","),") {P(",d.join(","),");return a0}"].join(""));return g(n(h))}var o={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};(function(){for(var h in o){var d=o[h];r[h]=s({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+d+"c"},funcName:h}),r[h+"eq"]=s({args:["array","array"],body:{args:["a","b"],body:"a"+d+"=b"},funcName:h+"eq"}),r[h+"s"]=s({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+d+"s"},funcName:h+"s"}),r[h+"seq"]=s({args:["array","scalar"],body:{args:["a","s"],body:"a"+d+"=s"},funcName:h+"seq"})}})();var a={not:"!",bnot:"~",neg:"-",recip:"1.0/"};(function(){for(var h in a){var d=a[h];r[h]=s({args:["array","array"],body:{args:["a","b"],body:"a="+d+"b"},funcName:h}),r[h+"eq"]=s({args:["array"],body:{args:["a"],body:"a="+d+"a"},funcName:h+"eq"})}})();var l={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};(function(){for(var h in l){var d=l[h];r[h]=s({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+d+"c"},funcName:h}),r[h+"s"]=s({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+d+"s"},funcName:h+"s"}),r[h+"eq"]=s({args:["array","array"],body:{args:["a","b"],body:"a=a"+d+"b"},funcName:h+"eq"}),r[h+"seq"]=s({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+d+"s"},funcName:h+"seq"})}})();var A=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];(function(){for(var h=0;h<A.length;++h){var d=A[h];r[d]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:d}),r[d+"eq"]=s({args:["array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},funcName:d+"eq"})}})();var u=["max","min","atan2","pow"];(function(){for(var h=0;h<u.length;++h){var d=u[h];r[d]=s({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:d}),r[d+"s"]=s({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:d+"s"}),r[d+"eq"]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},funcName:d+"eq"}),r[d+"seq"]=s({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},funcName:d+"seq"})}})();var c=["atan2","pow"];(function(){for(var h=0;h<c.length;++h){var d=c[h];r[d+"op"]=s({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:d+"op"}),r[d+"ops"]=s({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:d+"ops"}),r[d+"opeq"]=s({args:["array","array"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},funcName:d+"opeq"}),r[d+"opseq"]=s({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+d,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},funcName:d+"opseq"})}})(),r.any=e({args:["array"],pre:t,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"}),r.all=e({args:["array"],pre:t,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"}),r.sum=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"}),r.prod=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"}),r.norm2squared=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"}),r.norm2=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"}),r.norminf=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=e({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=e({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=e({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.argmin=e({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.argmax=e({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=s({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=s({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=s({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=e({args:["array","array"],pre:t,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})})(du);var Pe={},lt={},Fa=32;lt.INT_BITS=Fa,lt.INT_MAX=2147483647,lt.INT_MIN=-1<<Fa-1,lt.sign=function(r){return(r>0)-(r<0)},lt.abs=function(r){var e=r>>Fa-1;return(r^e)-e},lt.min=function(r,e){return e^(r^e)&-(r<e)},lt.max=function(r,e){return r^(r^e)&-(r<e)},lt.isPow2=function(r){return!(r&r-1)&&!!r},lt.log2=function(r){var e,t;return e=(r>65535)<<4,r>>>=e,t=(r>255)<<3,r>>>=t,e|=t,t=(r>15)<<2,r>>>=t,e|=t,t=(r>3)<<1,r>>>=t,e|=t,e|r>>1},lt.log10=function(r){return r>=1e9?9:r>=1e8?8:r>=1e7?7:r>=1e6?6:r>=1e5?5:r>=1e4?4:r>=1e3?3:r>=100?2:r>=10?1:0},lt.popCount=function(r){return r=r-(r>>>1&1431655765),r=(r&858993459)+(r>>>2&858993459),(r+(r>>>4)&252645135)*16843009>>>24};function gu(r){var e=32;return r&=-r,r&&e--,r&65535&&(e-=16),r&16711935&&(e-=8),r&252645135&&(e-=4),r&858993459&&(e-=2),r&1431655765&&(e-=1),e}lt.countTrailingZeros=gu,lt.nextPow2=function(r){return r+=r===0,--r,r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r+1},lt.prevPow2=function(r){return r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r-(r>>>1)},lt.parity=function(r){return r^=r>>>16,r^=r>>>8,r^=r>>>4,r&=15,27030>>>r&1};var Rn=new Array(256);(function(r){for(var e=0;e<256;++e){var t=e,i=e,n=7;for(t>>>=1;t;t>>>=1)i<<=1,i|=t&1,--n;r[e]=i<<n&255}})(Rn),lt.reverse=function(r){return Rn[r&255]<<24|Rn[r>>>8&255]<<16|Rn[r>>>16&255]<<8|Rn[r>>>24&255]},lt.interleave2=function(r,e){return r&=65535,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e&=65535,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1},lt.deinterleave2=function(r,e){return r=r>>>e&1431655765,r=(r|r>>>1)&858993459,r=(r|r>>>2)&252645135,r=(r|r>>>4)&16711935,r=(r|r>>>16)&65535,r<<16>>16},lt.interleave3=function(r,e,t){return r&=1023,r=(r|r<<16)&4278190335,r=(r|r<<8)&251719695,r=(r|r<<4)&3272356035,r=(r|r<<2)&1227133513,e&=1023,e=(e|e<<16)&4278190335,e=(e|e<<8)&251719695,e=(e|e<<4)&3272356035,e=(e|e<<2)&1227133513,r|=e<<1,t&=1023,t=(t|t<<16)&4278190335,t=(t|t<<8)&251719695,t=(t|t<<4)&3272356035,t=(t|t<<2)&1227133513,r|t<<2},lt.deinterleave3=function(r,e){return r=r>>>e&1227133513,r=(r|r>>>2)&3272356035,r=(r|r>>>4)&251719695,r=(r|r>>>8)&4278190335,r=(r|r>>>16)&1023,r<<22>>22},lt.nextCombination=function(r){var e=r|r-1;return e+1|(~e&-~e)-1>>>gu(r)+1};function pu(r,e,t){var i=r[t]|0;if(i<=0)return[];var n=new Array(i),s;if(t===r.length-1)for(s=0;s<i;++s)n[s]=e;else for(s=0;s<i;++s)n[s]=pu(r,e,t+1);return n}function vE(r,e){var t,i;for(t=new Array(r),i=0;i<r;++i)t[i]=e;return t}function yE(r,e){switch(typeof e>"u"&&(e=0),typeof r){case"number":if(r>0)return vE(r|0,e);break;case"object":if(typeof r.length=="number")return pu(r,e,0);break}return[]}var CE=yE,mu={},Os={};Os.byteLength=SE,Os.toByteArray=xE,Os.fromByteArray=wE;for(var oi=[],Yt=[],BE=typeof Uint8Array<"u"?Uint8Array:Array,Pa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Mr=0,TE=Pa.length;Mr<TE;++Mr)oi[Mr]=Pa[Mr],Yt[Pa.charCodeAt(Mr)]=Mr;Yt[45]=62,Yt[95]=63;function Eu(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function SE(r){var e=Eu(r),t=e[0],i=e[1];return(t+i)*3/4-i}function bE(r,e,t){return(e+t)*3/4-t}function xE(r){var e,t=Eu(r),i=t[0],n=t[1],s=new BE(bE(r,i,n)),o=0,a=n>0?i-4:i,l;for(l=0;l<a;l+=4)e=Yt[r.charCodeAt(l)]<<18|Yt[r.charCodeAt(l+1)]<<12|Yt[r.charCodeAt(l+2)]<<6|Yt[r.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return n===2&&(e=Yt[r.charCodeAt(l)]<<2|Yt[r.charCodeAt(l+1)]>>4,s[o++]=e&255),n===1&&(e=Yt[r.charCodeAt(l)]<<10|Yt[r.charCodeAt(l+1)]<<4|Yt[r.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function QE(r){return oi[r>>18&63]+oi[r>>12&63]+oi[r>>6&63]+oi[r&63]}function _E(r,e,t){for(var i,n=[],s=e;s<t;s+=3)i=(r[s]<<16&16711680)+(r[s+1]<<8&65280)+(r[s+2]&255),n.push(QE(i));return n.join("")}function wE(r){for(var e,t=r.length,i=t%3,n=[],s=16383,o=0,a=t-i;o<a;o+=s)n.push(_E(r,o,o+s>a?a:o+s));return i===1?(e=r[t-1],n.push(oi[e>>2]+oi[e<<4&63]+"==")):i===2&&(e=(r[t-2]<<8)+r[t-1],n.push(oi[e>>10]+oi[e>>4&63]+oi[e<<2&63]+"=")),n.join("")}var Na={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Na.read=function(r,e,t,i,n){var s,o,a=n*8-i-1,l=(1<<a)-1,A=l>>1,u=-7,c=t?n-1:0,h=t?-1:1,d=r[e+c];for(c+=h,s=d&(1<<-u)-1,d>>=-u,u+=a;u>0;s=s*256+r[e+c],c+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+r[e+c],c+=h,u-=8);if(s===0)s=1-A;else{if(s===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-A}return(d?-1:1)*o*Math.pow(2,s-i)},Na.write=function(r,e,t,i,n,s){var o,a,l,A=s*8-n-1,u=(1<<A)-1,c=u>>1,h=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:s-1,f=i?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+c>=1?e+=h/l:e+=h*Math.pow(2,1-c),e*l>=2&&(o++,l/=2),o+c>=u?(a=0,o=u):o+c>=1?(a=(e*l-1)*Math.pow(2,n),o=o+c):(a=e*Math.pow(2,c-1)*Math.pow(2,n),o=0));n>=8;r[t+d]=a&255,d+=f,a/=256,n-=8);for(o=o<<n|a,A+=n;A>0;r[t+d]=o&255,d+=f,o/=256,A-=8);r[t+d-f]|=g*128};/*!
109
109
  * The buffer module from node.js, for the browser.
110
110
  *
111
111
  * @author Feross Aboukhadijeh <https://feross.org>
112
112
  * @license MIT
113
- */(function(r){const e=Os,t=Na,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=a,r.SlowBuffer=B,r.INSPECT_MAX_BYTES=50;const n=2147483647;r.kMaxLength=n,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const T=new Uint8Array(1),m={foo:function(){return 42}};return Object.setPrototypeOf(m,Uint8Array.prototype),Object.setPrototypeOf(T,m),T.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(T){if(T>n)throw new RangeError('The value "'+T+'" is invalid for option "size"');const m=new Uint8Array(T);return Object.setPrototypeOf(m,a.prototype),m}function a(T,m,E){if(typeof T=="number"){if(typeof m=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return c(T)}return l(T,m,E)}a.poolSize=8192;function l(T,m,E){if(typeof T=="string")return h(T,m);if(ArrayBuffer.isView(T))return f(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Ce(T,ArrayBuffer)||T&&Ce(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ce(T,SharedArrayBuffer)||T&&Ce(T.buffer,SharedArrayBuffer)))return g(T,m,E);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const Q=T.valueOf&&T.valueOf();if(Q!=null&&Q!==T)return a.from(Q,m,E);const N=p(T);if(N)return N;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return a.from(T[Symbol.toPrimitive]("string"),m,E);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}a.from=function(T,m,E){return l(T,m,E)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function A(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function u(T,m,E){return A(T),T<=0?o(T):m!==void 0?typeof E=="string"?o(T).fill(m,E):o(T).fill(m):o(T)}a.alloc=function(T,m,E){return u(T,m,E)};function c(T){return A(T),o(T<0?0:v(T)|0)}a.allocUnsafe=function(T){return c(T)},a.allocUnsafeSlow=function(T){return c(T)};function h(T,m){if((typeof m!="string"||m==="")&&(m="utf8"),!a.isEncoding(m))throw new TypeError("Unknown encoding: "+m);const E=C(T,m)|0;let Q=o(E);const N=Q.write(T,m);return N!==E&&(Q=Q.slice(0,N)),Q}function d(T){const m=T.length<0?0:v(T.length)|0,E=o(m);for(let Q=0;Q<m;Q+=1)E[Q]=T[Q]&255;return E}function f(T){if(Ce(T,Uint8Array)){const m=new Uint8Array(T);return g(m.buffer,m.byteOffset,m.byteLength)}return d(T)}function g(T,m,E){if(m<0||T.byteLength<m)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<m+(E||0))throw new RangeError('"length" is outside of buffer bounds');let Q;return m===void 0&&E===void 0?Q=new Uint8Array(T):E===void 0?Q=new Uint8Array(T,m):Q=new Uint8Array(T,m,E),Object.setPrototypeOf(Q,a.prototype),Q}function p(T){if(a.isBuffer(T)){const m=v(T.length)|0,E=o(m);return E.length===0||T.copy(E,0,0,m),E}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):d(T);if(T.type==="Buffer"&&Array.isArray(T.data))return d(T.data)}function v(T){if(T>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return T|0}function B(T){return+T!=T&&(T=0),a.alloc(+T)}a.isBuffer=function(m){return m!=null&&m._isBuffer===!0&&m!==a.prototype},a.compare=function(m,E){if(Ce(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),Ce(E,Uint8Array)&&(E=a.from(E,E.offset,E.byteLength)),!a.isBuffer(m)||!a.isBuffer(E))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(m===E)return 0;let Q=m.length,N=E.length;for(let J=0,z=Math.min(Q,N);J<z;++J)if(m[J]!==E[J]){Q=m[J],N=E[J];break}return Q<N?-1:N<Q?1:0},a.isEncoding=function(m){switch(String(m).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(m,E){if(!Array.isArray(m))throw new TypeError('"list" argument must be an Array of Buffers');if(m.length===0)return a.alloc(0);let Q;if(E===void 0)for(E=0,Q=0;Q<m.length;++Q)E+=m[Q].length;const N=a.allocUnsafe(E);let J=0;for(Q=0;Q<m.length;++Q){let z=m[Q];if(Ce(z,Uint8Array))J+z.length>N.length?(a.isBuffer(z)||(z=a.from(z)),z.copy(N,J)):Uint8Array.prototype.set.call(N,z,J);else if(a.isBuffer(z))z.copy(N,J);else throw new TypeError('"list" argument must be an Array of Buffers');J+=z.length}return N};function C(T,m){if(a.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Ce(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);const E=T.length,Q=arguments.length>2&&arguments[2]===!0;if(!Q&&E===0)return 0;let N=!1;for(;;)switch(m){case"ascii":case"latin1":case"binary":return E;case"utf8":case"utf-8":return ke(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E*2;case"hex":return E>>>1;case"base64":return Ge(T).length;default:if(N)return Q?-1:ke(T).length;m=(""+m).toLowerCase(),N=!0}}a.byteLength=C;function y(T,m,E){let Q=!1;if((m===void 0||m<0)&&(m=0),m>this.length||((E===void 0||E>this.length)&&(E=this.length),E<=0)||(E>>>=0,m>>>=0,E<=m))return"";for(T||(T="utf8");;)switch(T){case"hex":return _(this,m,E);case"utf8":case"utf-8":return oe(this,m,E);case"ascii":return q(this,m,E);case"latin1":case"binary":return R(this,m,E);case"base64":return le(this,m,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,m,E);default:if(Q)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),Q=!0}}a.prototype._isBuffer=!0;function x(T,m,E){const Q=T[m];T[m]=T[E],T[E]=Q}a.prototype.swap16=function(){const m=this.length;if(m%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let E=0;E<m;E+=2)x(this,E,E+1);return this},a.prototype.swap32=function(){const m=this.length;if(m%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let E=0;E<m;E+=4)x(this,E,E+3),x(this,E+1,E+2);return this},a.prototype.swap64=function(){const m=this.length;if(m%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let E=0;E<m;E+=8)x(this,E,E+7),x(this,E+1,E+6),x(this,E+2,E+5),x(this,E+3,E+4);return this},a.prototype.toString=function(){const m=this.length;return m===0?"":arguments.length===0?oe(this,0,m):y.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(m){if(!a.isBuffer(m))throw new TypeError("Argument must be a Buffer");return this===m?!0:a.compare(this,m)===0},a.prototype.inspect=function(){let m="";const E=r.INSPECT_MAX_BYTES;return m=this.toString("hex",0,E).replace(/(.{2})/g,"$1 ").trim(),this.length>E&&(m+=" ... "),"<Buffer "+m+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(m,E,Q,N,J){if(Ce(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(m))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof m);if(E===void 0&&(E=0),Q===void 0&&(Q=m?m.length:0),N===void 0&&(N=0),J===void 0&&(J=this.length),E<0||Q>m.length||N<0||J>this.length)throw new RangeError("out of range index");if(N>=J&&E>=Q)return 0;if(N>=J)return-1;if(E>=Q)return 1;if(E>>>=0,Q>>>=0,N>>>=0,J>>>=0,this===m)return 0;let z=J-N,$=Q-E;const ae=Math.min(z,$),ue=this.slice(N,J),ve=m.slice(E,Q);for(let me=0;me<ae;++me)if(ue[me]!==ve[me]){z=ue[me],$=ve[me];break}return z<$?-1:$<z?1:0};function w(T,m,E,Q,N){if(T.length===0)return-1;if(typeof E=="string"?(Q=E,E=0):E>2147483647?E=2147483647:E<-2147483648&&(E=-2147483648),E=+E,et(E)&&(E=N?0:T.length-1),E<0&&(E=T.length+E),E>=T.length){if(N)return-1;E=T.length-1}else if(E<0)if(N)E=0;else return-1;if(typeof m=="string"&&(m=a.from(m,Q)),a.isBuffer(m))return m.length===0?-1:D(T,m,E,Q,N);if(typeof m=="number")return m=m&255,typeof Uint8Array.prototype.indexOf=="function"?N?Uint8Array.prototype.indexOf.call(T,m,E):Uint8Array.prototype.lastIndexOf.call(T,m,E):D(T,[m],E,Q,N);throw new TypeError("val must be string, number or Buffer")}function D(T,m,E,Q,N){let J=1,z=T.length,$=m.length;if(Q!==void 0&&(Q=String(Q).toLowerCase(),Q==="ucs2"||Q==="ucs-2"||Q==="utf16le"||Q==="utf-16le")){if(T.length<2||m.length<2)return-1;J=2,z/=2,$/=2,E/=2}function ae(ve,me){return J===1?ve[me]:ve.readUInt16BE(me*J)}let ue;if(N){let ve=-1;for(ue=E;ue<z;ue++)if(ae(T,ue)===ae(m,ve===-1?0:ue-ve)){if(ve===-1&&(ve=ue),ue-ve+1===$)return ve*J}else ve!==-1&&(ue-=ue-ve),ve=-1}else for(E+$>z&&(E=z-$),ue=E;ue>=0;ue--){let ve=!0;for(let me=0;me<$;me++)if(ae(T,ue+me)!==ae(m,me)){ve=!1;break}if(ve)return ue}return-1}a.prototype.includes=function(m,E,Q){return this.indexOf(m,E,Q)!==-1},a.prototype.indexOf=function(m,E,Q){return w(this,m,E,Q,!0)},a.prototype.lastIndexOf=function(m,E,Q){return w(this,m,E,Q,!1)};function F(T,m,E,Q){E=Number(E)||0;const N=T.length-E;Q?(Q=Number(Q),Q>N&&(Q=N)):Q=N;const J=m.length;Q>J/2&&(Q=J/2);let z;for(z=0;z<Q;++z){const $=parseInt(m.substr(z*2,2),16);if(et($))return z;T[E+z]=$}return z}function O(T,m,E,Q){return $e(ke(m,T.length-E),T,E,Q)}function M(T,m,E,Q){return $e(Ue(m),T,E,Q)}function j(T,m,E,Q){return $e(Ge(m),T,E,Q)}function X(T,m,E,Q){return $e(Xe(m,T.length-E),T,E,Q)}a.prototype.write=function(m,E,Q,N){if(E===void 0)N="utf8",Q=this.length,E=0;else if(Q===void 0&&typeof E=="string")N=E,Q=this.length,E=0;else if(isFinite(E))E=E>>>0,isFinite(Q)?(Q=Q>>>0,N===void 0&&(N="utf8")):(N=Q,Q=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const J=this.length-E;if((Q===void 0||Q>J)&&(Q=J),m.length>0&&(Q<0||E<0)||E>this.length)throw new RangeError("Attempt to write outside buffer bounds");N||(N="utf8");let z=!1;for(;;)switch(N){case"hex":return F(this,m,E,Q);case"utf8":case"utf-8":return O(this,m,E,Q);case"ascii":case"latin1":case"binary":return M(this,m,E,Q);case"base64":return j(this,m,E,Q);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X(this,m,E,Q);default:if(z)throw new TypeError("Unknown encoding: "+N);N=(""+N).toLowerCase(),z=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function le(T,m,E){return m===0&&E===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(m,E))}function oe(T,m,E){E=Math.min(T.length,E);const Q=[];let N=m;for(;N<E;){const J=T[N];let z=null,$=J>239?4:J>223?3:J>191?2:1;if(N+$<=E){let ae,ue,ve,me;switch($){case 1:J<128&&(z=J);break;case 2:ae=T[N+1],(ae&192)===128&&(me=(J&31)<<6|ae&63,me>127&&(z=me));break;case 3:ae=T[N+1],ue=T[N+2],(ae&192)===128&&(ue&192)===128&&(me=(J&15)<<12|(ae&63)<<6|ue&63,me>2047&&(me<55296||me>57343)&&(z=me));break;case 4:ae=T[N+1],ue=T[N+2],ve=T[N+3],(ae&192)===128&&(ue&192)===128&&(ve&192)===128&&(me=(J&15)<<18|(ae&63)<<12|(ue&63)<<6|ve&63,me>65535&&me<1114112&&(z=me))}}z===null?(z=65533,$=1):z>65535&&(z-=65536,Q.push(z>>>10&1023|55296),z=56320|z&1023),Q.push(z),N+=$}return U(Q)}const L=4096;function U(T){const m=T.length;if(m<=L)return String.fromCharCode.apply(String,T);let E="",Q=0;for(;Q<m;)E+=String.fromCharCode.apply(String,T.slice(Q,Q+=L));return E}function q(T,m,E){let Q="";E=Math.min(T.length,E);for(let N=m;N<E;++N)Q+=String.fromCharCode(T[N]&127);return Q}function R(T,m,E){let Q="";E=Math.min(T.length,E);for(let N=m;N<E;++N)Q+=String.fromCharCode(T[N]);return Q}function _(T,m,E){const Q=T.length;(!m||m<0)&&(m=0),(!E||E<0||E>Q)&&(E=Q);let N="";for(let J=m;J<E;++J)N+=ot[T[J]];return N}function k(T,m,E){const Q=T.slice(m,E);let N="";for(let J=0;J<Q.length-1;J+=2)N+=String.fromCharCode(Q[J]+Q[J+1]*256);return N}a.prototype.slice=function(m,E){const Q=this.length;m=~~m,E=E===void 0?Q:~~E,m<0?(m+=Q,m<0&&(m=0)):m>Q&&(m=Q),E<0?(E+=Q,E<0&&(E=0)):E>Q&&(E=Q),E<m&&(E=m);const N=this.subarray(m,E);return Object.setPrototypeOf(N,a.prototype),N};function K(T,m,E){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+m>E)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m],J=1,z=0;for(;++z<E&&(J*=256);)N+=this[m+z]*J;return N},a.prototype.readUintBE=a.prototype.readUIntBE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m+--E],J=1;for(;E>0&&(J*=256);)N+=this[m+--E]*J;return N},a.prototype.readUint8=a.prototype.readUInt8=function(m,E){return m=m>>>0,E||K(m,1,this.length),this[m]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(m,E){return m=m>>>0,E||K(m,2,this.length),this[m]|this[m+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(m,E){return m=m>>>0,E||K(m,2,this.length),this[m]<<8|this[m+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(m,E){return m=m>>>0,E||K(m,4,this.length),(this[m]|this[m+1]<<8|this[m+2]<<16)+this[m+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]*16777216+(this[m+1]<<16|this[m+2]<<8|this[m+3])},a.prototype.readBigUInt64LE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=E+this[++m]*2**8+this[++m]*2**16+this[++m]*2**24,J=this[++m]+this[++m]*2**8+this[++m]*2**16+Q*2**24;return BigInt(N)+(BigInt(J)<<BigInt(32))}),a.prototype.readBigUInt64BE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=E*2**24+this[++m]*2**16+this[++m]*2**8+this[++m],J=this[++m]*2**24+this[++m]*2**16+this[++m]*2**8+Q;return(BigInt(N)<<BigInt(32))+BigInt(J)}),a.prototype.readIntLE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m],J=1,z=0;for(;++z<E&&(J*=256);)N+=this[m+z]*J;return J*=128,N>=J&&(N-=Math.pow(2,8*E)),N},a.prototype.readIntBE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=E,J=1,z=this[m+--N];for(;N>0&&(J*=256);)z+=this[m+--N]*J;return J*=128,z>=J&&(z-=Math.pow(2,8*E)),z},a.prototype.readInt8=function(m,E){return m=m>>>0,E||K(m,1,this.length),this[m]&128?(255-this[m]+1)*-1:this[m]},a.prototype.readInt16LE=function(m,E){m=m>>>0,E||K(m,2,this.length);const Q=this[m]|this[m+1]<<8;return Q&32768?Q|4294901760:Q},a.prototype.readInt16BE=function(m,E){m=m>>>0,E||K(m,2,this.length);const Q=this[m+1]|this[m]<<8;return Q&32768?Q|4294901760:Q},a.prototype.readInt32LE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]|this[m+1]<<8|this[m+2]<<16|this[m+3]<<24},a.prototype.readInt32BE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]<<24|this[m+1]<<16|this[m+2]<<8|this[m+3]},a.prototype.readBigInt64LE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=this[m+4]+this[m+5]*2**8+this[m+6]*2**16+(Q<<24);return(BigInt(N)<<BigInt(32))+BigInt(E+this[++m]*256+this[++m]*65536+this[++m]*16777216)}),a.prototype.readBigInt64BE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=(E<<24)+this[++m]*2**16+this[++m]*2**8+this[++m];return(BigInt(N)<<BigInt(32))+BigInt(this[++m]*16777216+this[++m]*65536+this[++m]*256+Q)}),a.prototype.readFloatLE=function(m,E){return m=m>>>0,E||K(m,4,this.length),t.read(this,m,!0,23,4)},a.prototype.readFloatBE=function(m,E){return m=m>>>0,E||K(m,4,this.length),t.read(this,m,!1,23,4)},a.prototype.readDoubleLE=function(m,E){return m=m>>>0,E||K(m,8,this.length),t.read(this,m,!0,52,8)},a.prototype.readDoubleBE=function(m,E){return m=m>>>0,E||K(m,8,this.length),t.read(this,m,!1,52,8)};function Y(T,m,E,Q,N,J){if(!a.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(m>N||m<J)throw new RangeError('"value" argument is out of bounds');if(E+Q>T.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(m,E,Q,N){if(m=+m,E=E>>>0,Q=Q>>>0,!N){const $=Math.pow(2,8*Q)-1;Y(this,m,E,Q,$,0)}let J=1,z=0;for(this[E]=m&255;++z<Q&&(J*=256);)this[E+z]=m/J&255;return E+Q},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(m,E,Q,N){if(m=+m,E=E>>>0,Q=Q>>>0,!N){const $=Math.pow(2,8*Q)-1;Y(this,m,E,Q,$,0)}let J=Q-1,z=1;for(this[E+J]=m&255;--J>=0&&(z*=256);)this[E+J]=m/z&255;return E+Q},a.prototype.writeUint8=a.prototype.writeUInt8=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,1,255,0),this[E]=m&255,E+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,65535,0),this[E]=m&255,this[E+1]=m>>>8,E+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,65535,0),this[E]=m>>>8,this[E+1]=m&255,E+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,4294967295,0),this[E+3]=m>>>24,this[E+2]=m>>>16,this[E+1]=m>>>8,this[E]=m&255,E+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,4294967295,0),this[E]=m>>>24,this[E+1]=m>>>16,this[E+2]=m>>>8,this[E+3]=m&255,E+4};function te(T,m,E,Q,N){Ne(m,Q,N,T,E,7);let J=Number(m&BigInt(4294967295));T[E++]=J,J=J>>8,T[E++]=J,J=J>>8,T[E++]=J,J=J>>8,T[E++]=J;let z=Number(m>>BigInt(32)&BigInt(4294967295));return T[E++]=z,z=z>>8,T[E++]=z,z=z>>8,T[E++]=z,z=z>>8,T[E++]=z,E}function ie(T,m,E,Q,N){Ne(m,Q,N,T,E,7);let J=Number(m&BigInt(4294967295));T[E+7]=J,J=J>>8,T[E+6]=J,J=J>>8,T[E+5]=J,J=J>>8,T[E+4]=J;let z=Number(m>>BigInt(32)&BigInt(4294967295));return T[E+3]=z,z=z>>8,T[E+2]=z,z=z>>8,T[E+1]=z,z=z>>8,T[E]=z,E+8}a.prototype.writeBigUInt64LE=Ze(function(m,E=0){return te(this,m,E,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Ze(function(m,E=0){return ie(this,m,E,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(m,E,Q,N){if(m=+m,E=E>>>0,!N){const ae=Math.pow(2,8*Q-1);Y(this,m,E,Q,ae-1,-ae)}let J=0,z=1,$=0;for(this[E]=m&255;++J<Q&&(z*=256);)m<0&&$===0&&this[E+J-1]!==0&&($=1),this[E+J]=(m/z>>0)-$&255;return E+Q},a.prototype.writeIntBE=function(m,E,Q,N){if(m=+m,E=E>>>0,!N){const ae=Math.pow(2,8*Q-1);Y(this,m,E,Q,ae-1,-ae)}let J=Q-1,z=1,$=0;for(this[E+J]=m&255;--J>=0&&(z*=256);)m<0&&$===0&&this[E+J+1]!==0&&($=1),this[E+J]=(m/z>>0)-$&255;return E+Q},a.prototype.writeInt8=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,1,127,-128),m<0&&(m=255+m+1),this[E]=m&255,E+1},a.prototype.writeInt16LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,32767,-32768),this[E]=m&255,this[E+1]=m>>>8,E+2},a.prototype.writeInt16BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,32767,-32768),this[E]=m>>>8,this[E+1]=m&255,E+2},a.prototype.writeInt32LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,2147483647,-2147483648),this[E]=m&255,this[E+1]=m>>>8,this[E+2]=m>>>16,this[E+3]=m>>>24,E+4},a.prototype.writeInt32BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,2147483647,-2147483648),m<0&&(m=4294967295+m+1),this[E]=m>>>24,this[E+1]=m>>>16,this[E+2]=m>>>8,this[E+3]=m&255,E+4},a.prototype.writeBigInt64LE=Ze(function(m,E=0){return te(this,m,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Ze(function(m,E=0){return ie(this,m,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function he(T,m,E,Q,N,J){if(E+Q>T.length)throw new RangeError("Index out of range");if(E<0)throw new RangeError("Index out of range")}function fe(T,m,E,Q,N){return m=+m,E=E>>>0,N||he(T,m,E,4),t.write(T,m,E,Q,23,4),E+4}a.prototype.writeFloatLE=function(m,E,Q){return fe(this,m,E,!0,Q)},a.prototype.writeFloatBE=function(m,E,Q){return fe(this,m,E,!1,Q)};function _e(T,m,E,Q,N){return m=+m,E=E>>>0,N||he(T,m,E,8),t.write(T,m,E,Q,52,8),E+8}a.prototype.writeDoubleLE=function(m,E,Q){return _e(this,m,E,!0,Q)},a.prototype.writeDoubleBE=function(m,E,Q){return _e(this,m,E,!1,Q)},a.prototype.copy=function(m,E,Q,N){if(!a.isBuffer(m))throw new TypeError("argument should be a Buffer");if(Q||(Q=0),!N&&N!==0&&(N=this.length),E>=m.length&&(E=m.length),E||(E=0),N>0&&N<Q&&(N=Q),N===Q||m.length===0||this.length===0)return 0;if(E<0)throw new RangeError("targetStart out of bounds");if(Q<0||Q>=this.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("sourceEnd out of bounds");N>this.length&&(N=this.length),m.length-E<N-Q&&(N=m.length-E+Q);const J=N-Q;return this===m&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(E,Q,N):Uint8Array.prototype.set.call(m,this.subarray(Q,N),E),J},a.prototype.fill=function(m,E,Q,N){if(typeof m=="string"){if(typeof E=="string"?(N=E,E=0,Q=this.length):typeof Q=="string"&&(N=Q,Q=this.length),N!==void 0&&typeof N!="string")throw new TypeError("encoding must be a string");if(typeof N=="string"&&!a.isEncoding(N))throw new TypeError("Unknown encoding: "+N);if(m.length===1){const z=m.charCodeAt(0);(N==="utf8"&&z<128||N==="latin1")&&(m=z)}}else typeof m=="number"?m=m&255:typeof m=="boolean"&&(m=Number(m));if(E<0||this.length<E||this.length<Q)throw new RangeError("Out of range index");if(Q<=E)return this;E=E>>>0,Q=Q===void 0?this.length:Q>>>0,m||(m=0);let J;if(typeof m=="number")for(J=E;J<Q;++J)this[J]=m;else{const z=a.isBuffer(m)?m:a.from(m,N),$=z.length;if($===0)throw new TypeError('The value "'+m+'" is invalid for argument "value"');for(J=0;J<Q-E;++J)this[J+E]=z[J%$]}return this};const Te={};function Fe(T,m,E){Te[T]=class extends E{constructor(){super(),Object.defineProperty(this,"message",{value:m.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(N){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:N,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}Fe("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Fe("ERR_INVALID_ARG_TYPE",function(T,m){return`The "${T}" argument must be of type number. Received type ${typeof m}`},TypeError),Fe("ERR_OUT_OF_RANGE",function(T,m,E){let Q=`The value of "${T}" is out of range.`,N=E;return Number.isInteger(E)&&Math.abs(E)>4294967296?N=pe(String(E)):typeof E=="bigint"&&(N=String(E),(E>BigInt(2)**BigInt(32)||E<-(BigInt(2)**BigInt(32)))&&(N=pe(N)),N+="n"),Q+=` It must be ${m}. Received ${N}`,Q},RangeError);function pe(T){let m="",E=T.length;const Q=T[0]==="-"?1:0;for(;E>=Q+4;E-=3)m=`_${T.slice(E-3,E)}${m}`;return`${T.slice(0,E)}${m}`}function Qe(T,m,E){Re(m,"offset"),(T[m]===void 0||T[m+E]===void 0)&&Ke(m,T.length-(E+1))}function Ne(T,m,E,Q,N,J){if(T>E||T<m){const z=typeof m=="bigint"?"n":"";let $;throw m===0||m===BigInt(0)?$=`>= 0${z} and < 2${z} ** ${(J+1)*8}${z}`:$=`>= -(2${z} ** ${(J+1)*8-1}${z}) and < 2 ** ${(J+1)*8-1}${z}`,new Te.ERR_OUT_OF_RANGE("value",$,T)}Qe(Q,N,J)}function Re(T,m){if(typeof T!="number")throw new Te.ERR_INVALID_ARG_TYPE(m,"number",T)}function Ke(T,m,E){throw Math.floor(T)!==T?(Re(T,E),new Te.ERR_OUT_OF_RANGE("offset","an integer",T)):m<0?new Te.ERR_BUFFER_OUT_OF_BOUNDS:new Te.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${m}`,T)}const Se=/[^+/0-9A-Za-z-_]/g;function ye(T){if(T=T.split("=")[0],T=T.trim().replace(Se,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ke(T,m){m=m||1/0;let E;const Q=T.length;let N=null;const J=[];for(let z=0;z<Q;++z){if(E=T.charCodeAt(z),E>55295&&E<57344){if(!N){if(E>56319){(m-=3)>-1&&J.push(239,191,189);continue}else if(z+1===Q){(m-=3)>-1&&J.push(239,191,189);continue}N=E;continue}if(E<56320){(m-=3)>-1&&J.push(239,191,189),N=E;continue}E=(N-55296<<10|E-56320)+65536}else N&&(m-=3)>-1&&J.push(239,191,189);if(N=null,E<128){if((m-=1)<0)break;J.push(E)}else if(E<2048){if((m-=2)<0)break;J.push(E>>6|192,E&63|128)}else if(E<65536){if((m-=3)<0)break;J.push(E>>12|224,E>>6&63|128,E&63|128)}else if(E<1114112){if((m-=4)<0)break;J.push(E>>18|240,E>>12&63|128,E>>6&63|128,E&63|128)}else throw new Error("Invalid code point")}return J}function Ue(T){const m=[];for(let E=0;E<T.length;++E)m.push(T.charCodeAt(E)&255);return m}function Xe(T,m){let E,Q,N;const J=[];for(let z=0;z<T.length&&!((m-=2)<0);++z)E=T.charCodeAt(z),Q=E>>8,N=E%256,J.push(N),J.push(Q);return J}function Ge(T){return e.toByteArray(ye(T))}function $e(T,m,E,Q){let N;for(N=0;N<Q&&!(N+E>=m.length||N>=T.length);++N)m[N+E]=T[N];return N}function Ce(T,m){return T instanceof m||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===m.name}function et(T){return T!==T}const ot=function(){const T="0123456789abcdef",m=new Array(256);for(let E=0;E<16;++E){const Q=E*16;for(let N=0;N<16;++N)m[Q+N]=T[E]+T[N]}return m}();function Ze(T){return typeof BigInt>"u"?ze:T}function ze(){throw new Error("BigInt not supported")}})(mu);var Vi=at,St=CE,Iu=mu.Buffer;$i.__TYPEDARRAY_POOL||($i.__TYPEDARRAY_POOL={UINT8:St([32,0]),UINT16:St([32,0]),UINT32:St([32,0]),BIGUINT64:St([32,0]),INT8:St([32,0]),INT16:St([32,0]),INT32:St([32,0]),BIGINT64:St([32,0]),FLOAT:St([32,0]),DOUBLE:St([32,0]),DATA:St([32,0]),UINT8C:St([32,0]),BUFFER:St([32,0])});var RE=typeof Uint8ClampedArray<"u",DE=typeof BigUint64Array<"u",LE=typeof BigInt64Array<"u",ht=$i.__TYPEDARRAY_POOL;ht.UINT8C||(ht.UINT8C=St([32,0])),ht.BIGUINT64||(ht.BIGUINT64=St([32,0])),ht.BIGINT64||(ht.BIGINT64=St([32,0])),ht.BUFFER||(ht.BUFFER=St([32,0]));var Us=ht.DATA,Gs=ht.BUFFER;Pe.free=function(e){if(Iu.isBuffer(e))Gs[Vi.log2(e.length)].push(e);else{if(Object.prototype.toString.call(e)!=="[object ArrayBuffer]"&&(e=e.buffer),!e)return;var t=e.length||e.byteLength,i=Vi.log2(t)|0;Us[i].push(e)}};function vu(r){if(r){var e=r.length||r.byteLength,t=Vi.log2(e);Us[t].push(r)}}function kE(r){vu(r.buffer)}Pe.freeUint8=Pe.freeUint16=Pe.freeUint32=Pe.freeBigUint64=Pe.freeInt8=Pe.freeInt16=Pe.freeInt32=Pe.freeBigInt64=Pe.freeFloat32=Pe.freeFloat=Pe.freeFloat64=Pe.freeDouble=Pe.freeUint8Clamped=Pe.freeDataView=kE,Pe.freeArrayBuffer=vu,Pe.freeBuffer=function(e){Gs[Vi.log2(e.length)].push(e)},Pe.malloc=function(e,t){if(t===void 0||t==="arraybuffer")return Mt(e);switch(t){case"uint8":return Oa(e);case"uint16":return yu(e);case"uint32":return Cu(e);case"int8":return Bu(e);case"int16":return Tu(e);case"int32":return Su(e);case"float":case"float32":return bu(e);case"double":case"float64":return xu(e);case"uint8_clamped":return Qu(e);case"bigint64":return wu(e);case"biguint64":return _u(e);case"buffer":return Du(e);case"data":case"dataview":return Ru(e);default:return null}return null};function Mt(e){var e=Vi.nextPow2(e),t=Vi.log2(e),i=Us[t];return i.length>0?i.pop():new ArrayBuffer(e)}Pe.mallocArrayBuffer=Mt;function Oa(r){return new Uint8Array(Mt(r),0,r)}Pe.mallocUint8=Oa;function yu(r){return new Uint16Array(Mt(2*r),0,r)}Pe.mallocUint16=yu;function Cu(r){return new Uint32Array(Mt(4*r),0,r)}Pe.mallocUint32=Cu;function Bu(r){return new Int8Array(Mt(r),0,r)}Pe.mallocInt8=Bu;function Tu(r){return new Int16Array(Mt(2*r),0,r)}Pe.mallocInt16=Tu;function Su(r){return new Int32Array(Mt(4*r),0,r)}Pe.mallocInt32=Su;function bu(r){return new Float32Array(Mt(4*r),0,r)}Pe.mallocFloat32=Pe.mallocFloat=bu;function xu(r){return new Float64Array(Mt(8*r),0,r)}Pe.mallocFloat64=Pe.mallocDouble=xu;function Qu(r){return RE?new Uint8ClampedArray(Mt(r),0,r):Oa(r)}Pe.mallocUint8Clamped=Qu;function _u(r){return DE?new BigUint64Array(Mt(8*r),0,r):null}Pe.mallocBigUint64=_u;function wu(r){return LE?new BigInt64Array(Mt(8*r),0,r):null}Pe.mallocBigInt64=wu;function Ru(r){return new DataView(Mt(r),0,r)}Pe.mallocDataView=Ru;function Du(r){r=Vi.nextPow2(r);var e=Vi.log2(r),t=Gs[e];return t.length>0?t.pop():new Iu(r)}Pe.mallocBuffer=Du,Pe.clearCache=function(){for(var e=0;e<32;++e)ht.UINT8[e].length=0,ht.UINT16[e].length=0,ht.UINT32[e].length=0,ht.INT8[e].length=0,ht.INT16[e].length=0,ht.INT32[e].length=0,ht.FLOAT[e].length=0,ht.DOUBLE[e].length=0,ht.BIGUINT64[e].length=0,ht.BIGINT64[e].length=0,ht.UINT8C[e].length=0,Us[e].length=0,Gs[e].length=0};var $s=iE,Ua=du,Fr=Pe,ME=UE,Hs=null,Ga=null,Ys=null;function FE(r){Hs=[r.LINEAR,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_NEAREST],Ga=[r.NEAREST,r.LINEAR,r.NEAREST_MIPMAP_NEAREST,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_LINEAR],Ys=[r.REPEAT,r.CLAMP_TO_EDGE,r.MIRRORED_REPEAT]}function Lu(r){return typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof ImageData<"u"&&r instanceof ImageData}var ku=function(r,e){Ua.muls(r,e,255)};function $a(r,e,t){var i=r.gl,n=i.getParameter(i.MAX_TEXTURE_SIZE);if(e<0||e>n||t<0||t>n)throw new Error("gl-texture2d: Invalid texture size");return r._shape=[e,t],r.bind(),i.texImage2D(i.TEXTURE_2D,0,r.format,e,t,0,r.format,r.type,null),r._mipLevels=[0],r}function Vs(r,e,t,i,n,s){this.gl=r,this.handle=e,this.format=n,this.type=s,this._shape=[t,i],this._mipLevels=[0],this._magFilter=r.NEAREST,this._minFilter=r.NEAREST,this._wrapS=r.CLAMP_TO_EDGE,this._wrapT=r.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,a=[this._wrapS,this._wrapT];Object.defineProperties(a,[{get:function(){return o._wrapS},set:function(A){return o.wrapS=A}},{get:function(){return o._wrapT},set:function(A){return o.wrapT=A}}]),this._wrapVector=a;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(A){return o.width=A}},{get:function(){return o._shape[1]},set:function(A){return o.height=A}}]),this._shapeVector=l}var Dn=Vs.prototype;Object.defineProperties(Dn,{minFilter:{get:function(){return this._minFilter},set:function(r){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Hs.indexOf(r)>=0&&(e.getExtension("OES_texture_float_linear")||(r=e.NEAREST)),Ga.indexOf(r)<0)throw new Error("gl-texture2d: Unknown filter mode "+r);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,r),this._minFilter=r}},magFilter:{get:function(){return this._magFilter},set:function(r){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Hs.indexOf(r)>=0&&(e.getExtension("OES_texture_float_linear")||(r=e.NEAREST)),Ga.indexOf(r)<0)throw new Error("gl-texture2d: Unknown filter mode "+r);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,r),this._magFilter=r}},mipSamples:{get:function(){return this._anisoSamples},set:function(r){var e=this._anisoSamples;if(this._anisoSamples=Math.max(r,1)|0,e!==this._anisoSamples){var t=this.gl.getExtension("EXT_texture_filter_anisotropic");t&&this.gl.texParameterf(this.gl.TEXTURE_2D,t.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(r){if(this.bind(),Ys.indexOf(r)<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,r),this._wrapS=r}},wrapT:{get:function(){return this._wrapT},set:function(r){if(this.bind(),Ys.indexOf(r)<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,r),this._wrapT=r}},wrap:{get:function(){return this._wrapVector},set:function(r){if(Array.isArray(r)||(r=[r,r]),r.length!==2)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(Ys.indexOf(r[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);this._wrapS=r[0],this._wrapT=r[1];var t=this.gl;return this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,this._wrapS),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,this._wrapT),r}},shape:{get:function(){return this._shapeVector},set:function(r){if(!Array.isArray(r))r=[r|0,r|0];else if(r.length!==2)throw new Error("gl-texture2d: Invalid texture shape");return $a(this,r[0]|0,r[1]|0),[r[0]|0,r[1]|0]}},width:{get:function(){return this._shape[0]},set:function(r){return r=r|0,$a(this,r,this._shape[1]),r}},height:{get:function(){return this._shape[1]},set:function(r){return r=r|0,$a(this,this._shape[0],r),r}}}),Dn.bind=function(r){var e=this.gl;return r!==void 0&&e.activeTexture(e.TEXTURE0+(r|0)),e.bindTexture(e.TEXTURE_2D,this.handle),r!==void 0?r|0:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},Dn.dispose=function(){this.gl.deleteTexture(this.handle)},Dn.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var r=Math.min(this._shape[0],this._shape[1]),e=0;r>0;++e,r>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},Dn.setPixels=function(r,e,t,i){var n=this.gl;this.bind(),Array.isArray(e)?(i=t,t=e[1]|0,e=e[0]|0):(e=e||0,t=t||0),i=i||0;var s=Lu(r)?r:r.raw;if(s){var o=this._mipLevels.indexOf(i)<0;o?(n.texImage2D(n.TEXTURE_2D,0,this.format,this.format,this.type,s),this._mipLevels.push(i)):n.texSubImage2D(n.TEXTURE_2D,i,e,t,this.format,this.type,s)}else if(r.shape&&r.stride&&r.data){if(r.shape.length<2||e+r.shape[1]>this._shape[1]>>>i||t+r.shape[0]>this._shape[0]>>>i||e<0||t<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");PE(n,e,t,i,this.format,this.type,this._mipLevels,r)}else throw new Error("gl-texture2d: Unsupported data type")};function Mu(r,e){return r.length===3?e[2]===1&&e[1]===r[0]*r[2]&&e[0]===r[2]:e[0]===1&&e[1]===r[0]}function PE(r,e,t,i,n,s,o,a){var l=a.dtype,A=a.shape.slice();if(A.length<2||A.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var u=0,c=0,h=Mu(A,a.stride.slice());if(l==="float32"?u=r.FLOAT:l==="float64"?(u=r.FLOAT,h=!1,l="float32"):l==="uint8"?u=r.UNSIGNED_BYTE:(u=r.UNSIGNED_BYTE,h=!1,l="uint8"),A.length===2)c=r.LUMINANCE,A=[A[0],A[1],1],a=$s(a.data,A,[a.stride[0],a.stride[1],1],a.offset);else if(A.length===3){if(A[2]===1)c=r.ALPHA;else if(A[2]===2)c=r.LUMINANCE_ALPHA;else if(A[2]===3)c=r.RGB;else if(A[2]===4)c=r.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");A[2]}else throw new Error("gl-texture2d: Invalid shape for texture");if((c===r.LUMINANCE||c===r.ALPHA)&&(n===r.LUMINANCE||n===r.ALPHA)&&(c=n),c!==n)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=a.size,f=o.indexOf(i)<0;if(f&&o.push(i),u===s&&h)a.offset===0&&a.data.length===d?f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,a.data):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,a.data):f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,a.data.subarray(a.offset,a.offset+d)):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,a.data.subarray(a.offset,a.offset+d));else{var g;s===r.FLOAT?g=Fr.mallocFloat32(d):g=Fr.mallocUint8(d);var p=$s(g,A,[A[2],A[2]*A[0],1]);u===r.FLOAT&&s===r.UNSIGNED_BYTE?ku(p,a):Ua.assign(p,a),f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,g.subarray(0,d)):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,g.subarray(0,d)),s===r.FLOAT?Fr.freeFloat32(g):Fr.freeUint8(g)}}function Ha(r){var e=r.createTexture();return r.bindTexture(r.TEXTURE_2D,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e}function Fu(r,e,t,i,n){var s=r.getParameter(r.MAX_TEXTURE_SIZE);if(e<0||e>s||t<0||t>s)throw new Error("gl-texture2d: Invalid texture shape");if(n===r.FLOAT&&!r.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,i,e,t,0,i,n,null),new Vs(r,o,e,t,i,n)}function NE(r,e,t,i,n,s){var o=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,n,n,s,e),new Vs(r,o,t,i,n,s)}function OE(r,e){var t=e.dtype,i=e.shape.slice(),n=r.getParameter(r.MAX_TEXTURE_SIZE);if(i[0]<0||i[0]>n||i[1]<0||i[1]>n)throw new Error("gl-texture2d: Invalid texture size");var s=Mu(i,e.stride.slice()),o=0;t==="float32"?o=r.FLOAT:t==="float64"?(o=r.FLOAT,s=!1,t="float32"):t==="uint8"?o=r.UNSIGNED_BYTE:(o=r.UNSIGNED_BYTE,s=!1,t="uint8");var a=0;if(i.length===2)a=r.LUMINANCE,i=[i[0],i[1],1],e=$s(e.data,i,[e.stride[0],e.stride[1],1],e.offset);else if(i.length===3)if(i[2]===1)a=r.ALPHA;else if(i[2]===2)a=r.LUMINANCE_ALPHA;else if(i[2]===3)a=r.RGB;else if(i[2]===4)a=r.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");else throw new Error("gl-texture2d: Invalid shape for texture");o===r.FLOAT&&!r.getExtension("OES_texture_float")&&(o=r.UNSIGNED_BYTE,s=!1);var l,A,u=e.size;if(s)e.offset===0&&e.data.length===u?l=e.data:l=e.data.subarray(e.offset,e.offset+u);else{var c=[i[2],i[2]*i[0],1];A=Fr.malloc(u,t);var h=$s(A,i,c,0);(t==="float32"||t==="float64")&&o===r.UNSIGNED_BYTE?ku(h,e):Ua.assign(h,e),l=A.subarray(0,u)}var d=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,a,i[0],i[1],0,a,o,l),s||Fr.free(A),new Vs(r,d,i[0],i[1],a,o)}function UE(r){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(Hs||FE(r),typeof arguments[1]=="number")return Fu(r,arguments[1],arguments[2],arguments[3]||r.RGBA,arguments[4]||r.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return Fu(r,arguments[1][0]|0,arguments[1][1]|0,arguments[2]||r.RGBA,arguments[3]||r.UNSIGNED_BYTE);if(typeof arguments[1]=="object"){var e=arguments[1],t=Lu(e)?e:e.raw;if(t)return NE(r,t,e.width|0,e.height|0,arguments[2]||r.RGBA,arguments[3]||r.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return OE(r,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}const Ks=_a(ME);var Pu={},Nu=GE;function GE(r,e){for(var t={},i=0;i<r.length;++i)for(var n=r[i].name,s=n.split("."),o=t,a=0;a<s.length;++a){var l=s[a].split("[");if(l.length>1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var A=1;A<l.length;++A){var u=parseInt(l[A]);A<l.length-1||a<s.length-1?(u in o||(A<l.length-1?o[u]=[]:o[u]={}),o=o[u]):e?o[u]=i:o[u]=r[i].type}}else a<s.length-1?(l[0]in o||(o[l[0]]={}),o=o[l[0]]):e?o[l[0]]=i:o[l[0]]=r[i].type}return t}function Ln(r,e,t){this.shortMessage=e||"",this.longMessage=t||"",this.rawError=r||"",this.message="gl-shader: "+(e||r||"")+(t?`
113
+ */(function(r){const e=Os,t=Na,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=a,r.SlowBuffer=B,r.INSPECT_MAX_BYTES=50;const n=2147483647;r.kMaxLength=n,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const T=new Uint8Array(1),m={foo:function(){return 42}};return Object.setPrototypeOf(m,Uint8Array.prototype),Object.setPrototypeOf(T,m),T.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(T){if(T>n)throw new RangeError('The value "'+T+'" is invalid for option "size"');const m=new Uint8Array(T);return Object.setPrototypeOf(m,a.prototype),m}function a(T,m,E){if(typeof T=="number"){if(typeof m=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return c(T)}return l(T,m,E)}a.poolSize=8192;function l(T,m,E){if(typeof T=="string")return h(T,m);if(ArrayBuffer.isView(T))return f(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Ce(T,ArrayBuffer)||T&&Ce(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ce(T,SharedArrayBuffer)||T&&Ce(T.buffer,SharedArrayBuffer)))return g(T,m,E);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const Q=T.valueOf&&T.valueOf();if(Q!=null&&Q!==T)return a.from(Q,m,E);const N=p(T);if(N)return N;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return a.from(T[Symbol.toPrimitive]("string"),m,E);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}a.from=function(T,m,E){return l(T,m,E)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function A(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function u(T,m,E){return A(T),T<=0?o(T):m!==void 0?typeof E=="string"?o(T).fill(m,E):o(T).fill(m):o(T)}a.alloc=function(T,m,E){return u(T,m,E)};function c(T){return A(T),o(T<0?0:v(T)|0)}a.allocUnsafe=function(T){return c(T)},a.allocUnsafeSlow=function(T){return c(T)};function h(T,m){if((typeof m!="string"||m==="")&&(m="utf8"),!a.isEncoding(m))throw new TypeError("Unknown encoding: "+m);const E=C(T,m)|0;let Q=o(E);const N=Q.write(T,m);return N!==E&&(Q=Q.slice(0,N)),Q}function d(T){const m=T.length<0?0:v(T.length)|0,E=o(m);for(let Q=0;Q<m;Q+=1)E[Q]=T[Q]&255;return E}function f(T){if(Ce(T,Uint8Array)){const m=new Uint8Array(T);return g(m.buffer,m.byteOffset,m.byteLength)}return d(T)}function g(T,m,E){if(m<0||T.byteLength<m)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<m+(E||0))throw new RangeError('"length" is outside of buffer bounds');let Q;return m===void 0&&E===void 0?Q=new Uint8Array(T):E===void 0?Q=new Uint8Array(T,m):Q=new Uint8Array(T,m,E),Object.setPrototypeOf(Q,a.prototype),Q}function p(T){if(a.isBuffer(T)){const m=v(T.length)|0,E=o(m);return E.length===0||T.copy(E,0,0,m),E}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):d(T);if(T.type==="Buffer"&&Array.isArray(T.data))return d(T.data)}function v(T){if(T>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return T|0}function B(T){return+T!=T&&(T=0),a.alloc(+T)}a.isBuffer=function(m){return m!=null&&m._isBuffer===!0&&m!==a.prototype},a.compare=function(m,E){if(Ce(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),Ce(E,Uint8Array)&&(E=a.from(E,E.offset,E.byteLength)),!a.isBuffer(m)||!a.isBuffer(E))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(m===E)return 0;let Q=m.length,N=E.length;for(let J=0,z=Math.min(Q,N);J<z;++J)if(m[J]!==E[J]){Q=m[J],N=E[J];break}return Q<N?-1:N<Q?1:0},a.isEncoding=function(m){switch(String(m).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(m,E){if(!Array.isArray(m))throw new TypeError('"list" argument must be an Array of Buffers');if(m.length===0)return a.alloc(0);let Q;if(E===void 0)for(E=0,Q=0;Q<m.length;++Q)E+=m[Q].length;const N=a.allocUnsafe(E);let J=0;for(Q=0;Q<m.length;++Q){let z=m[Q];if(Ce(z,Uint8Array))J+z.length>N.length?(a.isBuffer(z)||(z=a.from(z)),z.copy(N,J)):Uint8Array.prototype.set.call(N,z,J);else if(a.isBuffer(z))z.copy(N,J);else throw new TypeError('"list" argument must be an Array of Buffers');J+=z.length}return N};function C(T,m){if(a.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Ce(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);const E=T.length,Q=arguments.length>2&&arguments[2]===!0;if(!Q&&E===0)return 0;let N=!1;for(;;)switch(m){case"ascii":case"latin1":case"binary":return E;case"utf8":case"utf-8":return ke(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E*2;case"hex":return E>>>1;case"base64":return Ge(T).length;default:if(N)return Q?-1:ke(T).length;m=(""+m).toLowerCase(),N=!0}}a.byteLength=C;function y(T,m,E){let Q=!1;if((m===void 0||m<0)&&(m=0),m>this.length||((E===void 0||E>this.length)&&(E=this.length),E<=0)||(E>>>=0,m>>>=0,E<=m))return"";for(T||(T="utf8");;)switch(T){case"hex":return _(this,m,E);case"utf8":case"utf-8":return oe(this,m,E);case"ascii":return q(this,m,E);case"latin1":case"binary":return R(this,m,E);case"base64":return le(this,m,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,m,E);default:if(Q)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),Q=!0}}a.prototype._isBuffer=!0;function x(T,m,E){const Q=T[m];T[m]=T[E],T[E]=Q}a.prototype.swap16=function(){const m=this.length;if(m%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let E=0;E<m;E+=2)x(this,E,E+1);return this},a.prototype.swap32=function(){const m=this.length;if(m%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let E=0;E<m;E+=4)x(this,E,E+3),x(this,E+1,E+2);return this},a.prototype.swap64=function(){const m=this.length;if(m%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let E=0;E<m;E+=8)x(this,E,E+7),x(this,E+1,E+6),x(this,E+2,E+5),x(this,E+3,E+4);return this},a.prototype.toString=function(){const m=this.length;return m===0?"":arguments.length===0?oe(this,0,m):y.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(m){if(!a.isBuffer(m))throw new TypeError("Argument must be a Buffer");return this===m?!0:a.compare(this,m)===0},a.prototype.inspect=function(){let m="";const E=r.INSPECT_MAX_BYTES;return m=this.toString("hex",0,E).replace(/(.{2})/g,"$1 ").trim(),this.length>E&&(m+=" ... "),"<Buffer "+m+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(m,E,Q,N,J){if(Ce(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(m))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof m);if(E===void 0&&(E=0),Q===void 0&&(Q=m?m.length:0),N===void 0&&(N=0),J===void 0&&(J=this.length),E<0||Q>m.length||N<0||J>this.length)throw new RangeError("out of range index");if(N>=J&&E>=Q)return 0;if(N>=J)return-1;if(E>=Q)return 1;if(E>>>=0,Q>>>=0,N>>>=0,J>>>=0,this===m)return 0;let z=J-N,$=Q-E;const ae=Math.min(z,$),ue=this.slice(N,J),ve=m.slice(E,Q);for(let me=0;me<ae;++me)if(ue[me]!==ve[me]){z=ue[me],$=ve[me];break}return z<$?-1:$<z?1:0};function w(T,m,E,Q,N){if(T.length===0)return-1;if(typeof E=="string"?(Q=E,E=0):E>2147483647?E=2147483647:E<-2147483648&&(E=-2147483648),E=+E,et(E)&&(E=N?0:T.length-1),E<0&&(E=T.length+E),E>=T.length){if(N)return-1;E=T.length-1}else if(E<0)if(N)E=0;else return-1;if(typeof m=="string"&&(m=a.from(m,Q)),a.isBuffer(m))return m.length===0?-1:D(T,m,E,Q,N);if(typeof m=="number")return m=m&255,typeof Uint8Array.prototype.indexOf=="function"?N?Uint8Array.prototype.indexOf.call(T,m,E):Uint8Array.prototype.lastIndexOf.call(T,m,E):D(T,[m],E,Q,N);throw new TypeError("val must be string, number or Buffer")}function D(T,m,E,Q,N){let J=1,z=T.length,$=m.length;if(Q!==void 0&&(Q=String(Q).toLowerCase(),Q==="ucs2"||Q==="ucs-2"||Q==="utf16le"||Q==="utf-16le")){if(T.length<2||m.length<2)return-1;J=2,z/=2,$/=2,E/=2}function ae(ve,me){return J===1?ve[me]:ve.readUInt16BE(me*J)}let ue;if(N){let ve=-1;for(ue=E;ue<z;ue++)if(ae(T,ue)===ae(m,ve===-1?0:ue-ve)){if(ve===-1&&(ve=ue),ue-ve+1===$)return ve*J}else ve!==-1&&(ue-=ue-ve),ve=-1}else for(E+$>z&&(E=z-$),ue=E;ue>=0;ue--){let ve=!0;for(let me=0;me<$;me++)if(ae(T,ue+me)!==ae(m,me)){ve=!1;break}if(ve)return ue}return-1}a.prototype.includes=function(m,E,Q){return this.indexOf(m,E,Q)!==-1},a.prototype.indexOf=function(m,E,Q){return w(this,m,E,Q,!0)},a.prototype.lastIndexOf=function(m,E,Q){return w(this,m,E,Q,!1)};function F(T,m,E,Q){E=Number(E)||0;const N=T.length-E;Q?(Q=Number(Q),Q>N&&(Q=N)):Q=N;const J=m.length;Q>J/2&&(Q=J/2);let z;for(z=0;z<Q;++z){const $=parseInt(m.substr(z*2,2),16);if(et($))return z;T[E+z]=$}return z}function O(T,m,E,Q){return $e(ke(m,T.length-E),T,E,Q)}function M(T,m,E,Q){return $e(Ue(m),T,E,Q)}function j(T,m,E,Q){return $e(Ge(m),T,E,Q)}function X(T,m,E,Q){return $e(Xe(m,T.length-E),T,E,Q)}a.prototype.write=function(m,E,Q,N){if(E===void 0)N="utf8",Q=this.length,E=0;else if(Q===void 0&&typeof E=="string")N=E,Q=this.length,E=0;else if(isFinite(E))E=E>>>0,isFinite(Q)?(Q=Q>>>0,N===void 0&&(N="utf8")):(N=Q,Q=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const J=this.length-E;if((Q===void 0||Q>J)&&(Q=J),m.length>0&&(Q<0||E<0)||E>this.length)throw new RangeError("Attempt to write outside buffer bounds");N||(N="utf8");let z=!1;for(;;)switch(N){case"hex":return F(this,m,E,Q);case"utf8":case"utf-8":return O(this,m,E,Q);case"ascii":case"latin1":case"binary":return M(this,m,E,Q);case"base64":return j(this,m,E,Q);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X(this,m,E,Q);default:if(z)throw new TypeError("Unknown encoding: "+N);N=(""+N).toLowerCase(),z=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function le(T,m,E){return m===0&&E===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(m,E))}function oe(T,m,E){E=Math.min(T.length,E);const Q=[];let N=m;for(;N<E;){const J=T[N];let z=null,$=J>239?4:J>223?3:J>191?2:1;if(N+$<=E){let ae,ue,ve,me;switch($){case 1:J<128&&(z=J);break;case 2:ae=T[N+1],(ae&192)===128&&(me=(J&31)<<6|ae&63,me>127&&(z=me));break;case 3:ae=T[N+1],ue=T[N+2],(ae&192)===128&&(ue&192)===128&&(me=(J&15)<<12|(ae&63)<<6|ue&63,me>2047&&(me<55296||me>57343)&&(z=me));break;case 4:ae=T[N+1],ue=T[N+2],ve=T[N+3],(ae&192)===128&&(ue&192)===128&&(ve&192)===128&&(me=(J&15)<<18|(ae&63)<<12|(ue&63)<<6|ve&63,me>65535&&me<1114112&&(z=me))}}z===null?(z=65533,$=1):z>65535&&(z-=65536,Q.push(z>>>10&1023|55296),z=56320|z&1023),Q.push(z),N+=$}return U(Q)}const L=4096;function U(T){const m=T.length;if(m<=L)return String.fromCharCode.apply(String,T);let E="",Q=0;for(;Q<m;)E+=String.fromCharCode.apply(String,T.slice(Q,Q+=L));return E}function q(T,m,E){let Q="";E=Math.min(T.length,E);for(let N=m;N<E;++N)Q+=String.fromCharCode(T[N]&127);return Q}function R(T,m,E){let Q="";E=Math.min(T.length,E);for(let N=m;N<E;++N)Q+=String.fromCharCode(T[N]);return Q}function _(T,m,E){const Q=T.length;(!m||m<0)&&(m=0),(!E||E<0||E>Q)&&(E=Q);let N="";for(let J=m;J<E;++J)N+=ot[T[J]];return N}function k(T,m,E){const Q=T.slice(m,E);let N="";for(let J=0;J<Q.length-1;J+=2)N+=String.fromCharCode(Q[J]+Q[J+1]*256);return N}a.prototype.slice=function(m,E){const Q=this.length;m=~~m,E=E===void 0?Q:~~E,m<0?(m+=Q,m<0&&(m=0)):m>Q&&(m=Q),E<0?(E+=Q,E<0&&(E=0)):E>Q&&(E=Q),E<m&&(E=m);const N=this.subarray(m,E);return Object.setPrototypeOf(N,a.prototype),N};function K(T,m,E){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+m>E)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m],J=1,z=0;for(;++z<E&&(J*=256);)N+=this[m+z]*J;return N},a.prototype.readUintBE=a.prototype.readUIntBE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m+--E],J=1;for(;E>0&&(J*=256);)N+=this[m+--E]*J;return N},a.prototype.readUint8=a.prototype.readUInt8=function(m,E){return m=m>>>0,E||K(m,1,this.length),this[m]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(m,E){return m=m>>>0,E||K(m,2,this.length),this[m]|this[m+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(m,E){return m=m>>>0,E||K(m,2,this.length),this[m]<<8|this[m+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(m,E){return m=m>>>0,E||K(m,4,this.length),(this[m]|this[m+1]<<8|this[m+2]<<16)+this[m+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]*16777216+(this[m+1]<<16|this[m+2]<<8|this[m+3])},a.prototype.readBigUInt64LE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=E+this[++m]*2**8+this[++m]*2**16+this[++m]*2**24,J=this[++m]+this[++m]*2**8+this[++m]*2**16+Q*2**24;return BigInt(N)+(BigInt(J)<<BigInt(32))}),a.prototype.readBigUInt64BE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=E*2**24+this[++m]*2**16+this[++m]*2**8+this[++m],J=this[++m]*2**24+this[++m]*2**16+this[++m]*2**8+Q;return(BigInt(N)<<BigInt(32))+BigInt(J)}),a.prototype.readIntLE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=this[m],J=1,z=0;for(;++z<E&&(J*=256);)N+=this[m+z]*J;return J*=128,N>=J&&(N-=Math.pow(2,8*E)),N},a.prototype.readIntBE=function(m,E,Q){m=m>>>0,E=E>>>0,Q||K(m,E,this.length);let N=E,J=1,z=this[m+--N];for(;N>0&&(J*=256);)z+=this[m+--N]*J;return J*=128,z>=J&&(z-=Math.pow(2,8*E)),z},a.prototype.readInt8=function(m,E){return m=m>>>0,E||K(m,1,this.length),this[m]&128?(255-this[m]+1)*-1:this[m]},a.prototype.readInt16LE=function(m,E){m=m>>>0,E||K(m,2,this.length);const Q=this[m]|this[m+1]<<8;return Q&32768?Q|4294901760:Q},a.prototype.readInt16BE=function(m,E){m=m>>>0,E||K(m,2,this.length);const Q=this[m+1]|this[m]<<8;return Q&32768?Q|4294901760:Q},a.prototype.readInt32LE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]|this[m+1]<<8|this[m+2]<<16|this[m+3]<<24},a.prototype.readInt32BE=function(m,E){return m=m>>>0,E||K(m,4,this.length),this[m]<<24|this[m+1]<<16|this[m+2]<<8|this[m+3]},a.prototype.readBigInt64LE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=this[m+4]+this[m+5]*2**8+this[m+6]*2**16+(Q<<24);return(BigInt(N)<<BigInt(32))+BigInt(E+this[++m]*256+this[++m]*65536+this[++m]*16777216)}),a.prototype.readBigInt64BE=Ze(function(m){m=m>>>0,Re(m,"offset");const E=this[m],Q=this[m+7];(E===void 0||Q===void 0)&&Ke(m,this.length-8);const N=(E<<24)+this[++m]*2**16+this[++m]*2**8+this[++m];return(BigInt(N)<<BigInt(32))+BigInt(this[++m]*16777216+this[++m]*65536+this[++m]*256+Q)}),a.prototype.readFloatLE=function(m,E){return m=m>>>0,E||K(m,4,this.length),t.read(this,m,!0,23,4)},a.prototype.readFloatBE=function(m,E){return m=m>>>0,E||K(m,4,this.length),t.read(this,m,!1,23,4)},a.prototype.readDoubleLE=function(m,E){return m=m>>>0,E||K(m,8,this.length),t.read(this,m,!0,52,8)},a.prototype.readDoubleBE=function(m,E){return m=m>>>0,E||K(m,8,this.length),t.read(this,m,!1,52,8)};function Y(T,m,E,Q,N,J){if(!a.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(m>N||m<J)throw new RangeError('"value" argument is out of bounds');if(E+Q>T.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(m,E,Q,N){if(m=+m,E=E>>>0,Q=Q>>>0,!N){const $=Math.pow(2,8*Q)-1;Y(this,m,E,Q,$,0)}let J=1,z=0;for(this[E]=m&255;++z<Q&&(J*=256);)this[E+z]=m/J&255;return E+Q},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(m,E,Q,N){if(m=+m,E=E>>>0,Q=Q>>>0,!N){const $=Math.pow(2,8*Q)-1;Y(this,m,E,Q,$,0)}let J=Q-1,z=1;for(this[E+J]=m&255;--J>=0&&(z*=256);)this[E+J]=m/z&255;return E+Q},a.prototype.writeUint8=a.prototype.writeUInt8=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,1,255,0),this[E]=m&255,E+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,65535,0),this[E]=m&255,this[E+1]=m>>>8,E+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,65535,0),this[E]=m>>>8,this[E+1]=m&255,E+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,4294967295,0),this[E+3]=m>>>24,this[E+2]=m>>>16,this[E+1]=m>>>8,this[E]=m&255,E+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,4294967295,0),this[E]=m>>>24,this[E+1]=m>>>16,this[E+2]=m>>>8,this[E+3]=m&255,E+4};function te(T,m,E,Q,N){Ne(m,Q,N,T,E,7);let J=Number(m&BigInt(4294967295));T[E++]=J,J=J>>8,T[E++]=J,J=J>>8,T[E++]=J,J=J>>8,T[E++]=J;let z=Number(m>>BigInt(32)&BigInt(4294967295));return T[E++]=z,z=z>>8,T[E++]=z,z=z>>8,T[E++]=z,z=z>>8,T[E++]=z,E}function ie(T,m,E,Q,N){Ne(m,Q,N,T,E,7);let J=Number(m&BigInt(4294967295));T[E+7]=J,J=J>>8,T[E+6]=J,J=J>>8,T[E+5]=J,J=J>>8,T[E+4]=J;let z=Number(m>>BigInt(32)&BigInt(4294967295));return T[E+3]=z,z=z>>8,T[E+2]=z,z=z>>8,T[E+1]=z,z=z>>8,T[E]=z,E+8}a.prototype.writeBigUInt64LE=Ze(function(m,E=0){return te(this,m,E,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Ze(function(m,E=0){return ie(this,m,E,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(m,E,Q,N){if(m=+m,E=E>>>0,!N){const ae=Math.pow(2,8*Q-1);Y(this,m,E,Q,ae-1,-ae)}let J=0,z=1,$=0;for(this[E]=m&255;++J<Q&&(z*=256);)m<0&&$===0&&this[E+J-1]!==0&&($=1),this[E+J]=(m/z>>0)-$&255;return E+Q},a.prototype.writeIntBE=function(m,E,Q,N){if(m=+m,E=E>>>0,!N){const ae=Math.pow(2,8*Q-1);Y(this,m,E,Q,ae-1,-ae)}let J=Q-1,z=1,$=0;for(this[E+J]=m&255;--J>=0&&(z*=256);)m<0&&$===0&&this[E+J+1]!==0&&($=1),this[E+J]=(m/z>>0)-$&255;return E+Q},a.prototype.writeInt8=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,1,127,-128),m<0&&(m=255+m+1),this[E]=m&255,E+1},a.prototype.writeInt16LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,32767,-32768),this[E]=m&255,this[E+1]=m>>>8,E+2},a.prototype.writeInt16BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,2,32767,-32768),this[E]=m>>>8,this[E+1]=m&255,E+2},a.prototype.writeInt32LE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,2147483647,-2147483648),this[E]=m&255,this[E+1]=m>>>8,this[E+2]=m>>>16,this[E+3]=m>>>24,E+4},a.prototype.writeInt32BE=function(m,E,Q){return m=+m,E=E>>>0,Q||Y(this,m,E,4,2147483647,-2147483648),m<0&&(m=4294967295+m+1),this[E]=m>>>24,this[E+1]=m>>>16,this[E+2]=m>>>8,this[E+3]=m&255,E+4},a.prototype.writeBigInt64LE=Ze(function(m,E=0){return te(this,m,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Ze(function(m,E=0){return ie(this,m,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function he(T,m,E,Q,N,J){if(E+Q>T.length)throw new RangeError("Index out of range");if(E<0)throw new RangeError("Index out of range")}function fe(T,m,E,Q,N){return m=+m,E=E>>>0,N||he(T,m,E,4),t.write(T,m,E,Q,23,4),E+4}a.prototype.writeFloatLE=function(m,E,Q){return fe(this,m,E,!0,Q)},a.prototype.writeFloatBE=function(m,E,Q){return fe(this,m,E,!1,Q)};function _e(T,m,E,Q,N){return m=+m,E=E>>>0,N||he(T,m,E,8),t.write(T,m,E,Q,52,8),E+8}a.prototype.writeDoubleLE=function(m,E,Q){return _e(this,m,E,!0,Q)},a.prototype.writeDoubleBE=function(m,E,Q){return _e(this,m,E,!1,Q)},a.prototype.copy=function(m,E,Q,N){if(!a.isBuffer(m))throw new TypeError("argument should be a Buffer");if(Q||(Q=0),!N&&N!==0&&(N=this.length),E>=m.length&&(E=m.length),E||(E=0),N>0&&N<Q&&(N=Q),N===Q||m.length===0||this.length===0)return 0;if(E<0)throw new RangeError("targetStart out of bounds");if(Q<0||Q>=this.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("sourceEnd out of bounds");N>this.length&&(N=this.length),m.length-E<N-Q&&(N=m.length-E+Q);const J=N-Q;return this===m&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(E,Q,N):Uint8Array.prototype.set.call(m,this.subarray(Q,N),E),J},a.prototype.fill=function(m,E,Q,N){if(typeof m=="string"){if(typeof E=="string"?(N=E,E=0,Q=this.length):typeof Q=="string"&&(N=Q,Q=this.length),N!==void 0&&typeof N!="string")throw new TypeError("encoding must be a string");if(typeof N=="string"&&!a.isEncoding(N))throw new TypeError("Unknown encoding: "+N);if(m.length===1){const z=m.charCodeAt(0);(N==="utf8"&&z<128||N==="latin1")&&(m=z)}}else typeof m=="number"?m=m&255:typeof m=="boolean"&&(m=Number(m));if(E<0||this.length<E||this.length<Q)throw new RangeError("Out of range index");if(Q<=E)return this;E=E>>>0,Q=Q===void 0?this.length:Q>>>0,m||(m=0);let J;if(typeof m=="number")for(J=E;J<Q;++J)this[J]=m;else{const z=a.isBuffer(m)?m:a.from(m,N),$=z.length;if($===0)throw new TypeError('The value "'+m+'" is invalid for argument "value"');for(J=0;J<Q-E;++J)this[J+E]=z[J%$]}return this};const Te={};function Fe(T,m,E){Te[T]=class extends E{constructor(){super(),Object.defineProperty(this,"message",{value:m.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(N){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:N,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}Fe("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Fe("ERR_INVALID_ARG_TYPE",function(T,m){return`The "${T}" argument must be of type number. Received type ${typeof m}`},TypeError),Fe("ERR_OUT_OF_RANGE",function(T,m,E){let Q=`The value of "${T}" is out of range.`,N=E;return Number.isInteger(E)&&Math.abs(E)>4294967296?N=pe(String(E)):typeof E=="bigint"&&(N=String(E),(E>BigInt(2)**BigInt(32)||E<-(BigInt(2)**BigInt(32)))&&(N=pe(N)),N+="n"),Q+=` It must be ${m}. Received ${N}`,Q},RangeError);function pe(T){let m="",E=T.length;const Q=T[0]==="-"?1:0;for(;E>=Q+4;E-=3)m=`_${T.slice(E-3,E)}${m}`;return`${T.slice(0,E)}${m}`}function Qe(T,m,E){Re(m,"offset"),(T[m]===void 0||T[m+E]===void 0)&&Ke(m,T.length-(E+1))}function Ne(T,m,E,Q,N,J){if(T>E||T<m){const z=typeof m=="bigint"?"n":"";let $;throw m===0||m===BigInt(0)?$=`>= 0${z} and < 2${z} ** ${(J+1)*8}${z}`:$=`>= -(2${z} ** ${(J+1)*8-1}${z}) and < 2 ** ${(J+1)*8-1}${z}`,new Te.ERR_OUT_OF_RANGE("value",$,T)}Qe(Q,N,J)}function Re(T,m){if(typeof T!="number")throw new Te.ERR_INVALID_ARG_TYPE(m,"number",T)}function Ke(T,m,E){throw Math.floor(T)!==T?(Re(T,E),new Te.ERR_OUT_OF_RANGE("offset","an integer",T)):m<0?new Te.ERR_BUFFER_OUT_OF_BOUNDS:new Te.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${m}`,T)}const Se=/[^+/0-9A-Za-z-_]/g;function ye(T){if(T=T.split("=")[0],T=T.trim().replace(Se,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ke(T,m){m=m||1/0;let E;const Q=T.length;let N=null;const J=[];for(let z=0;z<Q;++z){if(E=T.charCodeAt(z),E>55295&&E<57344){if(!N){if(E>56319){(m-=3)>-1&&J.push(239,191,189);continue}else if(z+1===Q){(m-=3)>-1&&J.push(239,191,189);continue}N=E;continue}if(E<56320){(m-=3)>-1&&J.push(239,191,189),N=E;continue}E=(N-55296<<10|E-56320)+65536}else N&&(m-=3)>-1&&J.push(239,191,189);if(N=null,E<128){if((m-=1)<0)break;J.push(E)}else if(E<2048){if((m-=2)<0)break;J.push(E>>6|192,E&63|128)}else if(E<65536){if((m-=3)<0)break;J.push(E>>12|224,E>>6&63|128,E&63|128)}else if(E<1114112){if((m-=4)<0)break;J.push(E>>18|240,E>>12&63|128,E>>6&63|128,E&63|128)}else throw new Error("Invalid code point")}return J}function Ue(T){const m=[];for(let E=0;E<T.length;++E)m.push(T.charCodeAt(E)&255);return m}function Xe(T,m){let E,Q,N;const J=[];for(let z=0;z<T.length&&!((m-=2)<0);++z)E=T.charCodeAt(z),Q=E>>8,N=E%256,J.push(N),J.push(Q);return J}function Ge(T){return e.toByteArray(ye(T))}function $e(T,m,E,Q){let N;for(N=0;N<Q&&!(N+E>=m.length||N>=T.length);++N)m[N+E]=T[N];return N}function Ce(T,m){return T instanceof m||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===m.name}function et(T){return T!==T}const ot=function(){const T="0123456789abcdef",m=new Array(256);for(let E=0;E<16;++E){const Q=E*16;for(let N=0;N<16;++N)m[Q+N]=T[E]+T[N]}return m}();function Ze(T){return typeof BigInt>"u"?ze:T}function ze(){throw new Error("BigInt not supported")}})(mu);var Vi=lt,St=CE,Iu=mu.Buffer;$i.__TYPEDARRAY_POOL||($i.__TYPEDARRAY_POOL={UINT8:St([32,0]),UINT16:St([32,0]),UINT32:St([32,0]),BIGUINT64:St([32,0]),INT8:St([32,0]),INT16:St([32,0]),INT32:St([32,0]),BIGINT64:St([32,0]),FLOAT:St([32,0]),DOUBLE:St([32,0]),DATA:St([32,0]),UINT8C:St([32,0]),BUFFER:St([32,0])});var RE=typeof Uint8ClampedArray<"u",DE=typeof BigUint64Array<"u",LE=typeof BigInt64Array<"u",ht=$i.__TYPEDARRAY_POOL;ht.UINT8C||(ht.UINT8C=St([32,0])),ht.BIGUINT64||(ht.BIGUINT64=St([32,0])),ht.BIGINT64||(ht.BIGINT64=St([32,0])),ht.BUFFER||(ht.BUFFER=St([32,0]));var Us=ht.DATA,Gs=ht.BUFFER;Pe.free=function(e){if(Iu.isBuffer(e))Gs[Vi.log2(e.length)].push(e);else{if(Object.prototype.toString.call(e)!=="[object ArrayBuffer]"&&(e=e.buffer),!e)return;var t=e.length||e.byteLength,i=Vi.log2(t)|0;Us[i].push(e)}};function vu(r){if(r){var e=r.length||r.byteLength,t=Vi.log2(e);Us[t].push(r)}}function kE(r){vu(r.buffer)}Pe.freeUint8=Pe.freeUint16=Pe.freeUint32=Pe.freeBigUint64=Pe.freeInt8=Pe.freeInt16=Pe.freeInt32=Pe.freeBigInt64=Pe.freeFloat32=Pe.freeFloat=Pe.freeFloat64=Pe.freeDouble=Pe.freeUint8Clamped=Pe.freeDataView=kE,Pe.freeArrayBuffer=vu,Pe.freeBuffer=function(e){Gs[Vi.log2(e.length)].push(e)},Pe.malloc=function(e,t){if(t===void 0||t==="arraybuffer")return Mt(e);switch(t){case"uint8":return Oa(e);case"uint16":return yu(e);case"uint32":return Cu(e);case"int8":return Bu(e);case"int16":return Tu(e);case"int32":return Su(e);case"float":case"float32":return bu(e);case"double":case"float64":return xu(e);case"uint8_clamped":return Qu(e);case"bigint64":return wu(e);case"biguint64":return _u(e);case"buffer":return Du(e);case"data":case"dataview":return Ru(e);default:return null}return null};function Mt(e){var e=Vi.nextPow2(e),t=Vi.log2(e),i=Us[t];return i.length>0?i.pop():new ArrayBuffer(e)}Pe.mallocArrayBuffer=Mt;function Oa(r){return new Uint8Array(Mt(r),0,r)}Pe.mallocUint8=Oa;function yu(r){return new Uint16Array(Mt(2*r),0,r)}Pe.mallocUint16=yu;function Cu(r){return new Uint32Array(Mt(4*r),0,r)}Pe.mallocUint32=Cu;function Bu(r){return new Int8Array(Mt(r),0,r)}Pe.mallocInt8=Bu;function Tu(r){return new Int16Array(Mt(2*r),0,r)}Pe.mallocInt16=Tu;function Su(r){return new Int32Array(Mt(4*r),0,r)}Pe.mallocInt32=Su;function bu(r){return new Float32Array(Mt(4*r),0,r)}Pe.mallocFloat32=Pe.mallocFloat=bu;function xu(r){return new Float64Array(Mt(8*r),0,r)}Pe.mallocFloat64=Pe.mallocDouble=xu;function Qu(r){return RE?new Uint8ClampedArray(Mt(r),0,r):Oa(r)}Pe.mallocUint8Clamped=Qu;function _u(r){return DE?new BigUint64Array(Mt(8*r),0,r):null}Pe.mallocBigUint64=_u;function wu(r){return LE?new BigInt64Array(Mt(8*r),0,r):null}Pe.mallocBigInt64=wu;function Ru(r){return new DataView(Mt(r),0,r)}Pe.mallocDataView=Ru;function Du(r){r=Vi.nextPow2(r);var e=Vi.log2(r),t=Gs[e];return t.length>0?t.pop():new Iu(r)}Pe.mallocBuffer=Du,Pe.clearCache=function(){for(var e=0;e<32;++e)ht.UINT8[e].length=0,ht.UINT16[e].length=0,ht.UINT32[e].length=0,ht.INT8[e].length=0,ht.INT16[e].length=0,ht.INT32[e].length=0,ht.FLOAT[e].length=0,ht.DOUBLE[e].length=0,ht.BIGUINT64[e].length=0,ht.BIGINT64[e].length=0,ht.UINT8C[e].length=0,Us[e].length=0,Gs[e].length=0};var $s=iE,Ua=du,Fr=Pe,ME=UE,Hs=null,Ga=null,Ys=null;function FE(r){Hs=[r.LINEAR,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_NEAREST],Ga=[r.NEAREST,r.LINEAR,r.NEAREST_MIPMAP_NEAREST,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_LINEAR],Ys=[r.REPEAT,r.CLAMP_TO_EDGE,r.MIRRORED_REPEAT]}function Lu(r){return typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof ImageData<"u"&&r instanceof ImageData}var ku=function(r,e){Ua.muls(r,e,255)};function $a(r,e,t){var i=r.gl,n=i.getParameter(i.MAX_TEXTURE_SIZE);if(e<0||e>n||t<0||t>n)throw new Error("gl-texture2d: Invalid texture size");return r._shape=[e,t],r.bind(),i.texImage2D(i.TEXTURE_2D,0,r.format,e,t,0,r.format,r.type,null),r._mipLevels=[0],r}function Vs(r,e,t,i,n,s){this.gl=r,this.handle=e,this.format=n,this.type=s,this._shape=[t,i],this._mipLevels=[0],this._magFilter=r.NEAREST,this._minFilter=r.NEAREST,this._wrapS=r.CLAMP_TO_EDGE,this._wrapT=r.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,a=[this._wrapS,this._wrapT];Object.defineProperties(a,[{get:function(){return o._wrapS},set:function(A){return o.wrapS=A}},{get:function(){return o._wrapT},set:function(A){return o.wrapT=A}}]),this._wrapVector=a;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(A){return o.width=A}},{get:function(){return o._shape[1]},set:function(A){return o.height=A}}]),this._shapeVector=l}var Dn=Vs.prototype;Object.defineProperties(Dn,{minFilter:{get:function(){return this._minFilter},set:function(r){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Hs.indexOf(r)>=0&&(e.getExtension("OES_texture_float_linear")||(r=e.NEAREST)),Ga.indexOf(r)<0)throw new Error("gl-texture2d: Unknown filter mode "+r);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,r),this._minFilter=r}},magFilter:{get:function(){return this._magFilter},set:function(r){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Hs.indexOf(r)>=0&&(e.getExtension("OES_texture_float_linear")||(r=e.NEAREST)),Ga.indexOf(r)<0)throw new Error("gl-texture2d: Unknown filter mode "+r);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,r),this._magFilter=r}},mipSamples:{get:function(){return this._anisoSamples},set:function(r){var e=this._anisoSamples;if(this._anisoSamples=Math.max(r,1)|0,e!==this._anisoSamples){var t=this.gl.getExtension("EXT_texture_filter_anisotropic");t&&this.gl.texParameterf(this.gl.TEXTURE_2D,t.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(r){if(this.bind(),Ys.indexOf(r)<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,r),this._wrapS=r}},wrapT:{get:function(){return this._wrapT},set:function(r){if(this.bind(),Ys.indexOf(r)<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,r),this._wrapT=r}},wrap:{get:function(){return this._wrapVector},set:function(r){if(Array.isArray(r)||(r=[r,r]),r.length!==2)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(Ys.indexOf(r[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+r);this._wrapS=r[0],this._wrapT=r[1];var t=this.gl;return this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,this._wrapS),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,this._wrapT),r}},shape:{get:function(){return this._shapeVector},set:function(r){if(!Array.isArray(r))r=[r|0,r|0];else if(r.length!==2)throw new Error("gl-texture2d: Invalid texture shape");return $a(this,r[0]|0,r[1]|0),[r[0]|0,r[1]|0]}},width:{get:function(){return this._shape[0]},set:function(r){return r=r|0,$a(this,r,this._shape[1]),r}},height:{get:function(){return this._shape[1]},set:function(r){return r=r|0,$a(this,this._shape[0],r),r}}}),Dn.bind=function(r){var e=this.gl;return r!==void 0&&e.activeTexture(e.TEXTURE0+(r|0)),e.bindTexture(e.TEXTURE_2D,this.handle),r!==void 0?r|0:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},Dn.dispose=function(){this.gl.deleteTexture(this.handle)},Dn.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var r=Math.min(this._shape[0],this._shape[1]),e=0;r>0;++e,r>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},Dn.setPixels=function(r,e,t,i){var n=this.gl;this.bind(),Array.isArray(e)?(i=t,t=e[1]|0,e=e[0]|0):(e=e||0,t=t||0),i=i||0;var s=Lu(r)?r:r.raw;if(s){var o=this._mipLevels.indexOf(i)<0;o?(n.texImage2D(n.TEXTURE_2D,0,this.format,this.format,this.type,s),this._mipLevels.push(i)):n.texSubImage2D(n.TEXTURE_2D,i,e,t,this.format,this.type,s)}else if(r.shape&&r.stride&&r.data){if(r.shape.length<2||e+r.shape[1]>this._shape[1]>>>i||t+r.shape[0]>this._shape[0]>>>i||e<0||t<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");PE(n,e,t,i,this.format,this.type,this._mipLevels,r)}else throw new Error("gl-texture2d: Unsupported data type")};function Mu(r,e){return r.length===3?e[2]===1&&e[1]===r[0]*r[2]&&e[0]===r[2]:e[0]===1&&e[1]===r[0]}function PE(r,e,t,i,n,s,o,a){var l=a.dtype,A=a.shape.slice();if(A.length<2||A.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var u=0,c=0,h=Mu(A,a.stride.slice());if(l==="float32"?u=r.FLOAT:l==="float64"?(u=r.FLOAT,h=!1,l="float32"):l==="uint8"?u=r.UNSIGNED_BYTE:(u=r.UNSIGNED_BYTE,h=!1,l="uint8"),A.length===2)c=r.LUMINANCE,A=[A[0],A[1],1],a=$s(a.data,A,[a.stride[0],a.stride[1],1],a.offset);else if(A.length===3){if(A[2]===1)c=r.ALPHA;else if(A[2]===2)c=r.LUMINANCE_ALPHA;else if(A[2]===3)c=r.RGB;else if(A[2]===4)c=r.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");A[2]}else throw new Error("gl-texture2d: Invalid shape for texture");if((c===r.LUMINANCE||c===r.ALPHA)&&(n===r.LUMINANCE||n===r.ALPHA)&&(c=n),c!==n)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=a.size,f=o.indexOf(i)<0;if(f&&o.push(i),u===s&&h)a.offset===0&&a.data.length===d?f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,a.data):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,a.data):f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,a.data.subarray(a.offset,a.offset+d)):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,a.data.subarray(a.offset,a.offset+d));else{var g;s===r.FLOAT?g=Fr.mallocFloat32(d):g=Fr.mallocUint8(d);var p=$s(g,A,[A[2],A[2]*A[0],1]);u===r.FLOAT&&s===r.UNSIGNED_BYTE?ku(p,a):Ua.assign(p,a),f?r.texImage2D(r.TEXTURE_2D,i,n,A[0],A[1],0,n,s,g.subarray(0,d)):r.texSubImage2D(r.TEXTURE_2D,i,e,t,A[0],A[1],n,s,g.subarray(0,d)),s===r.FLOAT?Fr.freeFloat32(g):Fr.freeUint8(g)}}function Ha(r){var e=r.createTexture();return r.bindTexture(r.TEXTURE_2D,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e}function Fu(r,e,t,i,n){var s=r.getParameter(r.MAX_TEXTURE_SIZE);if(e<0||e>s||t<0||t>s)throw new Error("gl-texture2d: Invalid texture shape");if(n===r.FLOAT&&!r.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,i,e,t,0,i,n,null),new Vs(r,o,e,t,i,n)}function NE(r,e,t,i,n,s){var o=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,n,n,s,e),new Vs(r,o,t,i,n,s)}function OE(r,e){var t=e.dtype,i=e.shape.slice(),n=r.getParameter(r.MAX_TEXTURE_SIZE);if(i[0]<0||i[0]>n||i[1]<0||i[1]>n)throw new Error("gl-texture2d: Invalid texture size");var s=Mu(i,e.stride.slice()),o=0;t==="float32"?o=r.FLOAT:t==="float64"?(o=r.FLOAT,s=!1,t="float32"):t==="uint8"?o=r.UNSIGNED_BYTE:(o=r.UNSIGNED_BYTE,s=!1,t="uint8");var a=0;if(i.length===2)a=r.LUMINANCE,i=[i[0],i[1],1],e=$s(e.data,i,[e.stride[0],e.stride[1],1],e.offset);else if(i.length===3)if(i[2]===1)a=r.ALPHA;else if(i[2]===2)a=r.LUMINANCE_ALPHA;else if(i[2]===3)a=r.RGB;else if(i[2]===4)a=r.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");else throw new Error("gl-texture2d: Invalid shape for texture");o===r.FLOAT&&!r.getExtension("OES_texture_float")&&(o=r.UNSIGNED_BYTE,s=!1);var l,A,u=e.size;if(s)e.offset===0&&e.data.length===u?l=e.data:l=e.data.subarray(e.offset,e.offset+u);else{var c=[i[2],i[2]*i[0],1];A=Fr.malloc(u,t);var h=$s(A,i,c,0);(t==="float32"||t==="float64")&&o===r.UNSIGNED_BYTE?ku(h,e):Ua.assign(h,e),l=A.subarray(0,u)}var d=Ha(r);return r.texImage2D(r.TEXTURE_2D,0,a,i[0],i[1],0,a,o,l),s||Fr.free(A),new Vs(r,d,i[0],i[1],a,o)}function UE(r){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(Hs||FE(r),typeof arguments[1]=="number")return Fu(r,arguments[1],arguments[2],arguments[3]||r.RGBA,arguments[4]||r.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return Fu(r,arguments[1][0]|0,arguments[1][1]|0,arguments[2]||r.RGBA,arguments[3]||r.UNSIGNED_BYTE);if(typeof arguments[1]=="object"){var e=arguments[1],t=Lu(e)?e:e.raw;if(t)return NE(r,t,e.width|0,e.height|0,arguments[2]||r.RGBA,arguments[3]||r.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return OE(r,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}const Ks=_a(ME);var Pu={},Nu=GE;function GE(r,e){for(var t={},i=0;i<r.length;++i)for(var n=r[i].name,s=n.split("."),o=t,a=0;a<s.length;++a){var l=s[a].split("[");if(l.length>1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var A=1;A<l.length;++A){var u=parseInt(l[A]);A<l.length-1||a<s.length-1?(u in o||(A<l.length-1?o[u]=[]:o[u]={}),o=o[u]):e?o[u]=i:o[u]=r[i].type}}else a<s.length-1?(l[0]in o||(o[l[0]]={}),o=o[l[0]]):e?o[l[0]]=i:o[l[0]]=r[i].type}return t}function Ln(r,e,t){this.shortMessage=e||"",this.longMessage=t||"",this.rawError=r||"",this.message="gl-shader: "+(e||r||"")+(t?`
114
114
  `+t:""),this.stack=new Error().stack}Ln.prototype=new Error,Ln.prototype.name="GLError",Ln.prototype.constructor=Ln;var Ws=Ln,$E=Nu,pr=Ws,HE=YE;function Ou(r){return function(){return r}}function Ya(r,e){for(var t=new Array(r),i=0;i<r;++i)t[i]=e;return t}function YE(r,e,t,i){function n(c){return function(h,d,f){return h.getUniform(d.program,f[c])}}function s(c){return function(d){for(var f=o("",c),g=0;g<f.length;++g){var p=f[g],v=p[0],B=p[1];if(i[B]){var C=d;if(typeof v=="string"&&(v.indexOf(".")===0||v.indexOf("[")===0)){var y=v;if(v.indexOf(".")===0&&(y=v.slice(1)),y.indexOf("]")===y.length-1){var x=y.indexOf("["),w=y.slice(0,x),D=y.slice(x+1,y.length-1);C=w?d[w][D]:d[D]}else C=d[y]}var F=t[B].type,O;switch(F){case"bool":case"int":case"sampler2D":case"samplerCube":r.uniform1i(i[B],C);break;case"float":r.uniform1f(i[B],C);break;default:var M=F.indexOf("vec");if(0<=M&&M<=1&&F.length===4+M){if(O=F.charCodeAt(F.length-1)-48,O<2||O>4)throw new pr("","Invalid data type");switch(F.charAt(0)){case"b":case"i":r["uniform"+O+"iv"](i[B],C);break;case"v":r["uniform"+O+"fv"](i[B],C);break;default:throw new pr("","Unrecognized data type for vector "+name+": "+F)}}else if(F.indexOf("mat")===0&&F.length===4){if(O=F.charCodeAt(F.length-1)-48,O<2||O>4)throw new pr("","Invalid uniform dimension type for matrix "+name+": "+F);r["uniformMatrix"+O+"fv"](i[B],!1,C);break}else throw new pr("","Unknown uniform data type for "+name+": "+F)}}}}}function o(c,h){if(typeof h!="object")return[[c,h]];var d=[];for(var f in h){var g=h[f],p=c;parseInt(f)+""===f?p+="["+f+"]":p+="."+f,typeof g=="object"?d.push.apply(d,o(p,g)):d.push([p,g])}return d}function a(c){switch(c){case"bool":return!1;case"int":case"sampler2D":case"samplerCube":return 0;case"float":return 0;default:var h=c.indexOf("vec");if(0<=h&&h<=1&&c.length===4+h){var d=c.charCodeAt(c.length-1)-48;if(d<2||d>4)throw new pr("","Invalid data type");return c.charAt(0)==="b"?Ya(d,!1):Ya(d,0)}else if(c.indexOf("mat")===0&&c.length===4){var d=c.charCodeAt(c.length-1)-48;if(d<2||d>4)throw new pr("","Invalid uniform dimension type for matrix "+name+": "+c);return Ya(d*d,0)}else throw new pr("","Unknown uniform data type for "+name+": "+c)}}function l(c,h,d){if(typeof d=="object"){var f=A(d);Object.defineProperty(c,h,{get:Ou(f),set:s(d),enumerable:!0,configurable:!1})}else i[d]?Object.defineProperty(c,h,{get:n(d),set:s(d),enumerable:!0,configurable:!1}):c[h]=a(t[d].type)}function A(c){var h;if(Array.isArray(c)){h=new Array(c.length);for(var d=0;d<c.length;++d)l(h,d,c[d])}else{h={};for(var f in c)l(h,f,c[f])}return h}var u=$E(t,!0);return{get:Ou(A(u)),set:s(u),enumerable:!0,configurable:!0}}var VE=qE,Va=Ws;function Uu(r,e,t,i,n,s){this._gl=r,this._wrapper=e,this._index=t,this._locations=i,this._dimension=n,this._constFunc=s}var Ka=Uu.prototype;Ka.pointer=function(e,t,i,n){var s=this,o=s._gl,a=s._locations[s._index];o.vertexAttribPointer(a,s._dimension,e||o.FLOAT,!!t,i||0,n||0),o.enableVertexAttribArray(a)},Ka.set=function(r,e,t,i){return this._constFunc(this._locations[this._index],r,e,t,i)},Object.defineProperty(Ka,"location",{get:function(){return this._locations[this._index]},set:function(r){return r!==this._locations[this._index]&&(this._locations[this._index]=r|0,this._wrapper.program=null),r|0}});var KE=[function(r,e,t){return t.length===void 0?r.vertexAttrib1f(e,t):r.vertexAttrib1fv(e,t)},function(r,e,t,i){return t.length===void 0?r.vertexAttrib2f(e,t,i):r.vertexAttrib2fv(e,t)},function(r,e,t,i,n){return t.length===void 0?r.vertexAttrib3f(e,t,i,n):r.vertexAttrib3fv(e,t)},function(r,e,t,i,n,s){return t.length===void 0?r.vertexAttrib4f(e,t,i,n,s):r.vertexAttrib4fv(e,t)}];function Wa(r,e,t,i,n,s,o){var a=KE[n],l=new Uu(r,e,t,i,n,a);Object.defineProperty(s,o,{set:function(A){return r.disableVertexAttribArray(i[t]),a(r,i[t],A),A},get:function(){return l},enumerable:!0})}function WE(r,e,t,i,n,s,o){for(var a=new Array(n),l=new Array(n),A=0;A<n;++A)Wa(r,e,t[A],i,n,a,A),l[A]=a[A];Object.defineProperty(a,"location",{set:function(h){if(Array.isArray(h))for(var d=0;d<n;++d)l[d].location=h[d];else for(var d=0;d<n;++d)l[d].location=h+d;return h},get:function(){for(var h=new Array(n),d=0;d<n;++d)h[d]=i[t[d]];return h},enumerable:!0}),a.pointer=function(h,d,f,g){h=h||r.FLOAT,d=!!d,f=f||n*n,g=g||0;for(var p=0;p<n;++p){var v=i[t[p]];r.vertexAttribPointer(v,n,h,d,f,g+p*n),r.enableVertexAttribArray(v)}};var u=new Array(n),c=r["vertexAttrib"+n+"fv"];Object.defineProperty(s,o,{set:function(h){for(var d=0;d<n;++d){var f=i[t[d]];if(r.disableVertexAttribArray(f),Array.isArray(h[0]))c.call(r,f,h[d]);else{for(var g=0;g<n;++g)u[g]=h[n*d+g];c.call(r,f,u)}}return h},get:function(){return a},enumerable:!0})}function qE(r,e,t,i){for(var n={},s=0,o=t.length;s<o;++s){var a=t[s],l=a.name,A=a.type,u=a.locations;switch(A){case"bool":case"int":case"float":Wa(r,e,u[0],i,1,n,l);break;default:if(A.indexOf("vec")>=0){var c=A.charCodeAt(A.length-1)-48;if(c<2||c>4)throw new Va("","Invalid data type for attribute "+l+": "+A);Wa(r,e,u[0],i,c,n,l)}else if(A.indexOf("mat")>=0){var c=A.charCodeAt(A.length-1)-48;if(c<2||c>4)throw new Va("","Invalid data type for attribute "+l+": "+A);WE(r,e,u,i,c,n,l)}else throw new Va("","Unknown data type for attribute "+l+": "+A);break}}return n}var qa={},Gu={};(function(r){(function(){var e={not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function t(a){return n(o(a),arguments)}function i(a,l){return t.apply(null,[a].concat(l||[]))}function n(a,l){var A=1,u=a.length,c,h="",d,f,g,p,v,B,C,y;for(d=0;d<u;d++)if(typeof a[d]=="string")h+=a[d];else if(typeof a[d]=="object"){if(g=a[d],g.keys)for(c=l[A],f=0;f<g.keys.length;f++){if(c==null)throw new Error(t('[sprintf] Cannot access property "%s" of undefined value "%s"',g.keys[f],g.keys[f-1]));c=c[g.keys[f]]}else g.param_no?c=l[g.param_no]:c=l[A++];if(e.not_type.test(g.type)&&e.not_primitive.test(g.type)&&c instanceof Function&&(c=c()),e.numeric_arg.test(g.type)&&typeof c!="number"&&isNaN(c))throw new TypeError(t("[sprintf] expecting number but found %T",c));switch(e.number.test(g.type)&&(C=c>=0),g.type){case"b":c=parseInt(c,10).toString(2);break;case"c":c=String.fromCharCode(parseInt(c,10));break;case"d":case"i":c=parseInt(c,10);break;case"j":c=JSON.stringify(c,null,g.width?parseInt(g.width):0);break;case"e":c=g.precision?parseFloat(c).toExponential(g.precision):parseFloat(c).toExponential();break;case"f":c=g.precision?parseFloat(c).toFixed(g.precision):parseFloat(c);break;case"g":c=g.precision?String(Number(c.toPrecision(g.precision))):parseFloat(c);break;case"o":c=(parseInt(c,10)>>>0).toString(8);break;case"s":c=String(c),c=g.precision?c.substring(0,g.precision):c;break;case"t":c=String(!!c),c=g.precision?c.substring(0,g.precision):c;break;case"T":c=Object.prototype.toString.call(c).slice(8,-1).toLowerCase(),c=g.precision?c.substring(0,g.precision):c;break;case"u":c=parseInt(c,10)>>>0;break;case"v":c=c.valueOf(),c=g.precision?c.substring(0,g.precision):c;break;case"x":c=(parseInt(c,10)>>>0).toString(16);break;case"X":c=(parseInt(c,10)>>>0).toString(16).toUpperCase();break}e.json.test(g.type)?h+=c:(e.number.test(g.type)&&(!C||g.sign)?(y=C?"+":"-",c=c.toString().replace(e.sign,"")):y="",v=g.pad_char?g.pad_char==="0"?"0":g.pad_char.charAt(1):" ",B=g.width-(y+c).length,p=g.width&&B>0?v.repeat(B):"",h+=g.align?y+c+p:v==="0"?y+p+c:p+y+c)}return h}var s=Object.create(null);function o(a){if(s[a])return s[a];for(var l=a,A,u=[],c=0;l;){if((A=e.text.exec(l))!==null)u.push(A[0]);else if((A=e.modulo.exec(l))!==null)u.push("%");else if((A=e.placeholder.exec(l))!==null){if(A[2]){c|=1;var h=[],d=A[2],f=[];if((f=e.key.exec(d))!==null)for(h.push(f[1]);(d=d.substring(f[0].length))!=="";)if((f=e.key_access.exec(d))!==null)h.push(f[1]);else if((f=e.index_access.exec(d))!==null)h.push(f[1]);else throw new SyntaxError("[sprintf] failed to parse named argument key");else throw new SyntaxError("[sprintf] failed to parse named argument key");A[2]=h}else c|=2;if(c===3)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");u.push({placeholder:A[0],param_no:A[1],keys:A[2],sign:A[3],pad_char:A[4],align:A[5],width:A[6],precision:A[7],type:A[8]})}else throw new SyntaxError("[sprintf] unexpected placeholder");l=l.substring(A[0].length)}return s[a]=u}r.sprintf=t,r.vsprintf=i,typeof window<"u"&&(window.sprintf=t,window.vsprintf=i)})()})(Gu);var JE={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34e3:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},jE=JE,XE=function(e){return jE[e]},$u=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","uint","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"],zE=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],Hu=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"],ZE=$u,eI=ZE.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),Ja=Hu;Ja=Ja.slice().filter(function(r){return!/^(gl\_|texture)/.test(r)});var tI=Ja.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"]),iI=hI,rI=$u,Yu=zE,nI=Hu,sI=eI,oI=tI,Zt=999,Vu=9999,ja=0,Xa=1,Ku=2,Wu=3,qu=4,kn=5,aI=6,lI=7,AI=8,Ju=9,cI=10,ju=11,uI=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];function hI(r){var e=0,t=0,i=Zt,n,s,o=[],a=[],l=1,A=0,u=0,c=!1,h=!1,d="",f;r=r||{};var g=nI,p=rI;r.version==="300 es"&&(g=oI,p=sI);for(var v={},B={},e=0;e<g.length;e++)v[g[e]]=!0;for(var e=0;e<p.length;e++)B[p[e]]=!0;return function(q){return a=[],q!==null?y(q):x()};function C(q){q.length&&a.push({type:uI[i],data:q,position:u,line:l,column:A})}function y(q){e=0,q.toString&&(q=q.toString()),d+=q.replace(/\r\n/g,`
115
115
  `),f=d.length;for(var R;n=d[e],e<f;){switch(R=e,i){case ja:e=M();break;case Xa:e=O();break;case Ku:e=F();break;case Wu:e=j();break;case qu:e=oe();break;case ju:e=le();break;case kn:e=L();break;case Vu:e=U();break;case Ju:e=D();break;case Zt:e=w();break}if(R!==e)switch(d[R]){case`
116
116
  `:A=0,++l;break;default:++A;break}}return t+=e,d=d.slice(e),a}function x(q){return o.length&&C(o.join("")),i=cI,C("(eof)"),a}function w(){return o=o.length?[]:o,s==="/"&&n==="*"?(u=t+e-1,i=ja,s=n,e+1):s==="/"&&n==="/"?(u=t+e-1,i=Xa,s=n,e+1):n==="#"?(i=Ku,u=t+e,e):/\s/.test(n)?(i=Ju,u=t+e,e):(c=/\d/.test(n),h=/[^\w_]/.test(n),u=t+e,i=c?qu:h?Wu:Vu,e)}function D(){return/[^\s]/g.test(n)?(C(o.join("")),i=Zt,e):(o.push(n),s=n,e+1)}function F(){return(n==="\r"||n===`
@@ -2473,7 +2473,7 @@ vec4 transition(vec2 uv) {
2473
2473
  return mix(a, b, step(0.0+p.y,progress));
2474
2474
  }
2475
2475
  `,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}];const uh=_a(nv);var hh;function sv(r){if(typeof r=="string"){const[e,t]=r.split(":");return Math.min(parseFloat(e),parseFloat(t))}return r}function ov(r){if(typeof r=="string"){const[e,t]=r.split(":"),i=parseFloat(e),n=parseFloat(t);return i/n}return r}function ol({resolution:r,aspectRatio:e}){const t=sv(r),i=ov(e),n=i>=1,s=Math.min(n?t*i:t/i,t),o=Math.max(n?t*i:t/i,t);return{resolution:t,aspectRatio:i,height:n?s:o,width:n?o:s}}const dh={linear:Em,easeIn:xa,easeInOut:vm,easeOut:Im,circIn:au,circInOut:ym,circOut:lu,backIn:Qa,backInOut:Bm,backOut:Cm,anticipate:Tm,bounceIn:Qm,bounceInOut:_m,bounceOut:_s};Ts((r,e,{clamp:t=!0,ease:i="easeIn",...n}={})=>hm(r,e,{...n,clamp:t,ease:dh[i]}),{cacheKey:([r,e,t])=>JSON.stringify({from:r,to:e,options:t})});function av({animation:r,sceneTime:e}){const t=r.keyframes;if(!t||t.length===0)return null;const i=[...t].sort((s,o)=>s.time-o.time);if(e<i[0].time)return null;const n=i[i.length-1];if(e>=n.time)return r.renderer.processor.getTargetState(n.value);for(let s=0;s<i.length-1;s++){const o=i[s],a=i[s+1];if(e>=o.time&&e<=a.time){const l=a.time-o.time,A=l===0?0:(e-o.time)/l,u=o.easing||"linear",c=r.renderer.processor.getTargetState(o.value);return r.renderer.processor.interpolateState({easing:u,progress:A,from:c,value:a.value})}}return null}function lv({layout:r,sceneTime:e,animations:t}){var i,n,s,o,a,l,A,u,c,h,d;let f={clip:null,opacity:((i=r==null?void 0:r.transform)==null?void 0:i.opacity)??1,translation:{x:((s=(n=r==null?void 0:r.transform)==null?void 0:n.translate)==null?void 0:s.x)??0,y:((a=(o=r==null?void 0:r.transform)==null?void 0:o.translate)==null?void 0:a.y)??0},scale:((l=r==null?void 0:r.transform)==null?void 0:l.scale)??1,rotation:((A=r==null?void 0:r.transform)==null?void 0:A.rotation)??0,dimensions:{widthRatio:((c=(u=r==null?void 0:r.transform)==null?void 0:u.dimension)==null?void 0:c.widthRatio)??1,heightRatio:((d=(h=r==null?void 0:r.transform)==null?void 0:h.dimension)==null?void 0:d.heightRatio)??1}};if(!t)return f;for(const g of Object.values(t)){const p=av({animation:g,sceneTime:e});p&&(f={...f,...p})}return f}let js;const Av=new Uint8Array(16);function cv(){if(!js&&(js=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!js))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return js(Av)}const bt=[];for(let r=0;r<256;++r)bt.push((r+256).toString(16).slice(1));function uv(r,e=0){return bt[r[e+0]]+bt[r[e+1]]+bt[r[e+2]]+bt[r[e+3]]+"-"+bt[r[e+4]]+bt[r[e+5]]+"-"+bt[r[e+6]]+bt[r[e+7]]+"-"+bt[r[e+8]]+bt[r[e+9]]+"-"+bt[r[e+10]]+bt[r[e+11]]+bt[r[e+12]]+bt[r[e+13]]+bt[r[e+14]]+bt[r[e+15]]}const fh={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function hv(r,e,t){if(fh.randomUUID&&!r)return fh.randomUUID();r=r||{};const i=r.random||(r.rng||cv)();return i[6]=i[6]&15|64,i[8]=i[8]&63|128,uv(i)}function dv(r=.4,e=.4){const t=Math.max(.1,Math.min(.8,r)),i=Math.max(.2,Math.min(.6,e)),s=(1-t)/2,a=1-i;return[{x:0,y:s},{x:a,y:s},{x:a,y:0},{x:1,y:.5},{x:a,y:1},{x:a,y:1-s},{x:0,y:1-s}]}const Xs=64;function fv(){const r=[],e={x:.5,y:.5},t=.5;for(let i=0;i<Xs;i++){const n=i/Xs*2*Math.PI,s=e.x+t*Math.cos(n),o=e.y+t*Math.sin(n);r.push({x:s,y:o})}return r}function gv(r=1){const e=[],t={x:.5,y:.5};let i,n;r>=1?(i=.5,n=.5/r):(i=.5*r,n=.5);for(let s=0;s<Xs;s++){const o=s/Xs*2*Math.PI,a=t.x+i*Math.cos(o),l=t.y+n*Math.sin(o);e.push({x:a,y:l})}return e}function pv(){const r=[];for(let t=0;t<=100;t++){const i=t/100*2*Math.PI,n=16*Math.sin(i)**3,s=-(13*Math.cos(i)-5*Math.cos(2*i)-2*Math.cos(3*i)-Math.cos(4*i)),o=(n+16)/32,a=(s+13)/26;r.push({x:o,y:a})}return r}function gh(r=0,e=1){if(r===0)return[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}];const t=r*Math.PI/180,i=Math.tan(t)/e;return[{x:Math.max(0,Math.min(1,0+i)),y:0},{x:Math.max(0,Math.min(1,1+i)),y:0},{x:Math.max(0,Math.min(1,1-i)),y:1},{x:Math.max(0,Math.min(1,0-i)),y:1}]}function zs(r){if(r<3)throw new Error("A polygon must have at least 3 sides");const e=[],t=[];for(let A=0;A<r;A++){const u=A*2*Math.PI/r-Math.PI/2,c=Math.cos(u),h=Math.sin(u);t.push({x:c,y:h})}const i=Math.min(...t.map(A=>A.x)),n=Math.max(...t.map(A=>A.x)),s=Math.min(...t.map(A=>A.y)),o=Math.max(...t.map(A=>A.y)),a=n-i,l=o-s;for(const A of t){const u=(A.x-i)/a,c=(A.y-s)/l;e.push({x:u,y:c})}return e}function ph(r=90){const e=r*Math.PI/180,i=.5/Math.tan(e),s=1/(1+Math.abs(i)*2),o=i*s;return[{x:.5+o,y:0},{x:1,y:.5},{x:.5-o,y:1},{x:0,y:.5}]}function mv(r=5,e=.4){const t=[];for(let n=0;n<r*2;n++){const s=n*Math.PI/r-Math.PI/2,o=n%2===0?.5:e,a=.5+o*Math.cos(s),l=.5+o*Math.sin(s);t.push({x:a,y:l})}return t}function Ev(r="isosceles",e={}){switch(r){case"equilateral":return Iv();case"isosceles":return mh(e.baseAngle??60);case"right":return vv(e.rightAnglePosition??"bottom-left");case"scalene":return yv(e.angles??[60,60,60])}}function Iv(){return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}]}function mh(r){const e=r*Math.PI/180,t=.5/Math.tan(e),i=Math.max(.1,Math.min(2,t));return[{x:.5,y:1-Math.min(1,i)},{x:0,y:1},{x:1,y:1}]}function vv(r){switch(r){case"top":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}];case"bottom-left":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}];case"bottom-right":return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}]}}function yv(r){return mh(r[0])}function Cv(r={},e=1){const{type:t="rectangle",customPolygon:i,parallelogram:n,triangle:s,rhombus:o,arrow:a,star:l,regularPolygon:A}=r;switch(t){case"rectangle":return gh(0,e);case"parallelogram":return gh((n==null?void 0:n.angle)??30,e);case"triangle":return Ev((s==null?void 0:s.type)??"isosceles",{baseAngle:s==null?void 0:s.baseAngle,angles:s==null?void 0:s.angles,rightAnglePosition:s==null?void 0:s.rightAnglePosition});case"rhombus":return ph((o==null?void 0:o.angle)??90);case"diamond":return ph(90);case"pentagon":return zs(5);case"hexagon":return zs(6);case"octagon":return zs(8);case"star":return mv((l==null?void 0:l.points)??5,(l==null?void 0:l.innerRadius)??.4);case"arrow":return dv((a==null?void 0:a.shaftRatio)??.4,(a==null?void 0:a.headRatio)??.4);case"heart":return pv();case"circle":return fv();case"ellipse":return gv(e);case"custom-polygon":if(!(i!=null&&i.points)||i.points.length<3)throw new Error("Custom polygon must have at least 3 points");return i.points;default:return zs((A==null?void 0:A.sides)??6)}}function Bv(r,e){let t=!1;const i=r.x,n=r.y;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s].x,l=e[s].y,A=e[o].x,u=e[o].y;l>n!=u>n&&i<(A-a)*(n-l)/(u-l)+a&&(t=!t)}return t}function Tv(r,e){let t=1,i=0;const n=200;for(let s=0;s<=n;s++){const o=s/n;Bv({x:o,y:r},e)&&(t=Math.min(t,o),i=Math.max(i,o))}return i>=t?{left:t,right:i}:null}function Sv(r){const e=Math.min(...r.map(l=>l.y)),t=Math.max(...r.map(l=>l.y));let i={x:0,y:0,width:0,height:0},n=0;const s=200,o=(t-e)/s,a=[];for(let l=0;l<=s;l++){const A=e+l*o;a.push({y:A,span:Tv(A,r)})}for(let l=0;l<a.length-1;l++){const A=a[l].y;for(let u=l+1;u<a.length;u++){const h=a[u].y-A;let d=0,f=1,g=!0;const p=Math.min(5,u-l+1);for(let v=0;v<p;v++){const B=l+Math.floor(v/(p-1)*(u-l)),C=a[B].span;if(C){if(d=Math.max(d,C.left),f=Math.min(f,C.right),d>=f){g=!1;break}}else{g=!1;break}}if(g&&f>d){const v=f-d,B=v*h;B>n&&(n=B,i={x:d,y:A,width:v,height:h})}}}return i}function bv(r,e=1){const t=Cv(r,e);if(t.length<3)return{top:0,right:0,bottom:0,left:0};if(r.type==="rectangle")return{top:0,right:0,bottom:0,left:0};const i=Sv(t),n=i.y,s=i.x,o=1-(i.x+i.width),a=1-(i.y+i.height);return{top:Math.max(0,n),right:Math.max(0,o),bottom:Math.max(0,a),left:Math.max(0,s)}}function xv(r){return typeof r=="number"?{topLeft:r,topRight:r,bottomRight:r,bottomLeft:r}:{topLeft:(r==null?void 0:r.topLeft)??0,topRight:(r==null?void 0:r.topRight)??0,bottomRight:(r==null?void 0:r.bottomRight)??0,bottomLeft:(r==null?void 0:r.bottomLeft)??0}}function Qv(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:typeof r.top=="number"?r.top*e:r.top,right:typeof r.right=="number"?r.right*e:r.right,bottom:typeof r.bottom=="number"?r.bottom*e:r.bottom,left:typeof r.left=="number"?r.left*e:r.left}}function _v(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:(typeof r.top=="number"?r.top*e:r.top)??0,right:(typeof r.right=="number"?r.right*e:r.right)??0,bottom:(typeof r.bottom=="number"?r.bottom*e:r.bottom)??0,left:(typeof r.left=="number"?r.left*e:r.left)??0}}function wv(r,e){return typeof r=="number"?{top:r*e,right:r*e,bottom:r*e,left:r*e}:typeof r=="string"?{top:r,right:r,bottom:r,left:r}:{top:(typeof r.top=="number"?r.top*e:r.top)??0,right:(typeof r.right=="number"?r.right*e:r.right)??0,bottom:(typeof r.bottom=="number"?r.bottom*e:r.bottom)??0,left:(typeof r.left=="number"?r.left*e:r.left)??0}}function Rv(r){if(r===null||typeof r!="object")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function Dv(r){return r.replace(/\\/g,"\\\\").replace(/\//g,"\\/").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\f/g,"\\f").replace(/"/g,'\\"')}const Lv=Hi(()=>Au.loadYoga());function Eh(r,e,{layout:t,scale:i=1}){const{position:n="relative",inset:s,width:o,height:a,minWidth:l,minHeight:A,maxWidth:u,maxHeight:c,flex:h,flexGrow:d,flexShrink:f,gap:g,margin:p,padding:v,direction:B="column",align:C="start",alignSelf:y,justify:x="start"}=t??{},w={static:r.POSITION_TYPE_STATIC,relative:r.POSITION_TYPE_RELATIVE,absolute:r.POSITION_TYPE_ABSOLUTE};if(e.setPositionType(w[n]),typeof s<"u"){const{top:M,right:j,bottom:X,left:le}=Qv(s,i);typeof M<"u"&&e.setPosition(r.EDGE_TOP,M),typeof j<"u"&&e.setPosition(r.EDGE_RIGHT,j),typeof X<"u"&&e.setPosition(r.EDGE_BOTTOM,X),typeof le<"u"&&e.setPosition(r.EDGE_LEFT,le)}const D={row:r.FLEX_DIRECTION_ROW,column:r.FLEX_DIRECTION_COLUMN,"row-reverse":r.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":r.FLEX_DIRECTION_COLUMN_REVERSE};e.setFlexDirection(D[B]);const F={start:r.ALIGN_FLEX_START,end:r.ALIGN_FLEX_END,center:r.ALIGN_CENTER,stretch:r.ALIGN_STRETCH};e.setAlignItems(F[C]),y&&e.setAlignSelf(F[y]);const O={start:r.JUSTIFY_FLEX_START,end:r.JUSTIFY_FLEX_END,center:r.JUSTIFY_CENTER,"space-between":r.JUSTIFY_SPACE_BETWEEN,"space-around":r.JUSTIFY_SPACE_AROUND,"space-evenly":r.JUSTIFY_SPACE_EVENLY};if(e.setJustifyContent(O[x]),typeof p<"u"){const{top:M,right:j,bottom:X,left:le}=_v(p,i);e.setMargin(r.EDGE_TOP,M),e.setMargin(r.EDGE_RIGHT,j),e.setMargin(r.EDGE_BOTTOM,X),e.setMargin(r.EDGE_LEFT,le)}if(typeof v<"u"){const{top:M,right:j,bottom:X,left:le}=wv(v,i);e.setPadding(r.EDGE_TOP,M),e.setPadding(r.EDGE_RIGHT,j),e.setPadding(r.EDGE_BOTTOM,X),e.setPadding(r.EDGE_LEFT,le)}typeof d<"u"||typeof f<"u"?(typeof d<"u"&&e.setFlexGrow(d),typeof f<"u"&&e.setFlexShrink(f)):typeof h<"u"&&e.setFlex(h),e.setGap(r.GUTTER_ALL,(g??0)*i),typeof o<"u"&&e.setWidth(typeof o=="number"?o*i:o),typeof a<"u"&&e.setHeight(typeof a=="number"?a*i:a),typeof l<"u"&&e.setMinWidth(typeof l=="number"?l*i:l),typeof A<"u"&&e.setMinHeight(typeof A=="number"?A*i:A),typeof u<"u"&&e.setMaxWidth(typeof u=="number"?u*i:u),typeof c<"u"&&e.setMaxHeight(typeof c=="number"?c*i:c)}async function Ih({id:r,yoga:e,index:t,parent:i,element:n,resolvers:s}){var o,a,l;const{layout:A={},config:u={},options:c={},renderer:h}=n,d=e.Node.create();Eh(e,d,{layout:A}),i.insertChild(d,t);let f=null;s&&((h==null?void 0:h.type)==="text"||(h==null?void 0:h.type)==="caption"||(h==null?void 0:h.type)==="image"||(h==null?void 0:h.type)==="video")&&((h==null?void 0:h.type)==="caption"?f=await((o=s.text)==null?void 0:o.call(s,{id:r,config:u,options:c}))??null:f=await((a=s[h.type])==null?void 0:a.call(s,{id:r,config:u,options:c}))??null);const g=[];for await(const[p,v]of((l=n.children)==null?void 0:l.entries())??[])g.push(await Ih({id:r,yoga:e,index:p,parent:d,element:v,resolvers:s}));return{node:d,radius:xv(A.radius),element:n,renderer:h,config:u,options:c,dependencies:f,childNodes:g}}function vh(r,e,t=0,i=0){const{top:n,left:s}=r.getComputedLayout(),{top:o,left:a,width:l,height:A}=e.node.getComputedLayout(),u=t+a,c=i+o,h=e.childNodes.map(d=>vh(r,d,u,c));return{...e,x:s+u,y:n+c,width:l,height:A,childNodes:h}}async function al({yoga:r,root:e,tree:t,measureCanvas:i}){for await(const{node:n,options:s,dependencies:o,renderer:a,childNodes:l}of t){if(a){const{width:A,height:u}=a;if(A&&i){e.calculateLayout();const c=await A({node:n,options:s,dependencies:o,measureCanvas:i});c&&n.setWidth(c)}if(u&&i){e.calculateLayout();const c=await u({node:n,options:s,dependencies:o,measureCanvas:i});c&&n.setHeight(c)}if(await al({yoga:r,root:e,tree:l,measureCanvas:i}),s!=null&&s.shape){const c=n.getComputedWidth(),h=n.getComputedHeight(),d=bv(s.shape,c/h);n.setPadding(r.EDGE_TOP,d.top*h),n.setPadding(r.EDGE_RIGHT,d.right*c),n.setPadding(r.EDGE_BOTTOM,d.bottom*h),n.setPadding(r.EDGE_LEFT,d.left*c)}}e.calculateLayout(),await al({yoga:r,root:e,tree:l,measureCanvas:i})}}async function yh({id:r,root:e,resolvers:t,measureCanvas:i}){const n=await Lv(),s=n.Node.create();Eh(n,s,{layout:e.layout});const o=await Ih({id:r,yoga:n,index:0,parent:s,element:e.element,resolvers:t});await al({yoga:n,root:s,tree:[o],measureCanvas:i});const{top:a,left:l,width:A,height:u}=s.getComputedLayout(),c={root:{x:l,y:a,width:A,height:u},node:vh(s,o)};return s.freeRecursive(),c}const kv={type:"audio"},Mn=/(?<value>\d+\.?\d*)(?=px)/;function ll({words:r,spaceMetrics:e,strokeWidth:t=0}){return r.reduce((i,n,s)=>{const o=n.metrics.width+t,a=s<r.length-1?e.width:0;return i+o+a},0)}Ts(({context:r,font:e,fontSizes:t,words:i,maxW:n=1/0,strokeWidth:s=0,letterSpacing:o=0})=>{try{r.save(),r.letterSpacing=`${o}px`,r.font=e.replace(Mn,t[0].toString());const a=r.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");if(i.length<=0)return[];const l=r.measureText(i[0].text);return i.slice(1).reduce((A,u)=>{const c=A[A.length-1],h=r.measureText(u.text),d={...u,metrics:h},f=[...c.words,d],g=ll({strokeWidth:s,words:f,spaceMetrics:c.spaceMetrics});if(g>n){const p=t[A.length%t.length];r.font=e.replace(Mn,p.toString());const v=r.measureText(" "),B=r.measureText(u.text),C=[{...u,metrics:B}],y=r.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");A=[...A,{allMetrics:y,spaceMetrics:v,lineWidth:ll({strokeWidth:s,spaceMetrics:v,words:C}),font:r.font,words:C,lineHeight:y.actualBoundingBoxAscent+y.actualBoundingBoxDescent+s}]}else A[A.length-1]={...c,lineWidth:g,words:f};return A},[{allMetrics:a,lineWidth:ll({strokeWidth:s,words:[{...i[0],metrics:l}],spaceMetrics:r.measureText(" ")}),lineHeight:a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+s,font:r.font,words:[{...i[0],metrics:l}],spaceMetrics:r.measureText(" ")}])}finally{r.restore()}},{cacheKey:([{font:r,fontSizes:e,words:t,maxW:i,strokeWidth:n,letterSpacing:s}])=>`${r}_${JSON.stringify(e)}_${JSON.stringify(t)}_${i}_${n}_${s}`});function Mv(r){return r.slice(0,1).toUpperCase()+r.slice(1)}const Ch=[{family:"Noto Arabic",regex:new RegExp("\\p{Script=Arabic}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansArabic-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Chinese",regex:new RegExp("\\p{Script=Han}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansSC-VariableFont_wght.woff2",style:"normal"},{family:"Noto Hebrew",regex:new RegExp("\\p{Script=Hebrew}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansHebrew-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Hindi",regex:new RegExp("\\p{Script=Devanagari}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansDevanagari-VariableFont_wdth%2Cwght.woff2",style:"normal"},{family:"Noto Japanese",regex:new RegExp("\\p{Script=Han}|\\p{Script=Katakana}|\\p{Script=Hiragana}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansJP-VariableFont_wght.woff2",style:"normal"},{family:"Noto Korean",regex:new RegExp("\\p{Script=Hangul}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoSansKR-VariableFont_wght.woff2",style:"normal"},{family:"Noto Color Emoji",regex:new RegExp("\\p{Extended_Pictographic}","u"),url:"https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/NotoColorEmoji-Regular.woff2",style:"normal"}];function Fv({text:r,font:e}){let t=e;return Ch.forEach(({family:i,regex:n})=>{n.exec(r)&&(t+=`, ${i}`)}),t}const Pv="caption";Object.keys(dh).map(r=>({label:Mv(r),value:r,data:r}));const Nv={type:Pv},Ov={type:"image"};function Bh({context:r,word:e,maxW:t=1/0}){const i=[],n=r.measureText(e);if(Math.floor(n.width)<=t)return[{text:e,metrics:n}];for(let s=0;s<e.length;s++){const o=i[i.length-1],a=((o==null?void 0:o.text)??"")+e[s],l=r.measureText(a);l.width<t?i[o?i.length-1:0]={text:a,metrics:l}:i.push({text:e[s],metrics:r.measureText(e[s])})}return i}const Uv=Ts(({font:r,context:e,fontSizes:t,text:i,maxW:n=1/0,letterSpacing:s=0})=>{try{return e.save(),e.letterSpacing=`${s}px`,e.font=r.replace(Mn,t[0].toString()),i.split(`
2476
- `).flatMap(a=>{const l=a.split(" ").filter(Boolean);return l.length?l.slice(1).reduce((A,u,c)=>{const d=`${A[A.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)A=[...A,...Bh({context:e,word:u,maxW:n})];else{const g=t[c%t.length];e.font=r.replace(Mn,g.toString()),A[A.length-1]={text:d,metrics:f}}return A},Bh({context:e,word:l[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:r,fontSizes:e,text:t,maxW:i,letterSpacing:n}])=>`${r}_${JSON.stringify(e)}_${t}_${i}_${n}`});Ts(({font:r,text:e,scale:t,context:i,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:l=0})=>{var A,u;let c=0;if(a){c=(o??0)*t;let d=0;for(;a*t>c+1;){c+=1;const f=Uv({font:r,context:i,fontSizes:[c],text:e,maxW:n,letterSpacing:l});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*c>s){c-=1;break}}}else c=parseFloat(((u=(A=r.match(Mn))==null?void 0:A.groups)==null?void 0:u.value)??"0")*t;return c},{cacheKey:([{font:r,text:e,scale:t,maxW:i,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${r}_${e}_${s}_${o}_${t}_${i}_${n}_${a}`});const Gv={type:"text"},$v={type:"video"};function Th(){return document.createElement("canvas")}function Hv(r,e){return Object.keys(r).reduce((t,i)=>(e.includes(i)||(t[i]=r[i]),t),{})}function Vt(r){let e=0;for(const t of r)Array.isArray(t)?e+=Vt(t):e+=t;return e}function Zs(r){return r.map(({type:e,duration:t},i)=>{var n,s,o,a;if(e==="transition"){const l=((n=r[i-2])==null?void 0:n.type)==="transition"?r[i-2]:null,A=((s=r[i-1])==null?void 0:s.duration)??1/0,u=((o=r[i+1])==null?void 0:o.duration)??1/0,c=((a=r[i+2])==null?void 0:a.type)==="transition"?r[i+2]:null;return Math.min(l?A/2:A,t,c?u/2:u)*-1}return t})}function Sh(r){var e;return{...r,children:((e=r.children)==null?void 0:e.map(t=>{if(!t.renderer)return Sh(t)}).filter(Boolean))??[]}}function bh(r){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};r.renderer&&(e[r.renderer.type]+=1);for(const t of r.children??[]){const{box:i,shape:n,image:s,video:o,text:a,audio:l,gradient:A,caption:u}=bh(t);e.box+=i,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=l,e.gradient+=A,e.caption+=u}return e}function Yv(r){return r.video>0?$v.type:r.image>0?Ov.type:r.audio>0?kv.type:r.caption>0?Nv.type:Gv.type}function xh({node:r,duration:e,parentAnimations:t}){const i=[],n={...t,...r.element.animations};if(r.renderer){const s=Sh({...r.element,layout:{...r.element.layout?Hv(r.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=bh(s);i.push({type:Yv(o),id:hv(),x:r.x,y:r.y,width:r.width,height:r.height,duration:e,root:{element:s}})}for(const s of r.childNodes)i.push(...xh({node:s,duration:e,parentAnimations:n}));return i}wm.filters.define("parse",r=>typeof r>"u"?null:typeof r=="string"?`"${Dv(r)}"`:Rv(r)||Array.isArray(r)?JSON.stringify(r):r);const Vv="3";async function Kv({scene:r,start:e=0}){const{id:t,root:i,duration:n}=r,s=await yh({id:t,root:i});return{type:r.type,start:e,duration:n,layout:s,id:r.id,config:r}}async function Wv({track:r}){const e=Zs(r),t=await Promise.all(r.reduce((s,o,a)=>{if(o.type!=="audio")return s;const l=Vt(e.slice(0,a));return s.push(Kv({scene:o,start:l})),s},[])),i=r.reduce((s,o,a)=>{if(o.type!=="gap")return s;const l=Vt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:l,config:o,duration:o.duration}),s},[]),n=r.map(({id:s})=>t.find(({id:o})=>o===s)??i.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:i,mergedScenes:n,config:r,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function Qh({node:r,canvases:e,sceneTime:t,parentOpacity:i=1,parentTransform:n,debug:s=!1}){var o,a;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(n);const A=lv({layout:r.element.layout,sceneTime:t,animations:r.element.animations}),{opacity:u,translation:c,scale:h,clip:d,dimensions:f,rotation:g}=A,p=r.width*f.widthRatio,v=r.height*f.heightRatio;if(l.globalAlpha=u*i,(c.x||c.y)&&l.translate(c.x,c.y),(h!==1||g!==0)&&(l.translate(r.x+p/2,r.y+v/2),l.scale(h,h),l.rotate(g*Math.PI/180),l.translate(-(r.x+p/2),-(r.y+v/2))),d){l.beginPath();const B={x:r.x+d.x*p,y:r.y+d.y*v,width:d.width*p,height:d.height*v};l.rect(B.x,B.y,B.width,B.height),l.clip()}if(s){const B=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(r.x,r.y,p,v),l.globalAlpha=B}await((a=(o=r.renderer)==null?void 0:o.render)==null?void 0:a.call(o,{canvases:e,sceneTime:t,dx:r.x,dy:r.y,dw:p,dh:v,radius:r.radius,options:r.options,dependencies:r.dependencies}));for await(const B of r.childNodes)await Qh({debug:s,node:B,canvases:e,sceneTime:t,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function qv({layout:r,canvases:e,sceneTime:t,debug:i=!1}){const{node:n}=r;await Qh({debug:i,node:n,canvases:e,sceneTime:t})}async function eo({debug:r=!1,scene:e,start:t=0,resolvers:i,rootWidth:n,rootHeight:s,canvasFactory:o=Th}){var a,l;const{id:A,x:u,y:c,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await yh({id:A,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof c=="number"?{position:"absolute",inset:{top:c,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((l=f.element.layout)==null?void 0:l.height)}}},resolvers:i,measureCanvas:y}),w=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await qv({debug:r,layout:x,sceneTime:F,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:A,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:w,config:e,childScenes:xh({node:x.node,duration:g})}}async function Jv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="caption"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function jv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="video"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),h.type==="image"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(0,...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function Xv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="text"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"text",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}function zv(r){return r.some(({type:e})=>e==="text")}function Zv(r){return r.some(({type:e})=>e==="caption")}function ey(r){return r.some(({type:e})=>e==="audio")}function ty(r){return r.some(({type:e})=>e==="video"||e==="image")}function iy(r){return r.type==="audio"}const ry=(((hh=uh)==null?void 0:hh.default)??uh).reduce((r,e)=>(r[e.name]=e,r),{});function ny(r,e){return r.has(e)||r.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),r.get(e)}function sy({name:r,to:e,from:t,progress:i,width:n,height:s,glContext:o,contextResources:a,returnPixels:l=!0}){var A,u,c;const h=ny(a,o);if(o.disable(o.DEPTH_TEST),h.buffer?o.bindBuffer(o.ARRAY_BUFFER,h.buffer):(h.buffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,h.buffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,-1,4,4,-1]),o.STATIC_DRAW)),o.viewport(0,0,n,s),h.fromTexture?h.fromTexture.setPixels(t):(h.fromTexture=(((A=Ks)==null?void 0:A.default)??Ks)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=Ks)==null?void 0:u.default)??Ks)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[r]||(h.transitions[r]=(((c=ch)==null?void 0:c.default)??ch)(o,ry[r])),h.transitions[r].draw(i,h.fromTexture,h.toTexture,n,s),!l)return o.flush(),new Uint8Array(0);const f=new Uint8Array(n*s*4);return o.readPixels(0,0,n,s,o.RGBA,o.UNSIGNED_BYTE,f),o.flush(),f}function oy(r){for(const[e,t]of r.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(i=>{i.dispose()}),r.delete(e)}function ay({name:r,to:e,from:t,progress:i,canvas:n,contextResources:s}){const o=n.getContext("webgl",{alpha:!0,depth:!1,antialias:!1,preserveDrawingBuffer:!1});o&&(o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!0),sy({name:r,to:e,from:t,progress:i,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function _h({debug:r=!1,config:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s=Th,drawTransition:o=ay}){const a=new Map,l=await Promise.all(e.tracks.map(async c=>{if(ty(c))return{...await jv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(zv(c))return{...await Xv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(Zv(c))return{...await Jv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ey(c))return{...await Wv({track:c}),config:c};throw new Error("Unknown track type")}));return{draw:async({canvas:c,currentTime:h})=>{const d=c.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,c.width,c.height),d.save(),d.fillStyle="black",d.fillRect(0,0,c.width,c.height),d.restore();for await(const f of l){if(iy(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=c.width,v.height=c.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:w})=>h>=x&&h<x+w);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:w})=>h>=x&&h<x+w);for await(const{sceneCanvas:x,draw:w}of C)await(w==null?void 0:w(h)),(!y||y&&(!y.to||!y.from))&&B.drawImage(x,0,0,x.width,x.height);if(y&&y.to&&y.from&&y.duration>0){const{name:x,to:w,from:D,duration:F,transitionCanvas:O}=y;O.width=O.height=0,O.width=v.width,O.height=v.height;const M=Math.min(1,Math.max(0,(h-w.start)/F));await o({name:x,progress:M,contextResources:a,to:w.sceneCanvas,from:D.sceneCanvas,canvas:O}),B.globalCompositeOperation="lighter",B.drawImage(O,0,0,O.width,O.height)}d.drawImage(v,0,0,v.width,v.height)}}},cleanup:()=>{oy(a)},tracks:l,aspectRatio:e.aspectRatio,duration:Math.max(...l.map(({duration:c})=>c))}}const ly={version:"6.0.0"};function Ay(r){const{publicApiUrl:e}=Bs(r),t=hr();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function cy(r){var s,o,a,l,A,u,c,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:hr()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(l=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:l.call(a,"vouch-uid-client"),i=(u=(A=window.sessionStorage)==null?void 0:A.getItem)==null?void 0:u.call(A,"vouch-uid-tab");const n=hr();return e||(e=Ay(r),(h=(c=window.localStorage)==null?void 0:c.setItem)==null||h.call(c,"vouch-uid-visitor",e)),t||(t=hr(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),i||(i=hr(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",i)),{client:t,tab:i,request:n,visitor:e}}function uy(r,e){return r&&"vouchId"in r?r.vouchId:(e==null?void 0:e.id)??null}function hy(r="embedded_player"){var n,s;const[e,t]=((s=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:s.call(n,"/"))??[],i={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const l=o.toLowerCase().replace(/[-_][a-z0-9]/g,A=>A.slice(-1).toUpperCase());i[l]=a}}),{source:r,time:new Date,region:t,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,embedType:"media-player-embed",embedVersion:ly.version,templateVersion:Vv,...i}}const wh=1;class dy{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,i)=>{const n=uy(i,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...i,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=Bs(this.host.env),{client:i,tab:n,request:s,visitor:o}=cy(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":i,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":hy(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:i}=this._currentlyPlayingVideo;this._streamLatestTime[i]>this._streamStartTime[i]+wh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]}},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._createTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{this._hasPlayed||(this._createTrackingEvent("VIDEO_PLAYED",{streamStart:this.host.currentTime}),this._hasPlayed=!0)},this._handleVideoPlay=({detail:{id:t,key:i}})=>{this._answersViewed[i]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[i]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:i,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:i,node:n},this._streamLatestTime[i]=n.currentTime,this._streamStartTime[i]||(this._streamStartTime[i]=n.currentTime,this._streamLatestTime[i]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:i}})=>{this._streamLatestTime[i]>this._streamStartTime[i]+wh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]},this._pageUnloading=()=>{this._streamEnded(),this._sendTrackingEvent()},this._handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this._pageUnloading()},this._handlePageHide=()=>{this._pageUnloading()},this.host=e,e.addController(this)}hostConnected(){requestAnimationFrame(()=>{var e,t,i,n;"onvisibilitychange"in document?document.addEventListener("visibilitychange",this._handleVisibilityChange):window.addEventListener("pagehide",this._handlePageHide),this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,n;this._pageUnloading(),"onvisibilitychange"in document?document.removeEventListener("visibilitychange",this._handleVisibilityChange):window.removeEventListener("pagehide",this._handlePageHide),this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var Al={exports:{}};(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof $i<"u"&&$i,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof $i<"u"&&$i||{},l={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function A(L){return L&&DataView.prototype.isPrototypeOf(L)}if(l.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(L){return L&&u.indexOf(Object.prototype.toString.call(L))>-1};function h(L){if(typeof L!="string"&&(L=String(L)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(L)||L==="")throw new TypeError('Invalid character in header field name: "'+L+'"');return L.toLowerCase()}function d(L){return typeof L!="string"&&(L=String(L)),L}function f(L){var U={next:function(){var q=L.shift();return{done:q===void 0,value:q}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function g(L){this.map={},L instanceof g?L.forEach(function(U,q){this.append(q,U)},this):Array.isArray(L)?L.forEach(function(U){if(U.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+U.length);this.append(U[0],U[1])},this):L&&Object.getOwnPropertyNames(L).forEach(function(U){this.append(U,L[U])},this)}g.prototype.append=function(L,U){L=h(L),U=d(U);var q=this.map[L];this.map[L]=q?q+", "+U:U},g.prototype.delete=function(L){delete this.map[h(L)]},g.prototype.get=function(L){return L=h(L),this.has(L)?this.map[L]:null},g.prototype.has=function(L){return this.map.hasOwnProperty(h(L))},g.prototype.set=function(L,U){this.map[h(L)]=d(U)},g.prototype.forEach=function(L,U){for(var q in this.map)this.map.hasOwnProperty(q)&&L.call(U,this.map[q],q,this)},g.prototype.keys=function(){var L=[];return this.forEach(function(U,q){L.push(q)}),f(L)},g.prototype.values=function(){var L=[];return this.forEach(function(U){L.push(U)}),f(L)},g.prototype.entries=function(){var L=[];return this.forEach(function(U,q){L.push([q,U])}),f(L)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function p(L){if(!L._noBody){if(L.bodyUsed)return Promise.reject(new TypeError("Already read"));L.bodyUsed=!0}}function v(L){return new Promise(function(U,q){L.onload=function(){U(L.result)},L.onerror=function(){q(L.error)}})}function B(L){var U=new FileReader,q=v(U);return U.readAsArrayBuffer(L),q}function C(L){var U=new FileReader,q=v(U),R=/charset=([A-Za-z0-9_-]+)/.exec(L.type),_=R?R[1]:"utf-8";return U.readAsText(L,_),q}function y(L){for(var U=new Uint8Array(L),q=new Array(U.length),R=0;R<U.length;R++)q[R]=String.fromCharCode(U[R]);return q.join("")}function x(L){if(L.slice)return L.slice(0);var U=new Uint8Array(L.byteLength);return U.set(new Uint8Array(L)),U.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:l.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:l.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():l.arrayBuffer&&l.blob&&A(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||c(L))?this._bodyArrayBuffer=x(L):this._bodyText=L=Object.prototype.toString.call(L):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof L=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var L=p(this);return L||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(l.blob)return this.blob().then(B);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(L){var U=L.toUpperCase();return D.indexOf(U)>-1?U:L}function O(L,U){if(!(this instanceof O))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');U=U||{};var q=U.body;if(L instanceof O){if(L.bodyUsed)throw new TypeError("Already read");this.url=L.url,this.credentials=L.credentials,U.headers||(this.headers=new g(L.headers)),this.method=L.method,this.mode=L.mode,this.signal=L.signal,!q&&L._bodyInit!=null&&(q=L._bodyInit,L.bodyUsed=!0)}else this.url=String(L);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new g(U.headers)),this.method=F(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&q)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(q),(this.method==="GET"||this.method==="HEAD")&&(U.cache==="no-store"||U.cache==="no-cache")){var R=/([?&])_=[^&]*/;if(R.test(this.url))this.url=this.url.replace(R,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}O.prototype.clone=function(){return new O(this,{body:this._bodyInit})};function M(L){var U=new FormData;return L.trim().split("&").forEach(function(q){if(q){var R=q.split("="),_=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(_),decodeURIComponent(k))}}),U}function j(L){var U=new g,q=L.replace(/\r?\n[\t ]+/g," ");return q.split("\r").map(function(R){return R.indexOf(`
2476
+ `).flatMap(a=>{const l=a.split(" ").filter(Boolean);return l.length?l.slice(1).reduce((A,u,c)=>{const d=`${A[A.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)A=[...A,...Bh({context:e,word:u,maxW:n})];else{const g=t[c%t.length];e.font=r.replace(Mn,g.toString()),A[A.length-1]={text:d,metrics:f}}return A},Bh({context:e,word:l[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:r,fontSizes:e,text:t,maxW:i,letterSpacing:n}])=>`${r}_${JSON.stringify(e)}_${t}_${i}_${n}`});Ts(({font:r,text:e,scale:t,context:i,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:l=0})=>{var A,u;let c=0;if(a){c=(o??0)*t;let d=0;for(;a*t>c+1;){c+=1;const f=Uv({font:r,context:i,fontSizes:[c],text:e,maxW:n,letterSpacing:l});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*c>s){c-=1;break}}}else c=parseFloat(((u=(A=r.match(Mn))==null?void 0:A.groups)==null?void 0:u.value)??"0")*t;return c},{cacheKey:([{font:r,text:e,scale:t,maxW:i,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${r}_${e}_${s}_${o}_${t}_${i}_${n}_${a}`});const Gv={type:"text"},$v={type:"video"};function Th(){return document.createElement("canvas")}function Hv(r,e){return Object.keys(r).reduce((t,i)=>(e.includes(i)||(t[i]=r[i]),t),{})}function Vt(r){let e=0;for(const t of r)Array.isArray(t)?e+=Vt(t):e+=t;return e}function Zs(r){return r.map(({type:e,duration:t},i)=>{var n,s,o,a;if(e==="transition"){const l=((n=r[i-2])==null?void 0:n.type)==="transition"?r[i-2]:null,A=((s=r[i-1])==null?void 0:s.duration)??1/0,u=((o=r[i+1])==null?void 0:o.duration)??1/0,c=((a=r[i+2])==null?void 0:a.type)==="transition"?r[i+2]:null;return Math.min(l?A/2:A,t,c?u/2:u)*-1}return t})}function Sh(r){var e;return{...r,children:((e=r.children)==null?void 0:e.map(t=>{if(!t.renderer)return Sh(t)}).filter(Boolean))??[]}}function bh(r){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};r.renderer&&(e[r.renderer.type]+=1);for(const t of r.children??[]){const{box:i,shape:n,image:s,video:o,text:a,audio:l,gradient:A,caption:u}=bh(t);e.box+=i,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=l,e.gradient+=A,e.caption+=u}return e}function Yv(r){return r.video>0?$v.type:r.image>0?Ov.type:r.audio>0?kv.type:r.caption>0?Nv.type:Gv.type}function xh({node:r,duration:e,parentAnimations:t}){const i=[],n={...t,...r.element.animations};if(r.renderer){const s=Sh({...r.element,layout:{...r.element.layout?Hv(r.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=bh(s);i.push({type:Yv(o),id:hv(),x:r.x,y:r.y,width:r.width,height:r.height,duration:e,root:{element:s}})}for(const s of r.childNodes)i.push(...xh({node:s,duration:e,parentAnimations:n}));return i}wm.filters.define("parse",r=>typeof r>"u"?null:typeof r=="string"?`"${Dv(r)}"`:Rv(r)||Array.isArray(r)?JSON.stringify(r):r);const Vv="3";async function Kv({scene:r,start:e=0}){const{id:t,root:i,duration:n}=r,s=await yh({id:t,root:i});return{type:r.type,start:e,duration:n,layout:s,id:r.id,config:r}}async function Wv({track:r}){const e=Zs(r),t=await Promise.all(r.reduce((s,o,a)=>{if(o.type!=="audio")return s;const l=Vt(e.slice(0,a));return s.push(Kv({scene:o,start:l})),s},[])),i=r.reduce((s,o,a)=>{if(o.type!=="gap")return s;const l=Vt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:l,config:o,duration:o.duration}),s},[]),n=r.map(({id:s})=>t.find(({id:o})=>o===s)??i.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:i,mergedScenes:n,config:r,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function Qh({node:r,canvases:e,sceneTime:t,parentOpacity:i=1,parentTransform:n,debug:s=!1}){var o,a;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(n);const A=lv({layout:r.element.layout,sceneTime:t,animations:r.element.animations}),{opacity:u,translation:c,scale:h,clip:d,dimensions:f,rotation:g}=A,p=r.width*f.widthRatio,v=r.height*f.heightRatio;if(l.globalAlpha=u*i,(c.x||c.y)&&l.translate(c.x,c.y),(h!==1||g!==0)&&(l.translate(r.x+p/2,r.y+v/2),l.scale(h,h),l.rotate(g*Math.PI/180),l.translate(-(r.x+p/2),-(r.y+v/2))),d){l.beginPath();const B={x:r.x+d.x*p,y:r.y+d.y*v,width:d.width*p,height:d.height*v};l.rect(B.x,B.y,B.width,B.height),l.clip()}if(s){const B=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(r.x,r.y,p,v),l.globalAlpha=B}await((a=(o=r.renderer)==null?void 0:o.render)==null?void 0:a.call(o,{canvases:e,sceneTime:t,dx:r.x,dy:r.y,dw:p,dh:v,radius:r.radius,options:r.options,dependencies:r.dependencies}));for await(const B of r.childNodes)await Qh({debug:s,node:B,canvases:e,sceneTime:t,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function qv({layout:r,canvases:e,sceneTime:t,debug:i=!1}){const{node:n}=r;await Qh({debug:i,node:n,canvases:e,sceneTime:t})}async function eo({debug:r=!1,scene:e,start:t=0,resolvers:i,rootWidth:n,rootHeight:s,canvasFactory:o=Th}){var a,l;const{id:A,x:u,y:c,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await yh({id:A,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof c=="number"?{position:"absolute",inset:{top:c,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((l=f.element.layout)==null?void 0:l.height)}}},resolvers:i,measureCanvas:y}),w=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await qv({debug:r,layout:x,sceneTime:F,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:A,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:w,config:e,childScenes:xh({node:x.node,duration:g})}}async function Jv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="caption"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function jv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="video"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),h.type==="image"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(0,...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}async function Xv({debug:r=!1,track:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}){const o=Zs(e),a=await Promise.all(e.reduce((c,h,d)=>{const f=Vt(o.slice(0,d));return h.type==="text"&&c.push(eo({debug:r,scene:h,start:f,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s})),c},[])),l=e.reduce((c,h,d)=>{if(h.type!=="gap")return c;const f=Vt(o.slice(0,d));return c.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),c},[]),A=e.reduce((c,h,d)=>{if(h.type!=="transition")return c;const f=h.duration,g=Vt(o.slice(0,d))-f;return c.push({type:h.type,id:h.id,name:h.name,start:g,duration:f,config:h,transitionCanvas:s(),to:a.find(({id:p})=>{var v;return p===((v=e[d+1])==null?void 0:v.id)}),from:a.find(({id:p})=>{var v;return p===((v=e[d-1])==null?void 0:v.id)})}),c},[]),u=e.map(({id:c})=>a.find(({id:h})=>h===c)??l.find(({id:h})=>h===c)??A.find(({id:h})=>h===c)).filter(Boolean);return{type:"text",scenes:a,gapScenes:l,transitions:A,mergedScenes:u,duration:Math.max(...u.map(({start:c,duration:h})=>c+h)),trackCanvas:s()}}function zv(r){return r.some(({type:e})=>e==="text")}function Zv(r){return r.some(({type:e})=>e==="caption")}function ey(r){return r.some(({type:e})=>e==="audio")}function ty(r){return r.some(({type:e})=>e==="video"||e==="image")}function iy(r){return r.type==="audio"}const ry=(((hh=uh)==null?void 0:hh.default)??uh).reduce((r,e)=>(r[e.name]=e,r),{});function ny(r,e){return r.has(e)||r.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),r.get(e)}function sy({name:r,to:e,from:t,progress:i,width:n,height:s,glContext:o,contextResources:a,returnPixels:l=!0}){var A,u,c;const h=ny(a,o);if(o.disable(o.DEPTH_TEST),h.buffer?o.bindBuffer(o.ARRAY_BUFFER,h.buffer):(h.buffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,h.buffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,-1,4,4,-1]),o.STATIC_DRAW)),o.viewport(0,0,n,s),h.fromTexture?h.fromTexture.setPixels(t):(h.fromTexture=(((A=Ks)==null?void 0:A.default)??Ks)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=Ks)==null?void 0:u.default)??Ks)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[r]||(h.transitions[r]=(((c=ch)==null?void 0:c.default)??ch)(o,ry[r])),h.transitions[r].draw(i,h.fromTexture,h.toTexture,n,s),!l)return o.flush(),new Uint8Array(0);const f=new Uint8Array(n*s*4);return o.readPixels(0,0,n,s,o.RGBA,o.UNSIGNED_BYTE,f),o.flush(),f}function oy(r){for(const[e,t]of r.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(i=>{i.dispose()}),r.delete(e)}function ay({name:r,to:e,from:t,progress:i,canvas:n,contextResources:s}){const o=n.getContext("webgl",{alpha:!0,depth:!1,antialias:!1,preserveDrawingBuffer:!1});o&&(o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!0),sy({name:r,to:e,from:t,progress:i,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function _h({debug:r=!1,config:e,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s=Th,drawTransition:o=ay}){const a=new Map,l=await Promise.all(e.tracks.map(async c=>{if(ty(c))return{...await jv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(zv(c))return{...await Xv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(Zv(c))return{...await Jv({debug:r,track:c,resolvers:t,rootWidth:i,rootHeight:n,canvasFactory:s}),config:c};if(ey(c))return{...await Wv({track:c}),config:c};throw new Error("Unknown track type")}));return{draw:async({canvas:c,currentTime:h})=>{const d=c.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,c.width,c.height),d.save(),d.fillStyle="black",d.fillRect(0,0,c.width,c.height),d.restore();for await(const f of l){if(iy(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=c.width,v.height=c.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:w})=>h>=x&&h<x+w);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:w})=>h>=x&&h<x+w);for await(const{sceneCanvas:x,draw:w}of C)await(w==null?void 0:w(h)),(!y||y&&(!y.to||!y.from))&&B.drawImage(x,0,0,x.width,x.height);if(y&&y.to&&y.from&&y.duration>0){const{name:x,to:w,from:D,duration:F,transitionCanvas:O}=y;O.width=O.height=0,O.width=v.width,O.height=v.height;const M=Math.min(1,Math.max(0,(h-w.start)/F));await o({name:x,progress:M,contextResources:a,to:w.sceneCanvas,from:D.sceneCanvas,canvas:O}),B.globalCompositeOperation="lighter",B.drawImage(O,0,0,O.width,O.height)}d.drawImage(v,0,0,v.width,v.height)}}},cleanup:()=>{oy(a)},tracks:l,aspectRatio:e.aspectRatio,duration:Math.max(...l.map(({duration:c})=>c))}}const ly={version:"6.1.1"};function Ay(r){const{publicApiUrl:e}=Bs(r),t=hr();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function cy(r){var s,o,a,l,A,u,c,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:hr()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(l=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:l.call(a,"vouch-uid-client"),i=(u=(A=window.sessionStorage)==null?void 0:A.getItem)==null?void 0:u.call(A,"vouch-uid-tab");const n=hr();return e||(e=Ay(r),(h=(c=window.localStorage)==null?void 0:c.setItem)==null||h.call(c,"vouch-uid-visitor",e)),t||(t=hr(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),i||(i=hr(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",i)),{client:t,tab:i,request:n,visitor:e}}function uy(r,e){return r&&"vouchId"in r?r.vouchId:(e==null?void 0:e.id)??null}function hy(r="embedded_player"){var n,s;const[e,t]=((s=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:s.call(n,"/"))??[],i={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const l=o.toLowerCase().replace(/[-_][a-z0-9]/g,A=>A.slice(-1).toUpperCase());i[l]=a}}),{source:r,time:new Date,region:t,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,embedType:"media-player-embed",embedVersion:ly.version,templateVersion:Vv,...i}}const wh=1;class dy{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,i)=>{const n=uy(i,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...i,senderId:this.host.senderId,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=Bs(this.host.env),{client:i,tab:n,request:s,visitor:o}=cy(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":i,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":hy(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:i}=this._currentlyPlayingVideo;this._streamLatestTime[i]>this._streamStartTime[i]+wh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]}},this._handleVouchLoaded=({detail:t})=>{t&&(this._hasLoaded[t]||(this._createTrackingEvent("VOUCH_LOADED",{vouchId:t}),this._hasLoaded[t]=!0))},this._handlePlay=()=>{this._hasPlayed||(this._createTrackingEvent("VIDEO_PLAYED",{streamStart:this.host.currentTime}),this._hasPlayed=!0)},this._handleVideoPlay=({detail:{id:t,key:i}})=>{this._answersViewed[i]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[i]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:i,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:i,node:n},this._streamLatestTime[i]=n.currentTime,this._streamStartTime[i]||(this._streamStartTime[i]=n.currentTime,this._streamLatestTime[i]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:i}})=>{this._streamLatestTime[i]>this._streamStartTime[i]+wh&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[i],streamEnd:this._streamLatestTime[i]}),delete this._streamStartTime[i],delete this._streamLatestTime[i]},this._pageUnloading=()=>{this._streamEnded(),this._sendTrackingEvent()},this._handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this._pageUnloading()},this._handlePageHide=()=>{this._pageUnloading()},this.host=e,e.addController(this)}hostConnected(){requestAnimationFrame(()=>{var e,t,i,n;"onvisibilitychange"in document?document.addEventListener("visibilitychange",this._handleVisibilityChange):window.addEventListener("pagehide",this._handlePageHide),this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.addEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,i,n;this._pageUnloading(),"onvisibilitychange"in document?document.removeEventListener("visibilitychange",this._handleVisibilityChange):window.removeEventListener("pagehide",this._handlePageHide),this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(e=this.host.mediaPlayer)==null||e.removeEventListener("play",this._handlePlay),(t=this.host.mediaPlayer)==null||t.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var Al={exports:{}};(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof $i<"u"&&$i,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof $i<"u"&&$i||{},l={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function A(L){return L&&DataView.prototype.isPrototypeOf(L)}if(l.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(L){return L&&u.indexOf(Object.prototype.toString.call(L))>-1};function h(L){if(typeof L!="string"&&(L=String(L)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(L)||L==="")throw new TypeError('Invalid character in header field name: "'+L+'"');return L.toLowerCase()}function d(L){return typeof L!="string"&&(L=String(L)),L}function f(L){var U={next:function(){var q=L.shift();return{done:q===void 0,value:q}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function g(L){this.map={},L instanceof g?L.forEach(function(U,q){this.append(q,U)},this):Array.isArray(L)?L.forEach(function(U){if(U.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+U.length);this.append(U[0],U[1])},this):L&&Object.getOwnPropertyNames(L).forEach(function(U){this.append(U,L[U])},this)}g.prototype.append=function(L,U){L=h(L),U=d(U);var q=this.map[L];this.map[L]=q?q+", "+U:U},g.prototype.delete=function(L){delete this.map[h(L)]},g.prototype.get=function(L){return L=h(L),this.has(L)?this.map[L]:null},g.prototype.has=function(L){return this.map.hasOwnProperty(h(L))},g.prototype.set=function(L,U){this.map[h(L)]=d(U)},g.prototype.forEach=function(L,U){for(var q in this.map)this.map.hasOwnProperty(q)&&L.call(U,this.map[q],q,this)},g.prototype.keys=function(){var L=[];return this.forEach(function(U,q){L.push(q)}),f(L)},g.prototype.values=function(){var L=[];return this.forEach(function(U){L.push(U)}),f(L)},g.prototype.entries=function(){var L=[];return this.forEach(function(U,q){L.push([q,U])}),f(L)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function p(L){if(!L._noBody){if(L.bodyUsed)return Promise.reject(new TypeError("Already read"));L.bodyUsed=!0}}function v(L){return new Promise(function(U,q){L.onload=function(){U(L.result)},L.onerror=function(){q(L.error)}})}function B(L){var U=new FileReader,q=v(U);return U.readAsArrayBuffer(L),q}function C(L){var U=new FileReader,q=v(U),R=/charset=([A-Za-z0-9_-]+)/.exec(L.type),_=R?R[1]:"utf-8";return U.readAsText(L,_),q}function y(L){for(var U=new Uint8Array(L),q=new Array(U.length),R=0;R<U.length;R++)q[R]=String.fromCharCode(U[R]);return q.join("")}function x(L){if(L.slice)return L.slice(0);var U=new Uint8Array(L.byteLength);return U.set(new Uint8Array(L)),U.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:l.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:l.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():l.arrayBuffer&&l.blob&&A(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||c(L))?this._bodyArrayBuffer=x(L):this._bodyText=L=Object.prototype.toString.call(L):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof L=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var L=p(this);return L||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(l.blob)return this.blob().then(B);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var L=p(this);if(L)return L;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(L){var U=L.toUpperCase();return D.indexOf(U)>-1?U:L}function O(L,U){if(!(this instanceof O))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');U=U||{};var q=U.body;if(L instanceof O){if(L.bodyUsed)throw new TypeError("Already read");this.url=L.url,this.credentials=L.credentials,U.headers||(this.headers=new g(L.headers)),this.method=L.method,this.mode=L.mode,this.signal=L.signal,!q&&L._bodyInit!=null&&(q=L._bodyInit,L.bodyUsed=!0)}else this.url=String(L);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new g(U.headers)),this.method=F(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal||function(){if("AbortController"in a){var k=new AbortController;return k.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&q)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(q),(this.method==="GET"||this.method==="HEAD")&&(U.cache==="no-store"||U.cache==="no-cache")){var R=/([?&])_=[^&]*/;if(R.test(this.url))this.url=this.url.replace(R,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}O.prototype.clone=function(){return new O(this,{body:this._bodyInit})};function M(L){var U=new FormData;return L.trim().split("&").forEach(function(q){if(q){var R=q.split("="),_=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(_),decodeURIComponent(k))}}),U}function j(L){var U=new g,q=L.replace(/\r?\n[\t ]+/g," ");return q.split("\r").map(function(R){return R.indexOf(`
2477
2477
  `)===0?R.substr(1,R.length):R}).forEach(function(R){var _=R.split(":"),k=_.shift().trim();if(k){var K=_.join(":").trim();try{U.append(k,K)}catch(Y){console.warn("Response "+Y.message)}}}),U}w.call(O.prototype);function X(L,U){if(!(this instanceof X))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=U.statusText===void 0?"":""+U.statusText,this.headers=new g(U.headers),this.url=U.url||"",this._initBody(L)}w.call(X.prototype),X.prototype.clone=function(){return new X(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},X.error=function(){var L=new X(null,{status:200,statusText:""});return L.ok=!1,L.status=0,L.type="error",L};var le=[301,302,303,307,308];X.redirect=function(L,U){if(le.indexOf(U)===-1)throw new RangeError("Invalid status code");return new X(null,{status:U,headers:{location:L}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(U,q){this.message=U,this.name=q;var R=Error(U);this.stack=R.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function oe(L,U){return new Promise(function(q,R){var _=new O(L,U);if(_.signal&&_.signal.aborted)return R(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function K(){k.abort()}k.onload=function(){var ie={statusText:k.statusText,headers:j(k.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(k.status<200||k.status>599)?ie.status=200:ie.status=k.status,ie.url="responseURL"in k?k.responseURL:ie.headers.get("X-Request-URL");var he="response"in k?k.response:k.responseText;setTimeout(function(){q(new X(he,ie))},0)},k.onerror=function(){setTimeout(function(){R(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){R(new TypeError("Network request timed out"))},0)},k.onabort=function(){setTimeout(function(){R(new o.DOMException("Aborted","AbortError"))},0)};function Y(ie){try{return ie===""&&a.location.href?a.location.href:ie}catch{return ie}}if(k.open(_.method,Y(_.url),!0),_.credentials==="include"?k.withCredentials=!0:_.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(l.blob?k.responseType="blob":l.arrayBuffer&&(k.responseType="arraybuffer")),U&&typeof U.headers=="object"&&!(U.headers instanceof g||a.Headers&&U.headers instanceof a.Headers)){var te=[];Object.getOwnPropertyNames(U.headers).forEach(function(ie){te.push(h(ie)),k.setRequestHeader(ie,d(U.headers[ie]))}),_.headers.forEach(function(ie,he){te.indexOf(he)===-1&&k.setRequestHeader(he,ie)})}else _.headers.forEach(function(ie,he){k.setRequestHeader(he,ie)});_.signal&&(_.signal.addEventListener("abort",K),k.onreadystatechange=function(){k.readyState===4&&_.signal.removeEventListener("abort",K)}),k.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return oe.polyfill=!0,a.fetch||(a.fetch=oe,a.Headers=g,a.Request=O,a.Response=X),o.Headers=g,o.Request=O,o.Response=X,o.fetch=oe,o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=t.fetch?t:i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,r.exports=e})(Al,Al.exports);var fy=Al.exports;const Rh=_a(fy);async function gy(r){var e;try{if((e=await Rh(r,{method:"HEAD"}))!=null&&e.ok)return r}catch{return}}async function cl({sources:r}){let e=null;const t=r==null?void 0:r.filter(Boolean),i=t==null?void 0:t.find(s=>s.startsWith("blob:")),n=t==null?void 0:t.find(s=>!s.startsWith("http")&&!s.startsWith("blob:"));if(i||n)return i??n;if(t.length>0){const s=t.map(o=>gy(o));e=(await Promise.all(s)).find(Boolean)}return e}async function py(r){try{return(await Rh(r)).text()}catch{return null}}async function my(r){return r=r.trim(),r.startsWith("http")||r.startsWith("blob:")?py(r):r}const Ey=Hi(async({original:r,translation:e,originalLanguage:t="",translationLanguage:i=""},{language:n})=>{var s,o;const a={[(s=i==null?void 0:i.split("-"))==null?void 0:s[0]]:e,[(o=t==null?void 0:t.split("-"))==null?void 0:o[0]]:r},l=(n&&a[n])??r;return l?my(l):null},{cacheKey:([r,{language:e}])=>JSON.stringify({...r,language:e})});function Iy(r){var e;return((e=r==null?void 0:r.items)==null?void 0:e.map(t=>{var i;return{text:(i=t.alternatives[0])==null?void 0:i.content,start:t.start_time,end:t.end_time}}))??[]}const vy=Hi(async r=>{var e,t,i,n,s,o,a,l,A,u,c;const[h,d,f]=await Promise.all([cl({sources:[(t=(e=r==null?void 0:r.answer)==null?void 0:e.media)==null?void 0:t.video,(n=(i=r==null?void 0:r.answer)==null?void 0:i.media)==null?void 0:n.input]}),cl({sources:[(o=(s=r==null?void 0:r.answer)==null?void 0:s.media)==null?void 0:o.playlist]}),cl({sources:[((l=(a=r==null?void 0:r.answer)==null?void 0:a.media)==null?void 0:l.reducedQuality)??((c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.media)==null?void 0:u.videos)==null?void 0:c.xs)]})]);return{src:h,playlist:d,preview:f}},{cacheKey:([r])=>{var e,t,i,n,s,o,a,l,A,u,c;return JSON.stringify({video:(t=(e=r==null?void 0:r.answer)==null?void 0:e.media)==null?void 0:t.video,input:(n=(i=r==null?void 0:r.answer)==null?void 0:i.media)==null?void 0:n.input,playlist:(o=(s=r==null?void 0:r.answer)==null?void 0:s.media)==null?void 0:o.playlist,preview:((l=(a=r==null?void 0:r.answer)==null?void 0:a.media)==null?void 0:l.reducedQuality)??((c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.media)==null?void 0:u.videos)==null?void 0:c.xs)})}});function Dh(r){var e,t,i,n,s,o,a,l,A,u,c,h;const d=((t=(e=r==null?void 0:r.answer)==null?void 0:e.contact)==null?void 0:t.name)==="Anonymous"?"":((s=(n=(i=r==null?void 0:r.answer)==null?void 0:i.contact)==null?void 0:n.name)==null?void 0:s.trim())??"",f=((l=(a=(o=r==null?void 0:r.answer)==null?void 0:o.contact)==null?void 0:a.client)==null?void 0:l.name)==="Not Supplied"?"":((h=(c=(u=(A=r==null?void 0:r.answer)==null?void 0:A.contact)==null?void 0:u.client)==null?void 0:c.name)==null?void 0:h.trim())??"",[g,p]=d.split(" ");return{name:d,firstName:g,lastName:p,companyName:f}}function yy(r){var e,t;const i=(t=(e=r==null?void 0:r.answer)==null?void 0:e.contact)==null?void 0:t.roleTitle,n=i==null?void 0:i.split(" ");return{roleTitle:i,roleWords:n,firstRoleWord:n==null?void 0:n[0],remainingRoleWords:n==null?void 0:n.slice(1).join(" ")}}const Cy=Hi(async(r,e,t)=>{var i,n,s;const o=(i=e==null?void 0:e.answer)==null?void 0:i.id;return((s=(n=r==null?void 0:r.questions)==null?void 0:n.items)==null?void 0:s.reduce((l,A)=>{var u;return((u=A==null?void 0:A.answer)==null?void 0:u.id)===o?(l??0)+1:l},0))<=1?o:`${o}-${t}`},{cacheKey:([r,e,t])=>{var i;return JSON.stringify({index:t,rootData:e,allQuestions:(i=r==null?void 0:r.questions)==null?void 0:i.items})}});async function ul({data:r,rootData:e,index:t},i){var n,s,o,a,l,A,u,c,h,d,f,g,p,v,B,C,y,x,w,D,F,O,M,j;const[X,le,oe]=await Promise.all([Cy(r,e,t),vy(e),Ey({original:((s=(n=e==null?void 0:e.answer)==null?void 0:n.media)==null?void 0:s.captions)??((a=(o=e==null?void 0:e.answer)==null?void 0:o.captions)==null?void 0:a.current),translation:((A=(l=e==null?void 0:e.answer)==null?void 0:l.media)==null?void 0:A.translation)??((c=(u=e==null?void 0:e.answer)==null?void 0:u.captions)==null?void 0:c.translation),originalLanguage:(d=(h=e==null?void 0:e.answer)==null?void 0:h.transcription)==null?void 0:d.language,translationLanguage:(p=(g=(f=e==null?void 0:e.answer)==null?void 0:f.transcription)==null?void 0:g.translation)==null?void 0:p.language},i)]),L=Dh(e),U=yy(e);return{...le,...L,...U,key:X,captions:oe,wordTimings:Iy((v=e==null?void 0:e.answer)==null?void 0:v.transcription),answerLabel:((B=e==null?void 0:e.answer)==null?void 0:B.label)??(e==null?void 0:e.title),prevAnswerLabel:t?((w=(x=(y=(C=r==null?void 0:r.questions)==null?void 0:C.items)==null?void 0:y[t-1])==null?void 0:x.answer)==null?void 0:w.label)??((O=(F=(D=r==null?void 0:r.questions)==null?void 0:D.items)==null?void 0:F[t-1])==null?void 0:O.title)??null:null,isFirstInstanceOfName:t?((j=(M=r==null?void 0:r.questions)==null?void 0:M.items)==null?void 0:j.findIndex(q=>Dh(q).name===L.name))===t:!0}}const to={af:"Afrikaans",sq:"Albanian",am:"Amharic",ar:"Arabic",hy:"Armenian",az:"Azerbaijani",eu:"Basque",be:"Belarusian",bn:"Bengali",bs:"Bosnian",bg:"Bulgarian",ca:"Catalan",zh:"Chinese (Simplified)",zh_TW:"Chinese (Traditional)",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch",en:"English",et:"Estonian",fi:"Finnish",fr:"French",fa:"Farsi",tl:"Filipino",ka:"Georgian",de:"German",el:"Greek",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",ga:"Irish",it:"Italian",ja:"Japanese",kn:"Kannada",kk:"Kazakh",ko:"Korean",lv:"Latvian",lt:"Lithuanian",mk:"Macedonian",ms:"Malay",ml:"Malayalam",mt:"Maltese",mr:"Marathi",mn:"Mongolian",no:"Norwegian",ps:"Pashto",pl:"Polish",pt:"Portuguese",pa:"Punjabi",ro:"Romanian",ru:"Russian",sr:"Serbian",si:"Sinhala",sk:"Slovak",sl:"Slovenian",so:"Somali",es:"Spanish",sw:"Swahili",sv:"Swedish",ta:"Tamil",te:"Telugu",th:"Thai",tr:"Turkish",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",vi:"Vietnamese",cy:"Welsh"};function By({data:r}){var e,t;return((t=(e=r==null?void 0:r.questions)==null?void 0:e.items)==null?void 0:t.reduce((i,n)=>{var s,o,a,l,A,u,c;const h=(a=(o=(s=n==null?void 0:n.answer)==null?void 0:s.transcription)==null?void 0:o.language)==null?void 0:a.split("-")[0],d=(c=(u=(A=(l=n==null?void 0:n.answer)==null?void 0:l.transcription)==null?void 0:A.translation)==null?void 0:u.language)==null?void 0:c.split("-")[0];return h&&to[h]&&!i.find(f=>f.value===h)&&i.push({value:h,label:to[h]}),d&&to[d]&&!i.find(f=>f.value===d)&&i.push({value:d,label:to[d]}),i},[]))??[]}/**
2478
2478
  * @license
2479
2479
  * Copyright 2018 Google LLC
@@ -2492,23 +2492,23 @@ vec4 transition(vec2 uv) {
2492
2492
  New BW estimate: ${this.getBwEstimate()|0} bps
2493
2493
  Switching to level ${k} @ ${K|0} bps`),o.nextLoadLevel=o.nextAutoLevel=k,this.clearTimer();const te=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===k&&k>0){const ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${k>0?"and switching down":""}
2494
2494
  Fragment duration: ${n.duration.toFixed(3)} s
2495
- Time to underbuffer: ${ie.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,ie,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>_*2?te():this.timer=self.setInterval(te,_*1e3),o.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new xy(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n: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 V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case V.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:s}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),a=s?s.stats:i.stats,l=o-a.loading.start,A=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&A>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,A),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const s=e+i/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===Ee.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,l=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;const o=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ee.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,n,1,1);if(s>-1)return s;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,s)&&o[e].loadError<=o[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),A=this.getStarvationDelay();let u=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(A){const p=this.findBestLevel(l,o,n,A,0,u,c);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!A){const p=this.bitrateTestDelay;p&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const d=this.findBestLevel(l,o,n,A,h,u,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${A?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[o],g=i.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,s,o,a){var l;const A=n+s,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(f.length===1)return 0;const B=f[c],C=!!((l=this.hls.latestLevelDetails)!=null&&l.live),y=p===-1||u===-1;let x,w="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=ad(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=fC(f,M,t,i)),q=dC(U,w,e,F,O),{codecSet:R,videoRanges:_,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:te}=q;j=Y,x=R,w=te?_[_.length-1]:_[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${it(q)}`)}else x=B==null?void 0:B.codecSet,w=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=i;U>=t;U--){var L;const q=f[U],R=U>c;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(oC(q,M,w,D,e,F)||so(q.videoCodec))?(q.supportedPromise=rd(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const _e=this.hls.levels,Te=_e.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${Te} ${it(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Te} ${it(fe)}`),Te>-1&&_e.length>1&&(this.log(`Removing unsupported level ${Te}`),this.hls.removeLevel(Te),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=ed}if((x&&q.codecSet!==x||w&&q.videoRange!==w||R&&D>q.frameRate||!R&&D>0&&D<q.frameRate||q.supportedResult&&!((L=q.supportedResult.decodingInfoResults)!=null&&L[0].smooth))&&(!y||U!==j)){oe.push(U);continue}const _=q.details,k=(d?_==null?void 0:_.partTarget:_==null?void 0:_.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,te=this.getTimeToLoadFrag(le,K,Y*k,_===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(te<=le||!de(te)||C&&!this.bitrateTestDelay||te<A)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${w}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${A.toFixed(1)} fetchDuration:${te.toFixed(1)} firstSelection:${y} codecSet:${q.codecSet} videoRange:${q.videoRange} hls.loadLevel:${p}`)),y&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Sl={search:function(r,e){let t=0,i=r.length-1,n=null,s=null;for(;t<=i;){n=(t+i)/2|0,s=r[n];const o=e(s);if(o>0)t=n+1;else if(o<0)i=n-1;else return s}return null}};function IC(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!de(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<r.length;++s){const o=r[s];if(yC(e,t,o))return o}return null}function Ir(r,e,t=0,i=0,n=.005){let s=null;if(r){s=e[1+r.sn-e[0].sn]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&r.level!==s.level&&s.end<=r.end&&(s=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!r||r.level===s.level)&&cd(t,i,s)===0||vC(s,r,Math.min(n,i))))return s;const o=Sl.search(e,cd.bind(null,t,i));return o&&(o!==r||!s)?o:s}function vC(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return r.start<=i}return!1}function cd(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function yC(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function ud(r,e){return Sl.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}function CC(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const i=t.start,n=t.end;let s=r.fragments;if(!t.relurl){const{fragmentHint:o}=r;o&&(s=s.concat(o))}return Sl.search(s,o=>o.cc<e||o.end<=i?1:o.cc>e||o.start>=n?-1:0)}return null}function ho(r){switch(r.details){case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_TIMEOUT:case V.LEVEL_LOAD_TIMEOUT:case V.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function hd(r,e){const t=ho(e);return r.default[`${t?"timeout":"error"}Retry`]}function bl(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function dd(r){return Ye(Ye({},r),{errorRetry:null,timeoutRetry:null})}function fo(r,e,t,i){if(!r)return!1;const n=i==null?void 0:i.code,s=e<r.maxNumRetry&&(BC(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,s):s}function BC(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}var _t={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ei={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class TC extends Ti{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Ee.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,s=t.context;switch(t.details){case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case V.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Nn();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=_t.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const A=t.parent===Ee.MAIN?t.level:n.loadLevel;t.details===V.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,A):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,A))}return;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.SUBTITLE_LOAD_ERROR:case V.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const A=n.loadLevelObj;if(A&&(s.type===Me.AUDIO_TRACK&&A.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&A.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=_t.SendAlternateToPenaltyBox,t.errorAction.flags=ei.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const A=n.loadLevelObj,u=A==null?void 0:A.attrs["HDCP-LEVEL"];u?t.errorAction={action:_t.SendAlternateToPenaltyBox,flags:ei.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case V.BUFFER_ADD_CODEC_ERROR:case V.REMUX_ALLOC_ERROR:case V.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case V.INTERNAL_EXCEPTION:case V.BUFFER_APPENDING_ERROR:case V.BUFFER_FULL_ERROR:case V.LEVEL_SWITCH_ERROR:case V.BUFFER_STALLED_ERROR:case V.BUFFER_SEEK_OVER_HOLE:case V.BUFFER_NUDGE_ON_STALL:t.errorAction=Nn();return}t.type===Ie.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=hd(i.config.playlistLoadPolicy,e),s=this.playlistError++;if(fo(n,s,ho(e),e.response))return{action:_t.RetryRequest,flags:ei.None,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=hd(e.details.startsWith("key")?o:s,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,fo(a,l,ho(e),e.response)))return{action:_t.RetryRequest,flags:ei.None,retryConfig:a,retryCount:l};const A=this.getLevelSwitchAction(e,i);return a&&(A.retryConfig=a,A.retryCount=l),A}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const A=e.details;n.loadError++,A===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&A===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:w})=>n.audioCodec!==w),C=e.sourceBufferName==="video"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR)&&c.some(({codecSet:w,audioCodec:D})=>n.codecSet!==w&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let w=c.length;w--;){const D=(w+h)%c.length;if(D!==h&&D>=d&&D<=f&&c[D].loadError===0){var a,l;const F=c[D];if(A===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=c[D].details;if(O){const M=Ir(e.frag,O.fragments,e.frag.start);if(M!=null&&M.gap)continue}}else{if(y===Me.AUDIO_TRACK&&F.hasAudioGroup(x)||y===Me.SUBTITLE_TRACK&&F.hasSubtitleGroup(x))continue;if(g===Ee.AUDIO&&(a=n.audioGroups)!=null&&a.some(O=>F.hasAudioGroup(O))||g===Ee.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(O=>F.hasSubtitleGroup(O))||v&&n.audioCodec===F.audioCodec||!v&&n.audioCodec!==F.audioCodec||C&&n.codecSet===F.codecSet)continue}u=D;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:_t.SendAlternateToPenaltyBox,flags:ei.None,nextAutoLevel:u}}return{action:_t.SendAlternateToPenaltyBox,flags:ei.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case _t.DoNothing:break;case _t.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==V.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=i;switch(n){case ei.None:this.switchLevel(e,o);break;case ei.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=Tl[Tl.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,o)}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===V.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Zh(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===i&&this.hls.removeLevel(s)}}}function Nn(r){const e={action:_t.DoNothing,flags:ei.None};return r&&(e.resolved=!0),e}var Et={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class SC{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const s=i[n];if(!s)break;const o=s.end;if(s.start<=e&&o!==null&&e<=o)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,s=Object.keys(n);for(let o=s.length;o--;){const a=n[s[o]];if((a==null?void 0:a.body.type)===t&&(!i||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,s){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===i&&this.removeFragment(l.body);return}const A=l.range[e];if(A){if(A.time.length===0){this.removeFragment(l.body);return}A.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Or(i),s=this.fragments[n];if(!s||s.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(a=>{const l=i.elementaryStreams[a];if(!l)return;const A=t[a],u=o||l.partial===!0;s.range[a]=this.getBufferedTimes(i,e.part,u,A)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),go(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=fd(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Or(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const s={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,A=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const c=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(A>=c&&l<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>c){const d=Math.max(o,n.start(u)),f=Math.min(a,n.end(u));f>d&&(s.partial=!0,s.time.push({startPTS:d,endPTS:f}))}else if(a<=c)break}return s}getPartialFragment(e){let t=null,i,n,s,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(A=>{const u=l[A];u&&go(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(i=Math.min(e-n,s-e),o<=i&&(t=u.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||go(t))}getState(e){const t=Or(e),i=this.fragments[t];return i?i.buffered?go(i)?Et.PARTIAL:Et.OK:Et.APPENDING:Et.NOT_LOADED}isTimeBuffered(e,t,i){let n,s;for(let o=0;o<i.length;o++){if(n=i.start(o)-this.bufferPadding,s=i.end(o)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,s=Or(i);this.fragments[s]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:s,type:o}=t;if(i.sn==="initSegment")return;const a=i.type;if(n){let A=this.activePartLists[a];A||(this.activePartLists[a]=A=[]),A.push(n)}this.timeRanges=s;const l=s[o];this.detectEvictedFragments(o,l,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Or(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const s=t[i[n]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=Or(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=fd(i,s=>s.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;i&&i.forEach(n=>n.clearElementaryStreamInfo())}}function go(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function Or(r){return`${r.type}_${r.level}_${r.sn}`}function fd(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var qi={cbc:0,ctr:1};class bC{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case qi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case qi.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 xC(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class QC{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],s=i[1],o=i[2],a=i[3],l=this.invSubMix,A=l[0],u=l[1],c=l[2],h=l[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const B=d[f],C=d[B],y=d[C];let x=d[v]*257^v*16843008;n[f]=x<<24|x>>>8,s[f]=x<<16|x>>>16,o[f]=x<<8|x>>>24,a[f]=x,x=y*16843009^C*65537^B*257^f*16843008,A[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,c[v]=x<<8|x>>>24,h[v]=x,f?(f=B^d[d[d[y^B]]],g^=d[d[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const o=this.ksRows=(s+6+1)*4;let a,l;const A=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),c=this.sBox,h=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],v=d[3];let B,C;for(a=0;a<o;a++){if(a<s){B=A[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255]),A[a]=B=(A[a-s]^C)>>>0}for(l=0;l<o;l++)a=o-l,l&3?C=A[a]:C=A[a-4],l<4||a<=4?u[l]=C:u[l]=f[c[C>>>24]]^g[c[C>>>16&255]]^p[c[C>>>8&255]]^v[c[C&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],A=a[1],u=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let d=h[0],f=h[1],g=h[2],p=h[3];const v=new Int32Array(e),B=new Int32Array(v.length);let C,y,x,w,D,F,O,M,j,X,le,oe,L,U;const q=this.networkToHostOrderSwap;for(;t<v.length;){for(j=q(v[t]),X=q(v[t+1]),le=q(v[t+2]),oe=q(v[t+3]),D=j^s[0],F=oe^s[1],O=le^s[2],M=X^s[3],L=4,U=1;U<n;U++)C=l[D>>>24]^A[F>>16&255]^u[O>>8&255]^c[M&255]^s[L],y=l[F>>>24]^A[O>>16&255]^u[M>>8&255]^c[D&255]^s[L+1],x=l[O>>>24]^A[M>>16&255]^u[D>>8&255]^c[F&255]^s[L+2],w=l[M>>>24]^A[D>>16&255]^u[F>>8&255]^c[O&255]^s[L+3],D=C,F=y,O=x,M=w,L=L+4;C=o[D>>>24]<<24^o[F>>16&255]<<16^o[O>>8&255]<<8^o[M&255]^s[L],y=o[F>>>24]<<24^o[O>>16&255]<<16^o[M>>8&255]<<8^o[D&255]^s[L+1],x=o[O>>>24]<<24^o[M>>16&255]<<16^o[D>>8&255]<<8^o[F&255]^s[L+2],w=o[M>>>24]<<24^o[D>>16&255]<<16^o[F>>8&255]<<8^o[O&255]^s[L+3],B[t]=q(C^d),B[t+1]=q(w^f),B[t+2]=q(x^g),B[t+3]=q(y^p),d=j,f=X,g=le,p=oe,t=t+4}return B.buffer}}class _C{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=wC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function wC(r){switch(r){case qi.cbc:return"AES-CBC";case qi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const RC=16;class xl{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?xC(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,n);const l=this.flush();l?s(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==qi.cbc||t.byteLength!==16)return Oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Kt(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let A=this.softwareDecrypter;A||(A=this.softwareDecrypter=new QC),A.expandKey(t);const u=o;return this.currentResult=A.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new _C(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bC(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(Oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%RC;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const gd=Math.pow(2,17);class DC{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(md(e));return}else e.gap=!1;const A=this.loader=s?new s(n):new o(n),u=pd(e);e.loader=A;const c=dd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:gd};e.stats=A.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,A);let B=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(B.slice(0,16)),B=B.slice(16)),a({frag:e,part:null,payload:B,networkDetails:v})},onError:(f,g,p,v)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ye({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}};t&&(d.onProgress=(f,g,p,v)=>t({frag:e,part:null,payload:p,networkDetails:v})),A.load(u,h,d)})}loadPart(e,t,i){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(md(e,t));return}const A=this.loader=s?new s(n):new o(n),u=pd(e,t);e.loader=A;const c=dd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gd};t.stats=A.stats,A.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,A),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};i(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ye({url:u.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:d}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,s=n.total;if(i.loaded+=n.loaded,s){const l=Math.round(e.duration/t.duration),A=Math.min(Math.round(i.loaded/s),l),c=(l-A)*Math.round(i.loaded/A);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=n.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function pd(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,s=t.byteRangeEndOffset;if(de(n)&&de(s)){var o;let a=n,l=s;if(r.sn==="initSegment"&&LC((o=r.decryptdata)==null?void 0:o.method)){const A=s-n;A%16&&(l=s+(16-A%16)),n!==0&&(i.resetIV=!0,a=n-16)}i.rangeStart=a,i.rangeEnd=l}return i}function md(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new Si(i)}function LC(r){return r==="AES-128"||r==="AES-256"}class Si extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ed extends Ti{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ql{constructor(e,t,i,n=0,s=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=po(),this.buffering={audio:po(),video:po(),audiovideo:po()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=s,this.partial=o}}function po(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Id={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const i=Le.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Le.getBuffered(e);return Le.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let n=-1,s=[];if(i)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const c=s.length;if(c){const h=s[c-1].end;e[u].start-h<i?e[u].end>h&&(s[c-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,l=t,A=t;for(let u=0;u<s.length;u++){const c=s[u].start,h=s[u].end;if(n===-1&&t>=c&&t<=h&&(n=u),t+i>=c&&t<h)l=c,A=h,o=A-t;else if(t+i<c){a=c;break}}return{len:o,start:l||0,end:A||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||Id}catch(t){return Oe.log("failed to get media.buffered",t),Id}}}const vd=/\{\$([a-zA-Z0-9-_]+)\}/g;function yd(r){return vd.test(r)}function _l(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(vd,i=>{const n=i.substring(2,i.length-1),s=t==null?void 0:t[n];return s===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):s})}return e}function Cd(r,e,t){let i=r.variableList;i||(r.variableList=i={});let n,s;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))s=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function kC(r,e,t){const i=e.IMPORT;if(t&&i in t){let n=r.variableList;n||(r.variableList=n={}),n[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const MC=/^(\d+)x(\d+)$/,Bd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class st{constructor(e,t){typeof e=="string"&&(e=st.parseAttrList(e,t)),We(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=MC.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},s='"';for(Bd.lastIndex=0;(i=Bd.exec(e))!==null;){const o=i[1].trim();let a=i[2];const l=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let A=!1;if(l)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":A=!0}if(t&&(l||A))a=_l(t,a);else if(!A&&!l)switch(o){case"CLOSED-CAPTIONS":if(a==="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":Oe.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=a}return n}}const FC="com.apple.hls.interstitial";function PC(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function NC(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Td{constructor(e,t,i=0){var n;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=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const s=t.attr;for(const o in s)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==s[o]){Oe.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=We(new st({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const 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(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(de(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===FC}get isValid(){return!!this.id&&!this._badValueForSameId&&de(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)}}const OC=10;class UC{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||OC}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Ur(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function wl(r){switch(r){case"AES-128":case"AES-256":return qi.cbc;case"AES-256-CTR":return qi.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Rl(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Dl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function GC(r){const e=Dl(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function $C(r){const e=function(i,n,s){const o=i[n];i[n]=i[s],i[s]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function HC(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(i.splice(-1,1),t=Rl(o)):t=GC(o)}}return t}const mo=typeof self<"u"?self:void 0;var Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ft={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ll(r){switch(r){case Ft.FAIRPLAY:return Ve.FAIRPLAY;case Ft.PLAYREADY:return Ve.PLAYREADY;case Ft.WIDEVINE:return Ve.WIDEVINE;case Ft.CLEARKEY:return Ve.CLEARKEY}}var Eo={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function kl(r){if(r===Eo.WIDEVINE)return Ve.WIDEVINE;if(r===Eo.PLAYREADY)return Ve.PLAYREADY;if(r===Eo.CENC||r===Eo.CLEARKEY)return Ve.CLEARKEY}function Ml(r){switch(r){case Ve.FAIRPLAY:return Ft.FAIRPLAY;case Ve.PLAYREADY:return Ft.PLAYREADY;case Ve.WIDEVINE:return Ft.WIDEVINE;case Ve.CLEARKEY:return Ft.CLEARKEY}}function Io(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[Ve.FAIRPLAY,Ve.WIDEVINE,Ve.PLAYREADY,Ve.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ve.WIDEVINE]&&t&&i.push(Ve.WIDEVINE),i}const Sd=function(r){return mo!=null&&(r=mo.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function YC(r,e,t,i){let n;switch(r){case Ve.FAIRPLAY:n=["cenc","sinf"];break;case Ve.WIDEVINE:case Ve.PLAYREADY:n=["cenc"];break;case Ve.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return VC(n,e,t,i)}function VC(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function KC(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function bd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const l=Rl(a).subarray(0,16);return $C(l),l}}return null}let vo={};class On{static clearKeyUriToKeyIdMap(){vo={}}constructor(e,t,i,n=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ur(e)}isSupported(){if(this.method){if(Ur(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ft.FAIRPLAY:case Ft.WIDEVINE:case Ft.PLAYREADY:case Ft.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(Ur(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(Oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=WC(e);return new On(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=HC(this.uri);if(t)switch(this.keyFormat){case Ft.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Ft.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=zy(i,null,t),this.keyId=bd(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=vo[this.uri];if(!i){const n=Object.keys(vo).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),vo[this.uri]=i}this.keyId=i}return this}}function WC(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const xd=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Qd=/#EXT-X-MEDIA:(.*)/g,qC=/^#EXT(?:INF|-X-TARGETDURATION):/m,Fl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),JC=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ui{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return pl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qC.test(e)}static parseMasterPlaylist(e,t){const i=yd(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},s=[];xd.lastIndex=0;let o;for(;(o=xd.exec(e))!=null;)if(o[1]){var a;const A=new st(o[1],n),u=_l(n,o[2]),c={attrs:A,bitrate:A.decimalInteger("BANDWIDTH")||A.decimalInteger("AVERAGE-BANDWIDTH"),name:A.NAME,url:ui.resolve(u,t)},h=A.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),Dd(A.CODECS,c);const d=A["SUPPLEMENTAL-CODECS"];d&&(c.supplemental={},Dd(d,c.supplemental)),(a=c.unknownCodecs)!=null&&a.length||s.push(c),n.levels.push(c)}else if(o[3]){const A=o[3],u=o[4];switch(A){case"SESSION-DATA":{const c=new st(u,n),h=c["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=c);break}case"SESSION-KEY":{const c=wd(u,t,n);c.encrypted&&c.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new st(u,n);Cd(n,c,t)}break}case"CONTENT-STEERING":{const c=new st(u,n);n.contentSteering={uri:ui.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Rd(u);break}}}const l=s.length>0&&s.length<n.levels.length;return n.levels=l?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const s={},o=i.levels,a={AUDIO:o.map(A=>({id:A.attrs.AUDIO,audioCodec:A.audioCodec})),SUBTITLES:o.map(A=>({id:A.attrs.SUBTITLES,textCodec:A.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Qd.lastIndex=0;(n=Qd.exec(e))!==null;){const A=new st(n[1],i),u=A.TYPE;if(u){const c=a[u],h=s[u]||[];s[u]=h;const d=A.LANGUAGE,f=A["ASSOC-LANGUAGE"],g=A.CHANNELS,p=A.CHARACTERISTICS,v=A["INSTREAM-ID"],B={attrs:A,bitrate:0,id:l++,groupId:A["GROUP-ID"]||"",name:A.NAME||d||"",type:u,default:A.bool("DEFAULT"),autoselect:A.bool("AUTOSELECT"),forced:A.bool("FORCED"),lang:d,url:A.URI?ui.resolve(A.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),c!=null&&c.length){const C=ui.findGroup(c,B.groupId)||c[0];Ld(B,C,"audioCodec"),Ld(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,i,n,s,o){var a;const l={url:t},A=new UC(t),u=A.fragments,c=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new El(n,l),y,x,w,D=-1,F=!1,O=null,M;if(Fl.lastIndex=0,A.m3u8=e,A.hasVariableRefs=yd(e),((a=Fl.exec(e))==null?void 0:a[0])!=="#EXTM3U")return A.playlistParsingError=new Error("Missing format identifier #EXTM3U"),A;for(;(y=Fl.exec(e))!==null;){F&&(F=!1,C=new El(n,l),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=i,h&&(C.initSegment=h,h.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),O&&(C.setByteRange(O),O=null)));const oe=y[1];if(oe){C.duration=parseFloat(oe);const L=(" "+y[2]).slice(1);C.title=L||null,C.tagList.push(L?["INF",oe,L]:["INF",oe])}else if(y[3]){if(de(C.duration)){C.playlistOffset=g,C.start=g,w&&Md(C,w,A),C.sn=d,C.level=i,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=_l(A,L),Pl(C,B,c),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(JC),!y){Oe.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<y.length&&y[x]===void 0;x++);const L=(" "+y[x]).slice(1),U=(" "+y[x+1]).slice(1),q=y[x+2]?(" "+y[x+2]).slice(1):null;switch(L){case"BYTERANGE":B?C.setByteRange(U,B):C.setByteRange(U);break;case"PROGRAM-DATE-TIME":C.rawProgramDateTime=U,C.tagList.push(["PROGRAM-DATE-TIME",U]),D===-1&&(D=u.length);break;case"PLAYLIST-TYPE":A.type&&bi(A,L,y),A.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":A.startSN!==0?bi(A,L,y):u.length>0&&Fd(A,L,y),d=A.startSN=parseInt(U);break;case"SKIP":{A.skippedSegments&&bi(A,L,y);const R=new st(U,A),_=R.decimalInteger("SKIPPED-SEGMENTS");if(de(_)){A.skippedSegments+=_;for(let K=_;K--;)u.push(null);d+=_}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(A.recentlyRemovedDateranges=(A.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":A.targetduration!==0&&bi(A,L,y),A.targetduration=Math.max(parseInt(U),1);break;case"VERSION":A.version!==null&&bi(A,L,y),A.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":A.live||bi(A,L,y),A.live=!1;break;case"#":(U||q)&&C.tagList.push(q?[U,q]:[U]);break;case"DISCONTINUITY":p++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([L]);break;case"BITRATE":C.tagList.push([L,U]),v=parseInt(U)*1e3,de(v)?C.bitrate=v:v=0;break;case"DATERANGE":{const R=new st(U,A),_=new Td(R,A.dateRanges[R.ID],A.dateRangeTagCount);A.dateRangeTagCount++,_.isValid||A.skippedSegments?A.dateRanges[_.id]=_:Oe.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new st(U,A);"IMPORT"in R?kC(A,R,o):Cd(A,R,t)}break}case"DISCONTINUITY-SEQUENCE":A.startCC!==0?bi(A,L,y):u.length>0&&Fd(A,L,y),A.startCC=p=parseInt(U);break;case"KEY":{const R=wd(U,t,A);if(R.isSupported()){if(R.method==="NONE"){w=void 0;break}w||(w={}),w[R.keyFormat]&&(w=We({},w)),w[R.keyFormat]=R}else Oe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":A.startTimeOffset=Rd(U);break;case"MAP":{const R=new st(U,A);if(C.duration){const _=new El(n,l);kd(_,R,i,w),h=_,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const _=C.byteRangeEndOffset;if(_){const k=C.byteRangeStartOffset;O=`${_-k}@${k}`}else O=null;kd(C,R,i,w),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&bi(A,L,y),M=new st(U),A.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),A.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),A.canSkipDateRanges=A.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),A.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),A.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{A.partTarget&&bi(A,L,y);const R=new st(U);A.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=A.partList;R||(R=A.partList=[]);const _=f>0?R[R.length-1]:void 0,k=f++,K=new st(U,A),Y=new Py(K,C,l,k,_);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new st(U,A);A.preloadHint=R;break}case"RENDITION-REPORT":{const R=new st(U,A);A.renditionReports=A.renditionReports||[],A.renditionReports.push(R);break}default:Oe.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,A.partList&&(A.fragmentHint=B)):A.partList&&(Pl(C,B,c),C.cc=p,A.fragmentHint=C,w&&Md(C,w,A)),A.targetduration||(A.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=A.skippedSegments*A.targetduration,g>0&&j&&le){A.averagetargetduration=g/j;const oe=le.sn;A.endSN=oe!=="initSegment"?oe:0,A.live||(le.endList=!0),X&&A.startCC===void 0&&(A.startCC=X.cc),D>0&&(XC(u,D),X&&c.unshift(X))}else A.endSN=0,A.startCC=0;return A.fragmentHint&&(g+=A.fragmentHint.duration),A.totalduration=g,c.length&&A.dateRangeTagCount&&X&&_d(c,A),A.endCC=p,A}}function _d(r,e){const t=r.length,i=r[t-1],n=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const a=e.dateRanges[s[o]],l=a.startDate.getTime();a.tagAnchor=i.ref;for(let A=t;A--;){const u=jC(e,l,r,A,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function jC(r,e,t,i,n){const s=t[i];if(s){const a=s.programDateTime;if(e>=a||i===0){var o;const l=(((o=t[i+1])==null?void 0:o.start)||n)-s.start;if(e<=a+l*1e3){const A=t[i].sn-r.startSN,u=r.fragments;if(u.length>t.length){const h=(t[i+1]||u[u.length-1]).sn-r.startSN;for(let d=h;d>A;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return A}}}return-1}function wd(r,e,t){var i,n;const s=new st(r,t),o=(i=s.METHOD)!=null?i:"",a=s.URI,l=s.hexadecimalInteger("IV"),A=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!l&&Oe.error(`Invalid IV: ${s.IV}`);const c=a?ui.resolve(a,e):"",h=(A||"1").split("/").map(Number).filter(Number.isFinite);return new On(o,c,u,h,l)}function Rd(r){const t=new st(r).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Dd(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(s=>Jh(s,i));n.length&&(e[`${i}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function Ld(r,e,t){const i=e[t];i&&(r[t]=i)}function XC(r,e){let t=r[e];for(let i=e;i--;){const n=r[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Pl(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function kd(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function Md(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(r)}function bi(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Fd(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Nl(r,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>r.sn?(i=t-r.start,n=r):(i=r.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Pd(r,e,t,i,n,s){i-t<=0&&(Oe.warn("Fragment should have a positive duration",e),i=t+e.duration,s=n+e.duration);let a=t,l=i;const A=e.startPTS,u=e.endPTS;if(de(A)){const p=Math.abs(A-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,A),t=Math.min(t,A),n=Math.min(n,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),s=Math.max(s,e.endDTS)}const c=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=i,e.minEndPTS=l,e.endDTS=s;const h=e.sn;if(!r||h<r.startSN||h>r.endSN)return 0;let d;const f=h-r.startSN,g=r.fragments;for(g[f]=e,d=f;d>0;d--)Nl(g[d],g[d-1]);for(d=f;d<g.length-1;d++)Nl(g[d],g[d+1]);return r.fragmentHint&&Nl(g[g.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,c}function zC(r,e){if(r===e)return;let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const A=i[l].initSegment;if(A){t=A;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;tB(r,e,(l,A,u,c)=>{if(!e.startCC&&A.cc!==l.cc){var h,d;const f=l.cc-A.cc;for(let g=u;g<c.length;g++)c[g].cc+=f;e.startCC=(h=(d=Gd(r,e.startSN-1))==null?void 0:d.cc)!=null?h:c[0].cc,e.endCC=c[c.length-1].cc}de(l.startPTS)&&de(l.endPTS)&&(A.setStart(A.startPTS=l.startPTS),A.startDTS=l.startDTS,A.maxStartPTS=l.maxStartPTS,A.endPTS=l.endPTS,A.endDTS=l.endDTS,A.minEndPTS=l.minEndPTS,A.setDuration(l.endPTS-l.startPTS),A.duration&&(n=A),e.PTSKnown=e.alignedSliding=!0),l.hasStreams&&(A.elementaryStreams=l.elementaryStreams),A.loader=l.loader,l.hasStats&&(A.stats=l.stats),l.initSegment&&(A.initSegment=l.initSegment,t=l.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(l=>{var A;l&&(!l.initSegment||l.initSegment.relurl===((A=t)==null?void 0:A.relurl))&&(l.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(l=>!l),e.deltaUpdateFailed){Oe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=ZC(r.dateRanges,e));const l=r.fragments.filter(A=>A.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let A=1;A<o.length;A++)o[A].programDateTime===null&&Pl(o[A],o[A-1],l);_d(l,e)}eB(r.partList,e.partList,(l,A)=>{A.elementaryStreams=l.elementaryStreams,A.stats=l.stats}),n?Pd(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Od(r,e),s.length&&(e.totalduration=e.edge-s[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const l=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=l),e.driftEndTime=a,e.driftEnd=l}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function ZC(r,e){const{dateRanges:t,recentlyRemovedDateranges:i}=e,n=We({},r);i&&i.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const l=n[a],A=new Td(t[a].attr,l);A.isValid?(n[a]=A,l||(A.tagOrder+=o)):Oe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${it(t[a].attr)}"`)}),n}function eB(r,e,t){if(r&&e){let i=0;for(let n=0,s=r.length;n<=s;n++){const o=r[n],a=e[n+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function tB(r,e,t){const i=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,s=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let A=n;A<=s;A++){const u=l[o+A];let c=a[A];if(i&&!c&&u&&(c=e.fragments[A]=u),u&&c){if(t(u,c,A,a),u.url&&u.url!==c.url){e.playlistParsingError=Nd(`media sequence mismatch ${c.sn}:`,r,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=Nd(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,r,e,u,c);return}}}}function Nd(r,e,t,i,n){return new Error(`${r} ${n.url}
2495
+ Time to underbuffer: ${ie.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,ie,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>_*2?te():this.timer=self.setInterval(te,_*1e3),o.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new xy(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n: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 V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case V.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:s}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),a=s?s.stats:i.stats,l=o-a.loading.start,A=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&A>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,A),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const s=e+i/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===Ee.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,l=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;const o=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ee.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,n,1,1);if(s>-1)return s;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,s)&&o[e].loadError<=o[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),A=this.getStarvationDelay();let u=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(A){const p=this.findBestLevel(l,o,n,A,0,u,c);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!A){const p=this.bitrateTestDelay;p&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const d=this.findBestLevel(l,o,n,A,h,u,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${A?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[o],g=i.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,s,o,a){var l;const A=n+s,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(f.length===1)return 0;const B=f[c],C=!!((l=this.hls.latestLevelDetails)!=null&&l.live),y=p===-1||u===-1;let x,w="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=ad(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=fC(f,M,t,i)),q=dC(U,w,e,F,O),{codecSet:R,videoRanges:_,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:te}=q;j=Y,x=R,w=te?_[_.length-1]:_[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${it(q)}`)}else x=B==null?void 0:B.codecSet,w=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=i;U>=t;U--){var L;const q=f[U],R=U>c;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(oC(q,M,w,D,e,F)||so(q.videoCodec))?(q.supportedPromise=rd(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const _e=this.hls.levels,Te=_e.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${Te} ${it(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Te} ${it(fe)}`),Te>-1&&_e.length>1&&(this.log(`Removing unsupported level ${Te}`),this.hls.removeLevel(Te),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=ed}if((x&&q.codecSet!==x||w&&q.videoRange!==w||R&&D>q.frameRate||!R&&D>0&&D<q.frameRate||q.supportedResult&&!((L=q.supportedResult.decodingInfoResults)!=null&&L[0].smooth))&&(!y||U!==j)){oe.push(U);continue}const _=q.details,k=(d?_==null?void 0:_.partTarget:_==null?void 0:_.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,te=this.getTimeToLoadFrag(le,K,Y*k,_===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(te<=le||!de(te)||C&&!this.bitrateTestDelay||te<A)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${w}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${A.toFixed(1)} fetchDuration:${te.toFixed(1)} firstSelection:${y} codecSet:${q.codecSet} videoRange:${q.videoRange} hls.loadLevel:${p}`)),y&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Sl={search:function(r,e){let t=0,i=r.length-1,n=null,s=null;for(;t<=i;){n=(t+i)/2|0,s=r[n];const o=e(s);if(o>0)t=n+1;else if(o<0)i=n-1;else return s}return null}};function IC(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!de(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<r.length;++s){const o=r[s];if(yC(e,t,o))return o}return null}function Ir(r,e,t=0,i=0,n=.005){let s=null;if(r){s=e[1+r.sn-e[0].sn]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&r.level!==s.level&&s.end<=r.end&&(s=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!r||r.level===s.level)&&cd(t,i,s)===0||vC(s,r,Math.min(n,i))))return s;const o=Sl.search(e,cd.bind(null,t,i));return o&&(o!==r||!s)?o:s}function vC(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return r.start<=i}return!1}function cd(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function yC(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function ud(r,e){return Sl.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}function CC(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const i=t.start,n=t.end;let s=r.fragments;if(!t.relurl){const{fragmentHint:o}=r;o&&(s=s.concat(o))}return Sl.search(s,o=>o.cc<e||o.end<=i?1:o.cc>e||o.start>=n?-1:0)}return null}function ho(r){switch(r.details){case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_TIMEOUT:case V.LEVEL_LOAD_TIMEOUT:case V.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function hd(r,e){const t=ho(e);return r.default[`${t?"timeout":"error"}Retry`]}function bl(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function dd(r){return Ye(Ye({},r),{errorRetry:null,timeoutRetry:null})}function fo(r,e,t,i){if(!r)return!1;const n=i==null?void 0:i.code,s=e<r.maxNumRetry&&(BC(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,s):s}function BC(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}var wt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ei={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class TC extends Ti{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Ee.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,s=t.context;switch(t.details){case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case V.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Nn();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=wt.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const A=t.parent===Ee.MAIN?t.level:n.loadLevel;t.details===V.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(a=o.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,A):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,A))}return;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.SUBTITLE_LOAD_ERROR:case V.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const A=n.loadLevelObj;if(A&&(s.type===Me.AUDIO_TRACK&&A.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&A.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=wt.SendAlternateToPenaltyBox,t.errorAction.flags=ei.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const A=n.loadLevelObj,u=A==null?void 0:A.attrs["HDCP-LEVEL"];u?t.errorAction={action:wt.SendAlternateToPenaltyBox,flags:ei.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case V.BUFFER_ADD_CODEC_ERROR:case V.REMUX_ALLOC_ERROR:case V.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case V.INTERNAL_EXCEPTION:case V.BUFFER_APPENDING_ERROR:case V.BUFFER_FULL_ERROR:case V.LEVEL_SWITCH_ERROR:case V.BUFFER_STALLED_ERROR:case V.BUFFER_SEEK_OVER_HOLE:case V.BUFFER_NUDGE_ON_STALL:t.errorAction=Nn();return}t.type===Ie.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=hd(i.config.playlistLoadPolicy,e),s=this.playlistError++;if(fo(n,s,ho(e),e.response))return{action:wt.RetryRequest,flags:ei.None,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=hd(e.details.startsWith("key")?o:s,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,fo(a,l,ho(e),e.response)))return{action:wt.RetryRequest,flags:ei.None,retryConfig:a,retryCount:l};const A=this.getLevelSwitchAction(e,i);return a&&(A.retryConfig=a,A.retryCount=l),A}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const A=e.details;n.loadError++,A===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&A===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:w})=>n.audioCodec!==w),C=e.sourceBufferName==="video"&&(A===V.BUFFER_ADD_CODEC_ERROR||A===V.BUFFER_APPEND_ERROR)&&c.some(({codecSet:w,audioCodec:D})=>n.codecSet!==w&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let w=c.length;w--;){const D=(w+h)%c.length;if(D!==h&&D>=d&&D<=f&&c[D].loadError===0){var a,l;const F=c[D];if(A===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=c[D].details;if(O){const M=Ir(e.frag,O.fragments,e.frag.start);if(M!=null&&M.gap)continue}}else{if(y===Me.AUDIO_TRACK&&F.hasAudioGroup(x)||y===Me.SUBTITLE_TRACK&&F.hasSubtitleGroup(x))continue;if(g===Ee.AUDIO&&(a=n.audioGroups)!=null&&a.some(O=>F.hasAudioGroup(O))||g===Ee.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(O=>F.hasSubtitleGroup(O))||v&&n.audioCodec===F.audioCodec||!v&&n.audioCodec!==F.audioCodec||C&&n.codecSet===F.codecSet)continue}u=D;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:wt.SendAlternateToPenaltyBox,flags:ei.None,nextAutoLevel:u}}return{action:wt.SendAlternateToPenaltyBox,flags:ei.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case wt.DoNothing:break;case wt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==V.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=i;switch(n){case ei.None:this.switchLevel(e,o);break;case ei.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=Tl[Tl.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,o)}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===V.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Zh(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===i&&this.hls.removeLevel(s)}}}function Nn(r){const e={action:wt.DoNothing,flags:ei.None};return r&&(e.resolved=!0),e}var Et={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class SC{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const s=i[n];if(!s)break;const o=s.end;if(s.start<=e&&o!==null&&e<=o)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,s=Object.keys(n);for(let o=s.length;o--;){const a=n[s[o]];if((a==null?void 0:a.body.type)===t&&(!i||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,s){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===i&&this.removeFragment(l.body);return}const A=l.range[e];if(A){if(A.time.length===0){this.removeFragment(l.body);return}A.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Or(i),s=this.fragments[n];if(!s||s.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(a=>{const l=i.elementaryStreams[a];if(!l)return;const A=t[a],u=o||l.partial===!0;s.range[a]=this.getBufferedTimes(i,e.part,u,A)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),go(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=fd(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Or(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const s={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,A=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const c=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(A>=c&&l<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>c){const d=Math.max(o,n.start(u)),f=Math.min(a,n.end(u));f>d&&(s.partial=!0,s.time.push({startPTS:d,endPTS:f}))}else if(a<=c)break}return s}getPartialFragment(e){let t=null,i,n,s,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(A=>{const u=l[A];u&&go(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(i=Math.min(e-n,s-e),o<=i&&(t=u.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||go(t))}getState(e){const t=Or(e),i=this.fragments[t];return i?i.buffered?go(i)?Et.PARTIAL:Et.OK:Et.APPENDING:Et.NOT_LOADED}isTimeBuffered(e,t,i){let n,s;for(let o=0;o<i.length;o++){if(n=i.start(o)-this.bufferPadding,s=i.end(o)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,s=Or(i);this.fragments[s]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:s,type:o}=t;if(i.sn==="initSegment")return;const a=i.type;if(n){let A=this.activePartLists[a];A||(this.activePartLists[a]=A=[]),A.push(n)}this.timeRanges=s;const l=s[o];this.detectEvictedFragments(o,l,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Or(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const s=t[i[n]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=Or(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=fd(i,s=>s.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;i&&i.forEach(n=>n.clearElementaryStreamInfo())}}function go(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function Or(r){return`${r.type}_${r.level}_${r.sn}`}function fd(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var qi={cbc:0,ctr:1};class bC{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case qi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case qi.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 xC(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class QC{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],s=i[1],o=i[2],a=i[3],l=this.invSubMix,A=l[0],u=l[1],c=l[2],h=l[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const B=d[f],C=d[B],y=d[C];let x=d[v]*257^v*16843008;n[f]=x<<24|x>>>8,s[f]=x<<16|x>>>16,o[f]=x<<8|x>>>24,a[f]=x,x=y*16843009^C*65537^B*257^f*16843008,A[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,c[v]=x<<8|x>>>24,h[v]=x,f?(f=B^d[d[d[y^B]]],g^=d[d[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const o=this.ksRows=(s+6+1)*4;let a,l;const A=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),c=this.sBox,h=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],v=d[3];let B,C;for(a=0;a<o;a++){if(a<s){B=A[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=c[C>>>24]<<24|c[C>>>16&255]<<16|c[C>>>8&255]<<8|c[C&255]),A[a]=B=(A[a-s]^C)>>>0}for(l=0;l<o;l++)a=o-l,l&3?C=A[a]:C=A[a-4],l<4||a<=4?u[l]=C:u[l]=f[c[C>>>24]]^g[c[C>>>16&255]]^p[c[C>>>8&255]]^v[c[C&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],A=a[1],u=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let d=h[0],f=h[1],g=h[2],p=h[3];const v=new Int32Array(e),B=new Int32Array(v.length);let C,y,x,w,D,F,O,M,j,X,le,oe,L,U;const q=this.networkToHostOrderSwap;for(;t<v.length;){for(j=q(v[t]),X=q(v[t+1]),le=q(v[t+2]),oe=q(v[t+3]),D=j^s[0],F=oe^s[1],O=le^s[2],M=X^s[3],L=4,U=1;U<n;U++)C=l[D>>>24]^A[F>>16&255]^u[O>>8&255]^c[M&255]^s[L],y=l[F>>>24]^A[O>>16&255]^u[M>>8&255]^c[D&255]^s[L+1],x=l[O>>>24]^A[M>>16&255]^u[D>>8&255]^c[F&255]^s[L+2],w=l[M>>>24]^A[D>>16&255]^u[F>>8&255]^c[O&255]^s[L+3],D=C,F=y,O=x,M=w,L=L+4;C=o[D>>>24]<<24^o[F>>16&255]<<16^o[O>>8&255]<<8^o[M&255]^s[L],y=o[F>>>24]<<24^o[O>>16&255]<<16^o[M>>8&255]<<8^o[D&255]^s[L+1],x=o[O>>>24]<<24^o[M>>16&255]<<16^o[D>>8&255]<<8^o[F&255]^s[L+2],w=o[M>>>24]<<24^o[D>>16&255]<<16^o[F>>8&255]<<8^o[O&255]^s[L+3],B[t]=q(C^d),B[t+1]=q(w^f),B[t+2]=q(x^g),B[t+3]=q(y^p),d=j,f=X,g=le,p=oe,t=t+4}return B.buffer}}class _C{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=wC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function wC(r){switch(r){case qi.cbc:return"AES-CBC";case qi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const RC=16;class xl{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?xC(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,n);const l=this.flush();l?s(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==qi.cbc||t.byteLength!==16)return Oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Kt(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let A=this.softwareDecrypter;A||(A=this.softwareDecrypter=new QC),A.expandKey(t);const u=o;return this.currentResult=A.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new _C(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bC(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(Oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%RC;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const gd=Math.pow(2,17);class DC{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(md(e));return}else e.gap=!1;const A=this.loader=s?new s(n):new o(n),u=pd(e);e.loader=A;const c=dd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:gd};e.stats=A.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,A);let B=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(B.slice(0,16)),B=B.slice(16)),a({frag:e,part:null,payload:B,networkDetails:v})},onError:(f,g,p,v)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ye({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}};t&&(d.onProgress=(f,g,p,v)=>t({frag:e,part:null,payload:p,networkDetails:v})),A.load(u,h,d)})}loadPart(e,t,i){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(md(e,t));return}const A=this.loader=s?new s(n):new o(n),u=pd(e,t);e.loader=A;const c=dd(n.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gd};t.stats=A.stats,A.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,A),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};i(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ye({url:u.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:g,stats:p}))},onAbort:(d,f,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:d}))},onTimeout:(d,f,g)=>{this.resetLoader(e,A),l(new Si({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:d}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,s=n.total;if(i.loaded+=n.loaded,s){const l=Math.round(e.duration/t.duration),A=Math.min(Math.round(i.loaded/s),l),c=(l-A)*Math.round(i.loaded/A);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const o=i.loading,a=n.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function pd(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,s=t.byteRangeEndOffset;if(de(n)&&de(s)){var o;let a=n,l=s;if(r.sn==="initSegment"&&LC((o=r.decryptdata)==null?void 0:o.method)){const A=s-n;A%16&&(l=s+(16-A%16)),n!==0&&(i.resetIV=!0,a=n-16)}i.rangeStart=a,i.rangeEnd=l}return i}function md(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new Si(i)}function LC(r){return r==="AES-128"||r==="AES-256"}class Si extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ed extends Ti{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ql{constructor(e,t,i,n=0,s=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=po(),this.buffering={audio:po(),video:po(),audiovideo:po()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=s,this.partial=o}}function po(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Id={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const i=Le.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Le.getBuffered(e);return Le.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let n=-1,s=[];if(i)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const c=s.length;if(c){const h=s[c-1].end;e[u].start-h<i?e[u].end>h&&(s[c-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,l=t,A=t;for(let u=0;u<s.length;u++){const c=s[u].start,h=s[u].end;if(n===-1&&t>=c&&t<=h&&(n=u),t+i>=c&&t<h)l=c,A=h,o=A-t;else if(t+i<c){a=c;break}}return{len:o,start:l||0,end:A||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||Id}catch(t){return Oe.log("failed to get media.buffered",t),Id}}}const vd=/\{\$([a-zA-Z0-9-_]+)\}/g;function yd(r){return vd.test(r)}function _l(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(vd,i=>{const n=i.substring(2,i.length-1),s=t==null?void 0:t[n];return s===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):s})}return e}function Cd(r,e,t){let i=r.variableList;i||(r.variableList=i={});let n,s;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))s=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function kC(r,e,t){const i=e.IMPORT;if(t&&i in t){let n=r.variableList;n||(r.variableList=n={}),n[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const MC=/^(\d+)x(\d+)$/,Bd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class st{constructor(e,t){typeof e=="string"&&(e=st.parseAttrList(e,t)),We(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=MC.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},s='"';for(Bd.lastIndex=0;(i=Bd.exec(e))!==null;){const o=i[1].trim();let a=i[2];const l=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let A=!1;if(l)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":A=!0}if(t&&(l||A))a=_l(t,a);else if(!A&&!l)switch(o){case"CLOSED-CAPTIONS":if(a==="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":Oe.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=a}return n}}const FC="com.apple.hls.interstitial";function PC(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function NC(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Td{constructor(e,t,i=0){var n;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=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const s=t.attr;for(const o in s)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==s[o]){Oe.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=We(new st({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const 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(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(de(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===FC}get isValid(){return!!this.id&&!this._badValueForSameId&&de(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)}}const OC=10;class UC{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||OC}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Ur(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function wl(r){switch(r){case"AES-128":case"AES-256":return qi.cbc;case"AES-256-CTR":return qi.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Rl(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Dl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function GC(r){const e=Dl(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function $C(r){const e=function(i,n,s){const o=i[n];i[n]=i[s],i[s]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function HC(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(i.splice(-1,1),t=Rl(o)):t=GC(o)}}return t}const mo=typeof self<"u"?self:void 0;var Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ft={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ll(r){switch(r){case Ft.FAIRPLAY:return Ve.FAIRPLAY;case Ft.PLAYREADY:return Ve.PLAYREADY;case Ft.WIDEVINE:return Ve.WIDEVINE;case Ft.CLEARKEY:return Ve.CLEARKEY}}var Eo={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function kl(r){if(r===Eo.WIDEVINE)return Ve.WIDEVINE;if(r===Eo.PLAYREADY)return Ve.PLAYREADY;if(r===Eo.CENC||r===Eo.CLEARKEY)return Ve.CLEARKEY}function Ml(r){switch(r){case Ve.FAIRPLAY:return Ft.FAIRPLAY;case Ve.PLAYREADY:return Ft.PLAYREADY;case Ve.WIDEVINE:return Ft.WIDEVINE;case Ve.CLEARKEY:return Ft.CLEARKEY}}function Io(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[Ve.FAIRPLAY,Ve.WIDEVINE,Ve.PLAYREADY,Ve.CLEARKEY].filter(n=>!!e[n]):[];return!i[Ve.WIDEVINE]&&t&&i.push(Ve.WIDEVINE),i}const Sd=function(r){return mo!=null&&(r=mo.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function YC(r,e,t,i){let n;switch(r){case Ve.FAIRPLAY:n=["cenc","sinf"];break;case Ve.WIDEVINE:case Ve.PLAYREADY:n=["cenc"];break;case Ve.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return VC(n,e,t,i)}function VC(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function KC(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function bd(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const l=Rl(a).subarray(0,16);return $C(l),l}}return null}let vo={};class On{static clearKeyUriToKeyIdMap(){vo={}}constructor(e,t,i,n=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ur(e)}isSupported(){if(this.method){if(Ur(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ft.FAIRPLAY:case Ft.WIDEVINE:case Ft.PLAYREADY:case Ft.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(Ur(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(Oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=WC(e);return new On(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=HC(this.uri);if(t)switch(this.keyFormat){case Ft.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Ft.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=zy(i,null,t),this.keyId=bd(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=vo[this.uri];if(!i){const n=Object.keys(vo).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),vo[this.uri]=i}this.keyId=i}return this}}function WC(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const xd=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Qd=/#EXT-X-MEDIA:(.*)/g,qC=/^#EXT(?:INF|-X-TARGETDURATION):/m,Fl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),JC=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ui{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return pl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qC.test(e)}static parseMasterPlaylist(e,t){const i=yd(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},s=[];xd.lastIndex=0;let o;for(;(o=xd.exec(e))!=null;)if(o[1]){var a;const A=new st(o[1],n),u=_l(n,o[2]),c={attrs:A,bitrate:A.decimalInteger("BANDWIDTH")||A.decimalInteger("AVERAGE-BANDWIDTH"),name:A.NAME,url:ui.resolve(u,t)},h=A.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),Dd(A.CODECS,c);const d=A["SUPPLEMENTAL-CODECS"];d&&(c.supplemental={},Dd(d,c.supplemental)),(a=c.unknownCodecs)!=null&&a.length||s.push(c),n.levels.push(c)}else if(o[3]){const A=o[3],u=o[4];switch(A){case"SESSION-DATA":{const c=new st(u,n),h=c["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=c);break}case"SESSION-KEY":{const c=wd(u,t,n);c.encrypted&&c.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new st(u,n);Cd(n,c,t)}break}case"CONTENT-STEERING":{const c=new st(u,n);n.contentSteering={uri:ui.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Rd(u);break}}}const l=s.length>0&&s.length<n.levels.length;return n.levels=l?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const s={},o=i.levels,a={AUDIO:o.map(A=>({id:A.attrs.AUDIO,audioCodec:A.audioCodec})),SUBTITLES:o.map(A=>({id:A.attrs.SUBTITLES,textCodec:A.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Qd.lastIndex=0;(n=Qd.exec(e))!==null;){const A=new st(n[1],i),u=A.TYPE;if(u){const c=a[u],h=s[u]||[];s[u]=h;const d=A.LANGUAGE,f=A["ASSOC-LANGUAGE"],g=A.CHANNELS,p=A.CHARACTERISTICS,v=A["INSTREAM-ID"],B={attrs:A,bitrate:0,id:l++,groupId:A["GROUP-ID"]||"",name:A.NAME||d||"",type:u,default:A.bool("DEFAULT"),autoselect:A.bool("AUTOSELECT"),forced:A.bool("FORCED"),lang:d,url:A.URI?ui.resolve(A.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),c!=null&&c.length){const C=ui.findGroup(c,B.groupId)||c[0];Ld(B,C,"audioCodec"),Ld(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,i,n,s,o){var a;const l={url:t},A=new UC(t),u=A.fragments,c=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new El(n,l),y,x,w,D=-1,F=!1,O=null,M;if(Fl.lastIndex=0,A.m3u8=e,A.hasVariableRefs=yd(e),((a=Fl.exec(e))==null?void 0:a[0])!=="#EXTM3U")return A.playlistParsingError=new Error("Missing format identifier #EXTM3U"),A;for(;(y=Fl.exec(e))!==null;){F&&(F=!1,C=new El(n,l),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=i,h&&(C.initSegment=h,h.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),O&&(C.setByteRange(O),O=null)));const oe=y[1];if(oe){C.duration=parseFloat(oe);const L=(" "+y[2]).slice(1);C.title=L||null,C.tagList.push(L?["INF",oe,L]:["INF",oe])}else if(y[3]){if(de(C.duration)){C.playlistOffset=g,C.start=g,w&&Md(C,w,A),C.sn=d,C.level=i,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=_l(A,L),Pl(C,B,c),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(JC),!y){Oe.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<y.length&&y[x]===void 0;x++);const L=(" "+y[x]).slice(1),U=(" "+y[x+1]).slice(1),q=y[x+2]?(" "+y[x+2]).slice(1):null;switch(L){case"BYTERANGE":B?C.setByteRange(U,B):C.setByteRange(U);break;case"PROGRAM-DATE-TIME":C.rawProgramDateTime=U,C.tagList.push(["PROGRAM-DATE-TIME",U]),D===-1&&(D=u.length);break;case"PLAYLIST-TYPE":A.type&&bi(A,L,y),A.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":A.startSN!==0?bi(A,L,y):u.length>0&&Fd(A,L,y),d=A.startSN=parseInt(U);break;case"SKIP":{A.skippedSegments&&bi(A,L,y);const R=new st(U,A),_=R.decimalInteger("SKIPPED-SEGMENTS");if(de(_)){A.skippedSegments+=_;for(let K=_;K--;)u.push(null);d+=_}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(A.recentlyRemovedDateranges=(A.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":A.targetduration!==0&&bi(A,L,y),A.targetduration=Math.max(parseInt(U),1);break;case"VERSION":A.version!==null&&bi(A,L,y),A.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":A.live||bi(A,L,y),A.live=!1;break;case"#":(U||q)&&C.tagList.push(q?[U,q]:[U]);break;case"DISCONTINUITY":p++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([L]);break;case"BITRATE":C.tagList.push([L,U]),v=parseInt(U)*1e3,de(v)?C.bitrate=v:v=0;break;case"DATERANGE":{const R=new st(U,A),_=new Td(R,A.dateRanges[R.ID],A.dateRangeTagCount);A.dateRangeTagCount++,_.isValid||A.skippedSegments?A.dateRanges[_.id]=_:Oe.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new st(U,A);"IMPORT"in R?kC(A,R,o):Cd(A,R,t)}break}case"DISCONTINUITY-SEQUENCE":A.startCC!==0?bi(A,L,y):u.length>0&&Fd(A,L,y),A.startCC=p=parseInt(U);break;case"KEY":{const R=wd(U,t,A);if(R.isSupported()){if(R.method==="NONE"){w=void 0;break}w||(w={}),w[R.keyFormat]&&(w=We({},w)),w[R.keyFormat]=R}else Oe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":A.startTimeOffset=Rd(U);break;case"MAP":{const R=new st(U,A);if(C.duration){const _=new El(n,l);kd(_,R,i,w),h=_,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const _=C.byteRangeEndOffset;if(_){const k=C.byteRangeStartOffset;O=`${_-k}@${k}`}else O=null;kd(C,R,i,w),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&bi(A,L,y),M=new st(U),A.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),A.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),A.canSkipDateRanges=A.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),A.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),A.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{A.partTarget&&bi(A,L,y);const R=new st(U);A.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=A.partList;R||(R=A.partList=[]);const _=f>0?R[R.length-1]:void 0,k=f++,K=new st(U,A),Y=new Py(K,C,l,k,_);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new st(U,A);A.preloadHint=R;break}case"RENDITION-REPORT":{const R=new st(U,A);A.renditionReports=A.renditionReports||[],A.renditionReports.push(R);break}default:Oe.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,A.partList&&(A.fragmentHint=B)):A.partList&&(Pl(C,B,c),C.cc=p,A.fragmentHint=C,w&&Md(C,w,A)),A.targetduration||(A.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=A.skippedSegments*A.targetduration,g>0&&j&&le){A.averagetargetduration=g/j;const oe=le.sn;A.endSN=oe!=="initSegment"?oe:0,A.live||(le.endList=!0),X&&A.startCC===void 0&&(A.startCC=X.cc),D>0&&(XC(u,D),X&&c.unshift(X))}else A.endSN=0,A.startCC=0;return A.fragmentHint&&(g+=A.fragmentHint.duration),A.totalduration=g,c.length&&A.dateRangeTagCount&&X&&_d(c,A),A.endCC=p,A}}function _d(r,e){const t=r.length,i=r[t-1],n=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const a=e.dateRanges[s[o]],l=a.startDate.getTime();a.tagAnchor=i.ref;for(let A=t;A--;){const u=jC(e,l,r,A,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function jC(r,e,t,i,n){const s=t[i];if(s){const a=s.programDateTime;if(e>=a||i===0){var o;const l=(((o=t[i+1])==null?void 0:o.start)||n)-s.start;if(e<=a+l*1e3){const A=t[i].sn-r.startSN,u=r.fragments;if(u.length>t.length){const h=(t[i+1]||u[u.length-1]).sn-r.startSN;for(let d=h;d>A;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return A}}}return-1}function wd(r,e,t){var i,n;const s=new st(r,t),o=(i=s.METHOD)!=null?i:"",a=s.URI,l=s.hexadecimalInteger("IV"),A=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!l&&Oe.error(`Invalid IV: ${s.IV}`);const c=a?ui.resolve(a,e):"",h=(A||"1").split("/").map(Number).filter(Number.isFinite);return new On(o,c,u,h,l)}function Rd(r){const t=new st(r).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Dd(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(s=>Jh(s,i));n.length&&(e[`${i}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function Ld(r,e,t){const i=e[t];i&&(r[t]=i)}function XC(r,e){let t=r[e];for(let i=e;i--;){const n=r[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Pl(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function kd(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function Md(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(r)}function bi(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Fd(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Nl(r,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>r.sn?(i=t-r.start,n=r):(i=r.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Pd(r,e,t,i,n,s){i-t<=0&&(Oe.warn("Fragment should have a positive duration",e),i=t+e.duration,s=n+e.duration);let a=t,l=i;const A=e.startPTS,u=e.endPTS;if(de(A)){const p=Math.abs(A-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,A),t=Math.min(t,A),n=Math.min(n,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),s=Math.max(s,e.endDTS)}const c=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=i,e.minEndPTS=l,e.endDTS=s;const h=e.sn;if(!r||h<r.startSN||h>r.endSN)return 0;let d;const f=h-r.startSN,g=r.fragments;for(g[f]=e,d=f;d>0;d--)Nl(g[d],g[d-1]);for(d=f;d<g.length-1;d++)Nl(g[d],g[d+1]);return r.fragmentHint&&Nl(g[g.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,c}function zC(r,e){if(r===e)return;let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const A=i[l].initSegment;if(A){t=A;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;tB(r,e,(l,A,u,c)=>{if(!e.startCC&&A.cc!==l.cc){var h,d;const f=l.cc-A.cc;for(let g=u;g<c.length;g++)c[g].cc+=f;e.startCC=(h=(d=Gd(r,e.startSN-1))==null?void 0:d.cc)!=null?h:c[0].cc,e.endCC=c[c.length-1].cc}de(l.startPTS)&&de(l.endPTS)&&(A.setStart(A.startPTS=l.startPTS),A.startDTS=l.startDTS,A.maxStartPTS=l.maxStartPTS,A.endPTS=l.endPTS,A.endDTS=l.endDTS,A.minEndPTS=l.minEndPTS,A.setDuration(l.endPTS-l.startPTS),A.duration&&(n=A),e.PTSKnown=e.alignedSliding=!0),l.hasStreams&&(A.elementaryStreams=l.elementaryStreams),A.loader=l.loader,l.hasStats&&(A.stats=l.stats),l.initSegment&&(A.initSegment=l.initSegment,t=l.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(l=>{var A;l&&(!l.initSegment||l.initSegment.relurl===((A=t)==null?void 0:A.relurl))&&(l.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(l=>!l),e.deltaUpdateFailed){Oe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=ZC(r.dateRanges,e));const l=r.fragments.filter(A=>A.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let A=1;A<o.length;A++)o[A].programDateTime===null&&Pl(o[A],o[A-1],l);_d(l,e)}eB(r.partList,e.partList,(l,A)=>{A.elementaryStreams=l.elementaryStreams,A.stats=l.stats}),n?Pd(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Od(r,e),s.length&&(e.totalduration=e.edge-s[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const l=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=l),e.driftEndTime=a,e.driftEnd=l}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function ZC(r,e){const{dateRanges:t,recentlyRemovedDateranges:i}=e,n=We({},r);i&&i.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const l=n[a],A=new Td(t[a].attr,l);A.isValid?(n[a]=A,l||(A.tagOrder+=o)):Oe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${it(t[a].attr)}"`)}),n}function eB(r,e,t){if(r&&e){let i=0;for(let n=0,s=r.length;n<=s;n++){const o=r[n],a=e[n+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--}}}function tB(r,e,t){const i=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,s=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let A=n;A<=s;A++){const u=l[o+A];let c=a[A];if(i&&!c&&u&&(c=e.fragments[A]=u),u&&c){if(t(u,c,A,a),u.url&&u.url!==c.url){e.playlistParsingError=Nd(`media sequence mismatch ${c.sn}:`,r,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=Nd(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,r,e,u,c);return}}}}function Nd(r,e,t,i,n){return new Error(`${r} ${n.url}
2496
2496
  Playlist starting @${e.startSN}
2497
2497
  ${e.m3u8}
2498
2498
 
2499
2499
  Playlist starting @${t.startSN}
2500
- ${t.m3u8}`)}function Od(r,e,t=!0){const i=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,s=i>=0;let o=0;if(s&&i<n.length)o=n[i].start;else if(s&&e.startSN===r.endSN+1)o=r.fragmentEnd;else if(s&&t)o=r.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart;else return;Ol(e,o)}function Ol(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Ud(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const s=i[i.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function Gd(r,e,t){if(!r)return null;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e)?i:e<r.startSN&&t&&t.sn===e?t:null}function $d(r,e,t){return r?Hd(r.partList,e,t):null}function Hd(r,e,t){if(r)for(let i=r.length;i--;){const n=r[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function Yd(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Un(r,e){for(let i=0,n=r.length;i<n;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function iB(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Vd(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Kd(r,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Vd(t[i],r);e.fragmentHint&&Vd(e.fragmentHint,r),e.alignedSliding=!0}function rB(r,e){r&&(Wd(e,r),!e.alignedSliding&&r&&yo(e,r),!e.alignedSliding&&r&&!e.skippedSegments&&Od(r,e,!1))}function Wd(r,e){if(!iB(e,r))return;const t=Math.min(e.endCC,r.endCC),i=Un(e.fragments,t),n=Un(r.fragments,t);if(!i||!n)return;Oe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=i.start-n.start;Kd(s,r)}function yo(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,s;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Un(i,o),s=Un(t,o)),(!n||!s)&&(n=i[Math.floor(i.length/2)],s=Un(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,l=s.programDateTime;if(!a||!l)return;const A=(l-a)/1e3-(s.start-n.start);Kd(A,r)}const nB={toString:function(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}},Z={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Ul extends Ed{constructor(e,t,i,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Z.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:a,media:l,mediaBuffer:A,state:u}=this,c=l?l.currentTime:0,h=Le.bufferInfo(A||l,c,o.maxBufferHole);if(this.log(`media seeking to ${de(c)?c.toFixed(3):c}, state: ${u}`),this.state===Z.ENDED)this.resetLoadingState();else if(a){const d=o.maxFragLookUpTolerance,f=a.start-d,g=a.start+a.duration+d;if(!h.len||g<h.start||f>h.end){const p=c>g;(c<f||p)&&(p&&a.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(c>d&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${c} because of seek before start`),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new DC(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new xl(e.config)}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Z.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=Z.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const s=e.nextStart;if(s&&s>n&&s<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const A=a[a.length-1];return Le.isBuffered(this.media,A.start+A.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),n.removeEventListener("seeking",this.onMediaSeeking),n.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Z.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=s=>{const o=s.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(o,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,i,n).then(s=>{if(!s)return;const o=this.state,a=s.frag;if(this.fragContextChanged(a)){(o===Z.FRAG_LOADING||!this.fragCurrent&&o===Z.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=Z.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(I.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Et.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Et.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:s,payload:o}=i,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Ur(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,wl(a.method)).catch(A=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:A,reason:A.message,frag:s}),A}).then(A=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:A,stats:{tstart:l,tdecrypt:u}}),i.payload=A,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?nB.toString(Le.getBuffered(i)):"(detached)"})`),vt(e)){var n;if(e.type!==Ee.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=Z.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Z.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(l=>!l),a=new Ql(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var s;this.fragCurrent=e;const o=t==null?void 0:t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Z.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(I.KEY_LOADED,c),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),c}),this.hls.trigger(I.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments);const l=this.fragPrevious;if(vt(e)&&(!l||e.sn!==l.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=c)}if(i=Math.max(e.start,i||0),this.loadingParts&&vt(e)){const c=o.partList;if(c&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(c,e,i);if(h>-1){const d=c[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${c.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=Z.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,n)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}if(vt(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${o?"["+o.startSN+"-"+o.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const A=this.config.progressive;let u;return A&&a?u=a.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,n)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,A?n:void 0),a]).then(([c])=>(!A&&c&&n&&n(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((s,o)=>{var a;const l=[],A=(a=i.details)==null?void 0:a.partList,u=c=>{this.fragmentLoader.loadPart(e,c,n).then(h=>{l[c.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=$d(i.details,e.sn,c.index+1)||Hd(A,e.sn,c.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:l})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===V.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Z.PARSING){!this.fragCurrent&&this.state!==Z.STOPPED&&this.state!==Z.ERROR&&(this.state=Z.IDLE);return}const{frag:i,part:n,level:s}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),A=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=A),this.updateLevelTiming(i,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var i;const s=e.partList[0],o=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:s,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],l=a.details,A=o>-1?$d(l,s,o):null,u=A?A.fragment:Gd(l,s,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:A,level:a}):null}bufferFragmentData(e,t,i,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:l}=e;let A=a;if(a&&l&&(A=Kt(a,l)),!((o=A)!=null&&o.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:A};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Le.bufferInfo(t,i,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(s.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(s.nextStart,o.end)-t,n);return Le.bufferInfo(e,t,a)}}return s}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return s>=n?(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var i;const n=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:s}=this,o=i[0].start,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=s.initialLiveManifestSize;if(n<c)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var A;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t,i);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=l?(h!==-1&&h>=o?h:d)||l.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(A=l)==null?void 0:A.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(l=i[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Et.OK||i===Et.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(a!==null&&i.len+a.len>=s){const l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(qd(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(qd(this.hls.config)&&e.type!==Ee.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=i==null?void 0:i.playerQueue;if(s)for(let o=s.length;o--;){const a=s[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,s=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const A=e[a];if(o=o&&!A.independent,n>-1&&i<A.start)break;const u=A.loaded;u?n=-1:(s||A.independent||o)&&A.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=IC(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=ud(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:A}=n,u=i.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&l&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-A||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:A;h=Ir(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-i.startSN,g=this.fragmentTracker.getState(h);if((g===Et.OK||g===Et.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!c||u[0].fragment.sn>h.sn||!i.live&&!c)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==Et.OK?h=v:h=null}}return h}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,o=!t,a=e.alignedSliding&&de(s);if(o||!a&&!s){rB(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(i=t+o,o<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&vt(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Z.FRAG_LOADING_WAITING_RETRY)&&(this.state=Z.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,flags:l,retryCount:A=0,retryConfig:u}=o||{},c=!!o&&!!u,h=c&&a===_t.RetryRequest,d=c&&!o.resolved&&l===ei.MoveAllAlternatesMatchingHost;if(!h&&d&&vt(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((h||d)&&A<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=bl(u,A);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${A+1}/${u.maxNumRetry} in ${f}ms`),o.resolved=!0,this.retryDate=self.performance.now()+f,this.state=Z.FRAG_LOADING_WAITING_RETRY}else if(u&&o)if(this.resetFragmentErrors(e),A<u.maxNumRetry)!s&&a!==_t.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${A})`);return}else a===_t.SendAlternateToPenaltyBox?this.state=Z.WAITING_LEVEL:this.state=Z.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Z.PARSING||this.state===Z.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!s;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===Ee.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Z.STOPPED&&(this.state=Z.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Z.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const s=i.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,A)=>{const u=e.elementaryStreams[A];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${A} duration reliably (${c})`),l||!1;const h=n?0:Pd(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:A,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var a;if(i.fragmentError===0&&this.treatAsGap(e,i),((a=this.transmuxer)==null?void 0:a.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Z.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Ee.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!i?e.endPTS:(i||e).end)!=null?s:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function qd(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Jd{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=sB(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function sB(r,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<r.length;n++){const s=r[n];t.set(s,i),i+=s.length}return t}var Gl={exports:{}},jd;function oB(){return jd||(jd=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,A,u){this.fn=l,this.context=A,this.once=u||!1}function s(l,A,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,c||l,h),f=t?t+A:A;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],d]:l._events[f].push(d):(l._events[f]=d,l._eventsCount++),l}function o(l,A){--l._eventsCount===0?l._events=new i:delete l._events[A]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var A=[],u,c;if(this._eventsCount===0)return A;for(c in u=this._events)e.call(u,c)&&A.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(u)):A},a.prototype.listeners=function(A){var u=t?t+A:A,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,d=c.length,f=new Array(d);h<d;h++)f[h]=c[h].fn;return f},a.prototype.listenerCount=function(A){var u=t?t+A:A,c=this._events[u];return c?c.fn?1:c.length:0},a.prototype.emit=function(A,u,c,h,d,f){var g=t?t+A:A;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(A,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,c),!0;case 4:return p.fn.call(p.context,u,c,h),!0;case 5:return p.fn.call(p.context,u,c,h,d),!0;case 6:return p.fn.call(p.context,u,c,h,d,f),!0}for(C=1,B=new Array(v-1);C<v;C++)B[C-1]=arguments[C];p.fn.apply(p.context,B)}else{var y=p.length,x;for(C=0;C<y;C++)switch(p[C].once&&this.removeListener(A,p[C].fn,void 0,!0),v){case 1:p[C].fn.call(p[C].context);break;case 2:p[C].fn.call(p[C].context,u);break;case 3:p[C].fn.call(p[C].context,u,c);break;case 4:p[C].fn.call(p[C].context,u,c,h);break;default:if(!B)for(x=1,B=new Array(v-1);x<v;x++)B[x-1]=arguments[x];p[C].fn.apply(p[C].context,B)}}return!0},a.prototype.on=function(A,u,c){return s(this,A,u,c,!1)},a.prototype.once=function(A,u,c){return s(this,A,u,c,!0)},a.prototype.removeListener=function(A,u,c,h){var d=t?t+A:A;if(!this._events[d])return this;if(!u)return o(this,d),this;var f=this._events[d];if(f.fn)f.fn===u&&(!h||f.once)&&(!c||f.context===c)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||c&&f[g].context!==c)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(A){var u;return A?(u=t?t+A:A,this._events[u]&&o(this,u)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a}(Gl)),Gl.exports}var aB=oB(),$l=My(aB);const Gn="1.6.2",Gr={};function lB(){return typeof __HLS_WORKER_BUNDLE__=="function"}function AB(){const r=Gr[Gn];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return Gr[Gn]=n,n}function cB(r){const e=Gr[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Gr[r]=n,n}function uB(r){const e=Gr[r||Gn];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete Gr[r||Gn],n&&self.URL.revokeObjectURL(n),i.terminate()}}function Xd(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Hl(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Co(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function $n(r,e){const t=e;let i=0;for(;Hl(r,e);){i+=10;const n=Co(r,e+6);i+=n,Xd(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function hB(r,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[t+2],o=s>>2&15;if(o>12){const d=new Error(`invalid ADTS sampling index:${o}`);r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}const a=(s>>6&3)+1,l=e[t+3]>>6&3|(s&1)<<2,A="mp4a.40."+a,u=n[o];let c=o;(a===5||a===29)&&(c-=3);const h=[a<<3|(c&14)>>1,(c&1)<<7|l<<3];return Oe.log(`manifest codec:${i}, parsed codec:${A}, channels:${l}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:l,codec:A,parsedCodec:A,manifestCodec:i}}function zd(r,e){return r[e]===255&&(r[e+1]&246)===240}function Zd(r,e){return r[e+1]&1?7:9}function Yl(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function dB(r,e){return e+5<r.length}function Bo(r,e){return e+1<r.length&&zd(r,e)}function fB(r,e){return dB(r,e)&&zd(r,e)&&Yl(r,e)<=r.length-e}function gB(r,e){if(Bo(r,e)){const t=Zd(r,e);if(e+t>=r.length)return!1;const i=Yl(r,e);if(i<=t)return!1;const n=e+i;return n===r.length||Bo(r,n)}return!1}function ef(r,e,t,i,n){if(!r.samplerate){const s=hB(e,t,i,n);if(!s)return;We(r,s)}}function tf(r){return 9216e4/r}function pB(r,e){const t=Zd(r,e);if(e+t<=r.length){const i=Yl(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function rf(r,e,t,i,n){const s=tf(r.samplerate),o=i+n*s,a=pB(e,t);let l;if(a){const{frameLength:c,headerLength:h}=a,d=h+c,f=Math.max(0,t+d-e.length);f?(l=new Uint8Array(d-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+d);const g={unit:l,pts:o};return f||r.samples.push(g),{sample:g,length:d,missing:f}}const A=e.length-t;return l=new Uint8Array(A),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:A,missing:-1}}function mB(r,e){return Hl(r,e)&&Co(r,e+6)+10<=r.length-e}function EB(r){if(r.size<2)return;const e=Ut(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function IB(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=Ut(r.data.subarray(t),!0);t+=i.length+1;const n=Ut(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=Ut(r.data.subarray(1));return{key:r.type,info:"",data:e}}function vB(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=Ut(r.data.subarray(t),!0);t+=i.length+1;const n=Ut(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=Ut(r.data);return{key:r.type,info:"",data:e}}function yB(r){return btoa(String.fromCharCode(...r))}function nf(r,e){if(r<0)return-nf(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const n=Math.floor(r*t);return(n%2===0?n:n+1)/t}else return Math.round(r*t)/t}function CB(r,e){const t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;const n=t.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1);for(;n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}function BB(){try{return crypto.randomUUID()}catch{try{const 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,n=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?s:s&3|8).toString(16)})}}}function TB(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Vl(r,e=0,t=1/0){return SB(r,e,t,Uint8Array)}function SB(r,e,t,i){const n=bB(r);let s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);const o=xB(r)?r.byteOffset:0,a=(o+r.byteLength)/s,l=(o+e)/s,A=Math.floor(Math.max(0,Math.min(l,a))),u=Math.floor(Math.min(A+Math.max(t,0),a));return new i(n,A,u-A)}function bB(r){return r instanceof ArrayBuffer?r:r.buffer}function xB(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function QB(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const n=Ut(Vl(r.data,1,i)),s=r.data[2+i],o=r.data.subarray(3+i).indexOf(0);if(o===-1)return;const a=Ut(Vl(r.data,3+i,o));let l;return n==="-->"?l=Ut(Vl(r.data,4+i+o)):l=TB(r.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=l,e}function _B(r){return r.type==="PRIV"?EB(r):r.type[0]==="W"?vB(r):r.type==="APIC"?QB(r):IB(r)}function wB(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Co(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const To=10,RB=10;function sf(r){let e=0;const t=[];for(;Hl(r,e);){const i=Co(r,e+6);r[e+5]>>6&1&&(e+=To),e+=To;const n=e+i;for(;e+RB<n;){const s=wB(r.subarray(e)),o=_B(s);o&&t.push(o),e+=s.size+To}Xd(r,e)&&(e+=To)}return t}function of(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function DB(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Kl(r){const e=sf(r);for(let t=0;t<e.length;t++){const i=e[t];if(of(i))return DB(i)}}let Gt=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function hi(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Wl{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Kt(this.cachedData,e),this.cachedData=null);let i=$n(e,0),n=i?i.length:0,s;const o=this._audioTrack,a=this._id3Track,l=i?Kl(i):void 0,A=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=LB(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Gt.audioId3,duration:Number.POSITIVE_INFINITY});n<A;){if(this.canParse(e,n)){const u=this.appendFrame(o,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,n+=u.length,s=n):n=A}else mB(e,n)?(i=$n(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Gt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,s=n):n++;if(n===A&&s!==A){const u=e.slice(s);this.cachedData?this.cachedData=Kt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:hi(),id3Track:a,textTrack:hi()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:hi(),id3Track:this._id3Track,textTrack:hi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const LB=(r,e,t)=>{if(de(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let So=null;const kB=[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],MB=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],FB=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],PB=[0,1,1,4];function af(r,e,t,i,n){if(t+24>e.length)return;const s=lf(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=i+n*o,l={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=s.channelCount,r.samplerate=s.sampleRate,r.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function lf(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,n=r[e+2]>>4&15,s=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,A=kB[l*14+n-1]*1e3,c=MB[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=FB[t][i],f=PB[i],g=d*8*f,p=Math.floor(d*A/c+o)*f;if(So===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);So=C?parseInt(C[1]):0}return!!So&&So<=87&&i===2&&A>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:c,channelCount:h,frameLength:p,samplesPerFrame:g}}}function ql(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Af(r,e){return e+1<r.length&&ql(r,e)}function NB(r,e){return ql(r,e)&&4<=r.length-e}function cf(r,e){if(e+1<r.length&&ql(r,e)){const i=lf(r,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const s=e+n;return s===r.length||Af(r,s)}return!1}class OB extends Wl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=$n(e,0);let n=(i==null?void 0:i.length)||0;if(cf(e,n))return!1;for(let s=e.length;n<s;n++)if(gB(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return fB(e,t)}appendFrame(e,t,i){ef(e,this.observer,t,i,e.manifestCodec);const n=rf(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const uf=(r,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=r[e];const a=Math.min(i,8),l=8-a;s[0]=4278190080>>>24+l<<l,n[0]=(o[0]&s[0])>>l,t=t?t<<a|n[0]:n[0],e+=1,i-=a}return t};class UB extends Wl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=hf(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=$n(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&Kl(t)!==void 0&&uf(e,i)<16}}function hf(r,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const s=e[t+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],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+s]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][c]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|c<<3|d<<2|l>>4,l<<4&224]),C=1536/a*9e4,y=i+n*C,x=e.subarray(t,t+u);return r.config=B,r.channelCount=g,r.samplerate=a,r.samples.push({unit:x,pts:y}),u}class GB extends Wl{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=$n(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Kl(t)!==void 0&&uf(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(cf(e,i))return Oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return NB(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return af(e,t,i,this.basePTS,this.frameIndex)}}const $B=/\/emsg[-/]ID3/i;class HB{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,n){const s=this.videoTrack=hi("video",1),o=this.audioTrack=hi("audio",1),a=this.txtTrack=hi("text",1);if(this.id3Track=hi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Yh(e);if(l.video){const{id:A,timescale:u,codec:c,supplemental:h}=l.video;s.id=A,s.timescale=a.timescale=u,s.codec=c,s.supplemental=h}if(l.audio){const{id:A,timescale:u,codec:c}=l.audio;o.id=A,o.timescale=u,o.codec=c}a.id=Uh.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Uy(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Kt(this.remainderData,e));const a=qy(i);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return s.samples=Kh(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=Kh(e,t),{videoTrack:t,audioTrack:hi(),id3Track:n,textTrack:hi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=we(e.samples,["emsg"]);n&&n.forEach(s=>{const o=jy(s);if($B.test(o.schemeIdUri)){const a=df(o,t);let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const A=o.payload;i.samples.push({data:A,len:A.byteLength,dts:a,pts:a,type:Gt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=df(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Gt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function df(r,e){return de(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class YB{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new xl(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,qi.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),o=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)i.set(e.subarray(s,s+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(i.subarray(n,n+16),s);return e}decryptAvcSample(e,t,i,n,s){const o=Wh(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(i>=s.length);i++){const o=s[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class ff{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const s=i.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const s=i[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let l=0,A,u,c,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,l=1);l<n;){if(A=t[l++],!s){s=A?0:1;continue}if(s===1){s=A?0:2;continue}if(!A)s=3;else if(A===1){if(u=l-s-1,h>=0){const f={data:t.subarray(h,u),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(o&&l<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=Kt(f.data,t.subarray(0,u)),f.state=0))}l<n?(c=this.getNALuType(t,l),h=l,d=c,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,n),type:d,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Kt(f.data,t))}return e.naluState=s,a}}class Hn{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(i,i+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}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);const i=this.word>>>32-t;if(e>32&&Oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class gf extends ff{parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 1:{let g=!1;a=!0;const p=A.data;if(l&&p.length>4){const v=this.readSliceType(p);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=g;break}case 5:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,yl(A.data,1,i.pts,t.samples);break}case 7:{var d,f;a=!0,l=!0;const g=A.data,p=this.readSPS(g);if(!e.sps||e.width!==p.width||e.height!==p.height||((d=e.pixelRatio)==null?void 0:d[0])!==p.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let B="avc1.";for(let C=0;C<3;C++){let y=v[C].toString(16);y.length<2&&(y="0"+y),B+=y}e.codec=B}break}case 8:a=!0,e.pps=[A.data];break;case 9:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Hn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(i+s+256)%256),i=n===0?i:n}readSPS(e){const t=new Hn(e);let i=0,n=0,s=0,o=0,a,l,A;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const B=u();if(c(5),f(3),u(),p(),B===100||B===110||B===122||B===244||B===44||B===83||B===86||B===118||B===128){const F=h();if(F===3&&f(1),p(),p(),f(1),d())for(l=F!==3?8:12,A=0;A<l;A++)d()&&(A<6?v(16,t):v(64,t))}p();const C=h();if(C===0)h();else if(C===1)for(f(1),g(),g(),a=h(),A=0;A<a;A++)g();p(),f(1);const y=h(),x=h(),w=c(1);w===0&&f(1),f(1),d()&&(i=h(),n=h(),s=h(),o=h());let D=[1,1];if(d()&&d())switch(u()){case 1:D=[1,1];break;case 2:D=[12,11];break;case 3:D=[10,11];break;case 4:D=[16,11];break;case 5:D=[40,33];break;case 6:D=[24,11];break;case 7:D=[20,11];break;case 8:D=[32,11];break;case 9:D=[80,33];break;case 10:D=[18,11];break;case 11:D=[15,11];break;case 12:D=[64,33];break;case 13:D=[160,99];break;case 14:D=[4,3];break;case 15:D=[3,2];break;case 16:D=[2,1];break;case 255:{D=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((y+1)*16-i*2-n*2),height:(2-w)*(x+1)*16-(w?2:4)*(s+o),pixelRatio:D}}}class pf extends ff{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,yl(A.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=We(e.params,this.readVPS(A.data)),this.initVPS=A.data),e.vps=[A.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],A.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(A.data);e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in d.params)e.params[f]=d.params[f]}this.pushParameterSet(e.sps,A.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(A.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,A.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Hn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new Hn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),A=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),B=[],C=[];for(let ye=0;ye<i;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(i>0)for(let ye=i;ye<8;ye++)t.readBits(2);for(let ye=0;ye<i;ye++)B[ye]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),C[ye]&&t.readUByte();t.readUEG();const y=t.readUEG();y==3&&t.skipBits(1);const x=t.readUEG(),w=t.readUEG(),D=t.readBoolean();let F=0,O=0,M=0,j=0;D&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG());const X=t.readUEG(),le=t.readUEG(),oe=t.readUEG(),L=t.readBoolean();for(let ye=L?0:i;ye<=i;ye++)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 ke=0;ke<4;ke++)for(let Ue=0;Ue<(ke===3?2:6);Ue++)if(!t.readBoolean())t.readUEG();else{const Ge=Math.min(64,1<<4+(ke<<1));ke>1&&t.readEG();for(let $e=0;$e<Ge;$e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const R=t.readUEG();let _=0;for(let ye=0;ye<R;ye++){let ke=!1;if(ye!==0&&(ke=t.readBoolean()),ke){ye===R&&t.readUEG(),t.readBoolean(),t.readUEG();let Ue=0;for(let Xe=0;Xe<=_;Xe++){const Ge=t.readBoolean();let $e=!1;Ge||($e=t.readBoolean()),(Ge||$e)&&Ue++}_=Ue}else{const Ue=t.readUEG(),Xe=t.readUEG();_=Ue+Xe;for(let Ge=0;Ge<Ue;Ge++)t.readUEG(),t.readBoolean();for(let Ge=0;Ge<Xe;Ge++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ye=t.readUEG();for(let ke=0;ke<ye;ke++){for(let Ue=0;Ue<oe+4;Ue++)t.readBits(1);t.readBits(1)}}let K=0,Y=1,te=1,ie=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let _e=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),et=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ot=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ce>0&&Ce<16?(Y=et[Ce-1],te=ot[Ce-1]):Ce===255&&(Y=t.readBits(16),te=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(),_e=t.readBoolean(),_e&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG()),t.readBoolean()&&(he=t.readBits(32),fe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const ot=t.readBoolean(),Ze=t.readBoolean();let ze=!1;(ot||Ze)&&(ze=t.readBoolean(),ze&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ze&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let T=0;T<=i;T++){ie=t.readBoolean();const m=ie||t.readBoolean();let E=!1;m?t.readEG():E=t.readBoolean();const Q=E?1:t.readUEG()+1;if(ot)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),ze&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Ze)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),ze&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Fe=x,pe=w;if(D||_e){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=w-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Ne=a<<24|l<<16|A<<8|u;let Re=0;for(let ye=0;ye<32;ye++)Re=(Re|(Ne>>ye&1)<<31-ye)>>>0;let Ke=Re.toString(16);return o===1&&Ke==="2"&&(Ke="6"),{codecString:`hvc1.${Qe}${o}.${Ke}.${s?"H":"L"}${v}.B0`,params:{general_tier_flag:s,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[a,l,A,u],general_constraint_indicator_flags:[c,h,d,f,g,p],general_level_idc:v,bit_depth:X+8,bit_depth_luma_minus8:X,bit_depth_chroma_minus8:le,min_spatial_segmentation_idc:K,chroma_format_idc:y,frame_rate:{fixed:ie,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,te]}}readPPS(e){const t=new Hn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),s=t.readBoolean();let o=1;return s&&n?o=0:s?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const yt=188;class Ji{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=Ji.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(yt*5,t-yt)+1,n=0;for(;n<i;){let s=!1,o=-1,a=0;for(let l=n;l<t;l+=yt)if(e[l]===71&&(t-l===yt||e[l+yt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+yt*99,e.length-yt)+1)),s||(s=Jl(e,l)===0),s&&a>1&&(o===0&&a>2||l+yt>i))return o}else{if(a)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Uh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ji.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Ji.createTrack("audio",n),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,A=this._txtTrack;let u=o.pid,c=o.pesData,h=a.pid,d=l.pid,f=a.pesData,g=l.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=Kt(this.remainderData,e),C=e.length,this.remainderData=null),C<yt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};const y=Math.max(0,Ji.syncOffset(e));C-=(C-y)%yt,C<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,C,e.buffer.byteLength-C));let x=0;for(let D=y;D<C;D+=yt)if(e[D]===71){const F=!!(e[D+1]&64),O=Jl(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+yt)continue}else j=D+4;switch(O){case u:if(F){if(c&&(s=$r(c,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new gf;break;case"hevc":this.videoParser=new pf;break}this.videoParser!==null&&this.videoParser.parsePES(o,A,s,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(j,D+yt)),c.size+=D+yt-j);break;case h:if(F){if(f&&(s=$r(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(j,D+yt)),f.size+=D+yt-j);break;case d:F&&(g&&(s=$r(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+yt)),g.size+=D+yt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=VB(e,j);break;case B:{F&&(j+=e[j]+1);const X=KB(e,j,this.typeSupported,i,this.observer,this.logger);u=X.videoPid,u>0&&(o.pid=u,o.segmentCodec=X.segmentVideoCodec),h=X.audioPid,h>0&&(a.pid=h,a.segmentCodec=X.segmentAudioCodec),d=X.id3Pid,d>0&&(l.pid=d),p!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${p}'. Backtracking to sync byte @${y} to parse all TS packets.`),p=null,D=y-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=O;break}}else x++;x>0&&jl(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=c,a.pesData=f,l.pesData=g;const w={audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};return n&&this.extractRemainingSamples(w),w}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:s}=e,o=i.pesData,a=t.pesData,l=n.pesData;let A;if(o&&(A=$r(o,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new gf;break;case"hevc":this.videoParser=new pf;break}this.videoParser!==null&&(this.videoParser.parsePES(i,s,A,!0),i.pesData=null)}else i.pesData=o;if(a&&(A=$r(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,A);break;case"mp3":this.parseMPEGPES(t,A);break;case"ac3":this.parseAC3PES(t,A);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(A=$r(l,this.logger))?(this.parseID3PES(n,A),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new YB(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const c=n.missing,h=n.sample.unit.byteLength;if(c===-1)s=Kt(n.sample.unit,s);else{const d=h-c;n.sample.unit.set(s.subarray(0,c),d),e.samples.push(n.sample),i=n.missing}}let o,a;for(o=i,a=s.length;o<a-1&&!Bo(s,o);o++);if(o!==i){let c;const h=o<a-1;if(h?c=`AAC PES did not start with ADTS header,offset:${o}`:c="No ADTS header found in AAC PES",jl(this.observer,new Error(c),h,this.logger),!h)return}ef(e,this.observer,s,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const c=tf(e.samplerate);l=n.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let A=0,u;for(;o<a;)if(u=rf(e,s,o,l,A),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(A++;o<a-1&&!Bo(s,o);o++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let s=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(Af(i,o)){const l=af(e,i,o,a,s);if(l)o+=l.length,s++;else break}else o++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=i.length;let o=0,a=0,l;for(;a<s&&(l=hf(e,i,a,n,o++))>0;)a+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=We({},t,{type:this._videoTrack?Gt.emsg:Gt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Jl(r,e){return((r[e+1]&31)<<8)+r[e+2]}function VB(r,e){return(r[e+10]&31)<<8|r[e+11]}function KB(r,e,t,i,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(r[e+1]&15)<<8|r[e+2],l=e+3+a-4,A=(r[e+10]&15)<<8|r[e+11];for(e+=12+A;e<l;){const u=Jl(r,e),c=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){Xl("ADTS AAC",s);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!i){Xl("H.264",s);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?s.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!i){Xl("AC-3",s);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&c>0){let h=e+5,d=c;for(;d>2;){switch(r[h]){case 106:t.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const g=r[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return jl(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=c+5}return o}function jl(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Xl(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function $r(r,e){let t=0,i,n,s,o,a;const l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Kt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>r.size-6)return null;const u=i[7];u&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(a=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-a>54e5&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),s=i[8];let c=s+9;if(r.size<=c)return null;r.size-=c;const h=new Uint8Array(r.size);for(let d=0,f=l.length;d<f;d++){i=l[d];let g=i.byteLength;if(c)if(c>g){c-=g;continue}else i=i.subarray(c),g-=c,c=0;h.set(i,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class WB{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}}}const ji=Math.pow(2,32)-1;class H{static init(){H.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in H.types)H.types.hasOwnProperty(e)&&(H.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);H.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);H.STTS=H.STSC=H.STCO=s,H.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),H.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),H.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),H.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);H.FTYP=H.box(H.types.ftyp,o,l,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let i=8,n=t.length;const s=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n<s;n++)o.set(t[n],i),i+=t[n].byteLength;return o}static hdlr(e){return H.box(H.types.hdlr,H.HDLR_TYPES[e])}static mdat(e){return H.box(H.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(ji+1)),n=Math.floor(t%(ji+1));return H.box(H.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return H.box(H.types.mdia,H.mdhd(e.timescale||0,e.duration||0),H.hdlr(e.type),H.minf(e))}static mfhd(e){return H.box(H.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?H.box(H.types.minf,H.box(H.types.smhd,H.SMHD),H.DINF,H.stbl(e)):H.box(H.types.minf,H.box(H.types.vmhd,H.VMHD),H.DINF,H.stbl(e))}static moof(e,t,i){return H.box(H.types.moof,H.mfhd(e),H.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(H.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(ji+1)),n=Math.floor(t%(ji+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return H.box(H.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,i[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,i)}static stbl(e){return H.box(H.types.stbl,H.stsd(e),H.box(H.types.stts,H.STTS),H.box(H.types.stsc,H.STSC),H.box(H.types.stsz,H.STSZ),H.box(H.types.stco,H.STCO))}static avc1(e){let t=[],i=[],n,s,o;for(n=0;n<e.sps.length;n++)s=e.sps[n],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(n=0;n<e.pps.length;n++)s=e.pps[n],o=s.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(s));const a=H.box(H.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,A=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return H.box(H.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,A>>8&255,A&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]),a,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.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){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||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 H.box(H.types.mp4a,H.audioStsd(e),H.box(H.types.esds,H.esds(e)))}static mp3(e){return H.box(H.types[".mp3"],H.audioStsd(e))}static ac3(e){return H.box(H.types["ac-3"],H.audioStsd(e),H.box(H.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return H.box(H.types.stsd,H.STSD,H.mp4a(e));if(t==="ac3"&&e.config)return H.box(H.types.stsd,H.STSD,H.ac3(e));if(t==="mp3"&&e.codec==="mp3")return H.box(H.types.stsd,H.STSD,H.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return H.box(H.types.stsd,H.STSD,H.avc1(e));if(t==="hevc"&&e.vps)return H.box(H.types.stsd,H.STSD,H.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){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(i/(ji+1)),a=Math.floor(i%(ji+1));return H.box(H.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,t){const i=H.sdtp(e),n=e.id,s=Math.floor(t/(ji+1)),o=Math.floor(t%(ji+1));return H.box(H.types.traf,H.box(H.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),H.box(H.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),H.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,H.box(H.types.trak,H.tkhd(e),H.mdia(e))}static trex(e){const t=e.id;return H.box(H.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,s=12+16*n,o=new Uint8Array(s);let a,l,A,u,c,h;for(t+=8+s,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<n;a++)l=i[a],A=l.duration,u=l.size,c=l.flags,h=l.cts,o.set([A>>>24&255,A>>>16&255,A>>>8&255,A&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*a);return H.box(H.types.trun,o)}static initSegment(e){H.types||H.init();const t=H.moov(e);return Kt(H.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,s=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),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=s.length;for(let f=0;f<i.length;f+=1){o+=3;for(let g=0;g<i[f].length;g+=1)o+=2+i[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){a.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),o),o+=3;for(let g=0;g<i[f].length;g+=1)a.set(new Uint8Array([i[f][g].length>>8,i[f][g].length&255]),o),o+=2,a.set(i[f][g],o),o+=i[f][g].length}const A=H.box(H.types.hvcC,a),u=e.width,c=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return H.box(H.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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]),A,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}}H.types=void 0,H.HDLR_TYPES=void 0,H.STTS=void 0,H.STSC=void 0,H.STCO=void 0,H.STSZ=void 0,H.VMHD=void 0,H.SMHD=void 0,H.STSD=void 0,H.FTYP=void 0,H.DINF=void 0;const mf=9e4;function zl(r,e,t=1,i=!1){const n=r*e*t;return i?Math.round(n):n}function qB(r,e,t=1,i=!1){return zl(r,e,1/t,i)}function Yn(r,e=!1){return zl(r,1e3,1/mf,e)}function JB(r,e=1){return zl(r,mf,1/e)}const jB=10*1e3,XB=1024,zB=1152,ZB=1536;let Hr=null,Zl=null;function Ef(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class bo{constructor(e,t,i,n){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.ISGenerated=!1,Hr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Hr=o?parseInt(o[1]):0}if(Zl===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Zl=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,l=a-s;return l<-4294967296&&(t=!0,a=Wt(a,i),l=a-s),l>0?s:a},i);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,i,n,s,o,a,l){let A,u,c,h,d,f,g=s,p=s;const v=e.pid>-1,B=t.pid>-1,C=t.samples.length,y=e.samples.length>0,x=a&&C>0||C>1;if((!v||y)&&(!B||x)||this.ISGenerated||a){if(this.ISGenerated){var D,F,O,M;const oe=this.videoTrackConfig;(oe&&(t.width!==oe.width||t.height!==oe.height||((D=t.pixelRatio)==null?void 0:D[0])!==((F=oe.pixelRatio)==null?void 0:F[0])||((O=t.pixelRatio)==null?void 0:O[1])!==((M=oe.pixelRatio)==null?void 0:M[1]))||!oe&&x||this.nextAudioPts===null&&y)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=eT(t.samples),!j&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,X>0){this.logger.warn(`[mp4-remuxer]: Dropped ${X} out of ${C} video samples due to a missing keyframe`);const oe=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(X),t.dropped+=X,p+=(t.samples[0].pts-oe)/t.inputTimeScale,le=p}else X===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${C} video samples`),f=!1);if(this.ISGenerated){if(y&&x){const oe=this.getVideoStartPts(t.samples),U=(Wt(e.samples[0].pts,oe)-oe)/t.inputTimeScale;g+=Math.max(0,U),p+=Math.max(0,-U)}if(y){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||l===Ee.AUDIO?p:void 0),x){const oe=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,o)),A=this.remuxVideo(t,p,j,oe)}}else x&&(A=this.remuxVideo(t,p,j,0));A&&(A.firstKeyFrame=X,A.independent=X!==-1,A.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=If(i,s,this._initPTS,this._initDTS)),n.samples.length&&(h=vf(n,s,this._initPTS))),{audio:u,video:A,initSegment:c,independent:f,text:h,id3:d}}generateIS(e,t,i,n){const s=e.samples,o=t.samples,a=this.typeSupported,l={},A=this._initPTS;let u=!A||n,c="audio/mp4",h,d,f;if(u&&(h=d=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!A||f!==A.timescale?h=d=s[0].pts-Math.round(f*i):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:H.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(f=t.inputTimeScale,!A||f!==A.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*i);d=Math.min(d,Wt(o[0].dts,g)-p),h=Math.min(h,g-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:l,initPTS:h,timescale:f}}remuxVideo(e,t,i,n){const s=e.inputTimeScale,o=e.samples,a=[],l=o.length,A=this._initPTS;let u=this.nextAvcDts,c=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const _=t*s,k=o[0].pts-Wt(o[0].dts,o[0].pts);Hr&&u!==null&&Math.abs(_-k-u)<15e3?i=!0:u=_-k}const B=A.baseTime*s/A.timescale;for(let _=0;_<l;_++){const k=o[_];k.pts=Wt(k.pts-B,u),k.dts=Wt(k.dts-B,u),k.dts<o[_>0?_-1:_].dts&&(v=!0)}v&&o.sort(function(_,k){const K=_.dts-k.dts,Y=_.pts-k.pts;return K||Y}),d=o[0].dts,f=o[o.length-1].dts;const C=f-d,y=C?Math.round(C/(l-1)):h||e.inputTimeScale/30;if(i){const _=d-u,k=_>y,K=_<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yn(_,!0)} ms (${_}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yn(-_,!0)} ms (${_}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Hr)){d=u;const Y=o[0].pts-_;if(k)o[0].dts=d,o[0].pts=Y;else{let te=!0;for(let ie=0;ie<o.length&&!(o[ie].dts>Y&&te);ie++){const he=o[ie].pts;if(o[ie].dts-=_,o[ie].pts-=_,ie<o.length-1){const fe=o[ie+1].pts,_e=o[ie].pts,Te=fe<=_e,Fe=fe<=he;te=Te==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${Yn(Y,!0)}/${Yn(d,!0)}, delta: ${Yn(_,!0)} ms`)}}d=Math.max(0,d);let x=0,w=0,D=d;for(let _=0;_<l;_++){const k=o[_],K=k.units,Y=K.length;let te=0;for(let ie=0;ie<Y;ie++)te+=K[ie].data.length;w+=te,x+=Y,k.length=te,k.dts<D?(k.dts=D,D+=y/4|0||1):D=k.dts,g=Math.min(k.pts,g),p=Math.max(k.pts,p)}f=o[l-1].dts;const F=w+4*x+8;let O;try{O=new Uint8Array(F)}catch(_){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:_,bytes:F,reason:`fail allocating video mdat ${F}`});return}const M=new DataView(O.buffer);M.setUint32(0,F),O.set(H.types.mdat,4);let j=!1,X=Number.POSITIVE_INFINITY,le=Number.POSITIVE_INFINITY,oe=Number.NEGATIVE_INFINITY,L=Number.NEGATIVE_INFINITY;for(let _=0;_<l;_++){const k=o[_],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const _e=K[he],Te=_e.data,Fe=_e.data.byteLength;M.setUint32(c,Fe),c+=4,O.set(Te,c),c+=Fe,Y+=4+Fe}let te;if(_<l-1)h=o[_+1].dts-k.dts,te=o[_+1].pts-k.pts;else{const he=this.config,fe=_>0?k.dts-o[_-1].dts:y;if(te=_>0?k.pts-o[_-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const _e=Math.floor(he.maxBufferHole*s),Te=(n?g+n*s:this.nextAudioPts)-k.pts;Te>_e?(h=Te-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${Te/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const ie=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,te),L=Math.max(L,te),a.push(Ef(k.key,h,Y,ie))}if(a.length){if(Hr){if(Hr<70){const _=a[0].flags;_.dependsOn=2,_.isNonSync=0}}else if(Zl&&L-le<oe-X&&y/oe<.025&&a[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let _=d;for(let k=0,K=a.length;k<K;k++){const Y=_+a[k].duration,te=_+a[k].cts;if(k<K-1){const ie=Y+a[k+1].cts;a[k].duration=ie-te}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,_=Y}}}h=j||!h?y:h,this.nextAvcDts=u=f+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;const R={data1:H.moof(e.sequenceNumber++,d,We(e,{samples:a})),data2:O,startPTS:g/s,endPTS:(p+h)/s,startDTS:d/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,R}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return zB;case"ac3":return ZB;default:return XB}}remuxAudio(e,t,i,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,A=this.getSamplesPerFrame(e),u=A*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=s!==void 0;let g=e.samples,p=h?0:8,v=this.nextAudioPts||-1;const B=t*o,C=c.baseTime*o/c.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(Wt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=Wt(U.pts-C,B)}),!i||v<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;s===0?v=0:n&&!f?v=Math.max(0,B):v=g[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let q=0,R=v;q<g.length;q++){const _=g[q],k=_.pts,K=k-R,Y=Math.abs(1e3*K/o);if(K<=-U*u&&f)q===0&&(this.logger.warn(`Audio frame @ ${(k/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*K/o)} ms.`),this.nextAudioPts=v=R=k);else if(K>=U*u&&Y<jB&&f){let te=Math.round(K/u);R=k-te*u,R<0&&(te--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${te} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let ie=0;ie<te;ie++){const he=Math.max(R,0);let fe=WB.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);fe||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),fe=_.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}_.pts=R,R+=u}}let y=null,x=null,w,D=0,F=g.length;for(;F--;)D+=g[F].unit.byteLength;for(let U=0,q=g.length;U<q;U++){const R=g[U],_=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/l)}else if(i&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{w=new Uint8Array(D)}catch(Y){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:D,reason:`fail allocating audio mdat ${D}`});return}h||(new DataView(w.buffer).setUint32(0,D),w.set(H.types.mdat,4))}else return;w.set(_,p);const K=_.byteLength;p+=K,d.push(Ef(!0,A,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+l*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/l,We({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:w,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function Wt(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function eT(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function If(r,e,t,i){const n=r.samples.length;if(!n)return;const s=r.inputTimeScale;for(let a=0;a<n;a++){const l=r.samples[a];l.pts=Wt(l.pts-t.baseTime*s/t.timescale,e*s)/s,l.dts=Wt(l.dts-i.baseTime*s/i.timescale,e*s)/s}const o=r.samples;return r.samples=[],{samples:o}}function vf(r,e,t){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=Wt(a.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((o,a)=>o.pts-a.pts);const s=r.samples;return r.samples=[],{samples:s}}class tT{constructor(e,t,i,n){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=n}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Hy(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=Yh(e);n.audio&&(t=yf(n.audio,qe.AUDIO)),n.video&&(i=yf(n.video,qe.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,n,s,o){var a,l;let{initPTS:A,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((l=f)!=null&&l.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=Vy(h,f),p=Yy(f,h),v=p===null?s:p;(o||!A)&&(iT(A,v,s,g)||d.timescale!==A.timescale)&&(d.initPTS=v-s,A&&A.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${A.baseTime/A.timescale} to ${d.initPTS}`),this.initPTS=A={baseTime:d.initPTS,timescale:1});const B=e?v-A.baseTime/A.timescale:u,C=B+g;Wy(f,h,A.baseTime/A.timescale),g>0?this.lastEndTime=C:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!f.audio,x=!!f.video;let w="";y&&(w+="audio"),x&&(w+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:w,hasAudio:y,hasVideo:x,nb:1,dropped:0};return c.audio=D.type==="audio"?D:void 0,c.video=D.type!=="audio"?D:void 0,c.initSegment=d,c.id3=If(i,s,A,A),n.samples.length&&(c.text=vf(n,s,A)),c}}function iT(r,e,t,i){if(r===null)return!0;const n=Math.max(i,1),s=e-r.baseTime/r.timescale;return Math.abs(s-t)>n}function yf(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===qe.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?ao(t,!1):(Oe.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(Oe.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let xi;try{xi=self.performance.now.bind(self.performance)}catch{xi=Date.now}const xo=[{demux:HB,remux:tT},{demux:Ji,remux:bo},{demux:OB,remux:bo},{demux:GB,remux:bo}];xo.splice(2,0,{demux:UB,remux:bo});class Cf{constructor(e,t,i,n,s,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const s=i.transmuxing;s.executeStart=xi();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:A,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=l,y=rT(o,t);if(y&&Ur(y.method)){const F=this.getDecrypter(),O=wl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(i.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=xi(),eA(i);o=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=F.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer,O).then(M=>{const j=this.push(M,null,i);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,c);if(x){const F=this.configureTransmuxer(o);if(F)return this.logger.warn(`[transmuxer] ${F.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:F,reason:F.message}),s.executeEnd=xi(),eA(i)}(u||c||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),A||this.resetContiguity();const w=this.transmux(o,y,d,h,i);this.asyncResult=Vn(w);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=xi(),w}flush(e){const t=e.transmuxing;t.executeStart=xi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(i){const c=i.flush();c&&o.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:A}=this;if(!l||!A){t.executeEnd=xi();const c=[eA(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(a);return Vn(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(o,c,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:A}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${i.level}`);const u=this.remuxer.remux(n,s,o,a,A,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=xi()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,n),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,s):o=this.transmuxUnencrypted(e,i,n,s),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,s){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let s;for(let c=0,h=xo.length;c<h;c++){var o;if((o=xo[c].demux)!=null&&o.probe(e,this.logger)){s=xo[c];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,A=s.remux,u=s.demux;(!l||!(l instanceof A))&&(this.remuxer=new A(i,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(i,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new xl(this.config)),e}}function rT(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const eA=r=>({remuxResult:{},chunkMeta:r});function Vn(r){return"then"in r&&r.then instanceof Function}class nT{constructor(e,t,i,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=s||null}}class sT{constructor(e,t,i,n,s,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}}let Bf=0;class Tf{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Bf++,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=>{const A=l.data,u=this.hls;if(!(!u||!(A!=null&&A.event)||A.instanceNo!==this.instanceNo))switch(A.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(A.data);break}case"flush":{this.onFlush(A.data);break}case"workerLog":{u.logger[A.data.logType]&&u.logger[A.data.logType](A.data.message);break}default:{A.data=A.data||{},A.data.frag=this.frag,A.data.part=this.part,A.data.id=this.id,u.trigger(A.event,A.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const A=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(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:A})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(l,A)=>{A=A||{},A.frag=this.frag||void 0,l===I.ERROR&&(A=A,A.parent=this.id,A.part=this.part,this.error=A.error),this.hls.trigger(l,A)};this.observer=new $l,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=zh(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||lB()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=cB(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=AB());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:it(s)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Cf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new Cf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Bf++;const t=this.hls.config,i=zh(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),uB(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,s,o,a,l,A,u){var c,h;A.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=o?o.start:s.start,p=s.decryptdata,v=this.frag,B=!(v&&s.cc===v.cc),C=!(v&&A.level===v.level),y=v?A.sn-v.sn:-1,x=this.part?A.part-this.part.index:-1,w=y===0&&A.id>1&&A.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||w&&x<=0)),F=self.performance.now();(C||y||s.stats.parsing.start===0)&&(s.stats.parsing.start=F),o&&(x||!D)&&(o.stats.parsing.start=F);const O=!(v&&((c=s.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),M=new sT(B,D,l,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${A.sn}${A.part>-1?" part: "+A.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${A.level} id: ${A.id}
2500
+ ${t.m3u8}`)}function Od(r,e,t=!0){const i=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,s=i>=0;let o=0;if(s&&i<n.length)o=n[i].start;else if(s&&e.startSN===r.endSN+1)o=r.fragmentEnd;else if(s&&t)o=r.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart;else return;Ol(e,o)}function Ol(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Ud(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const s=i[i.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function Gd(r,e,t){if(!r)return null;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e)?i:e<r.startSN&&t&&t.sn===e?t:null}function $d(r,e,t){return r?Hd(r.partList,e,t):null}function Hd(r,e,t){if(r)for(let i=r.length;i--;){const n=r[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function Yd(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Un(r,e){for(let i=0,n=r.length;i<n;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function iB(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Vd(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Kd(r,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Vd(t[i],r);e.fragmentHint&&Vd(e.fragmentHint,r),e.alignedSliding=!0}function rB(r,e){r&&(Wd(e,r),!e.alignedSliding&&r&&yo(e,r),!e.alignedSliding&&r&&!e.skippedSegments&&Od(r,e,!1))}function Wd(r,e){if(!iB(e,r))return;const t=Math.min(e.endCC,r.endCC),i=Un(e.fragments,t),n=Un(r.fragments,t);if(!i||!n)return;Oe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=i.start-n.start;Kd(s,r)}function yo(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,s;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Un(i,o),s=Un(t,o)),(!n||!s)&&(n=i[Math.floor(i.length/2)],s=Un(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,l=s.programDateTime;if(!a||!l)return;const A=(l-a)/1e3-(s.start-n.start);Kd(A,r)}const nB={toString:function(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}},Z={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Ul extends Ed{constructor(e,t,i,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Z.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:a,media:l,mediaBuffer:A,state:u}=this,c=l?l.currentTime:0,h=Le.bufferInfo(A||l,c,o.maxBufferHole);if(this.log(`media seeking to ${de(c)?c.toFixed(3):c}, state: ${u}`),this.state===Z.ENDED)this.resetLoadingState();else if(a){const d=o.maxFragLookUpTolerance,f=a.start-d,g=a.start+a.duration+d;if(!h.len||g<h.start||f>h.end){const p=c>g;(c<f||p)&&(p&&a.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(c>d&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${c} because of seek before start`),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new DC(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new xl(e.config)}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Z.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=Z.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const s=e.nextStart;if(s&&s>n&&s<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const A=a[a.length-1];return Le.isBuffered(this.media,A.start+A.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),n.removeEventListener("seeking",this.onMediaSeeking),n.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Z.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=s=>{const o=s.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(o,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,i,n).then(s=>{if(!s)return;const o=this.state,a=s.frag;if(this.fragContextChanged(a)){(o===Z.FRAG_LOADING||!this.fragCurrent&&o===Z.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=Z.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(I.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Et.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Et.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:s,payload:o}=i,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Ur(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,wl(a.method)).catch(A=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:A,reason:A.message,frag:s}),A}).then(A=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:A,stats:{tstart:l,tdecrypt:u}}),i.payload=A,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?nB.toString(Le.getBuffered(i)):"(detached)"})`),vt(e)){var n;if(e.type!==Ee.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=Z.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Z.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(l=>!l),a=new Ql(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var s;this.fragCurrent=e;const o=t==null?void 0:t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Z.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(I.KEY_LOADED,c),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),c}),this.hls.trigger(I.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments);const l=this.fragPrevious;if(vt(e)&&(!l||e.sn!==l.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=c)}if(i=Math.max(e.start,i||0),this.loadingParts&&vt(e)){const c=o.partList;if(c&&n){i>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(c,e,i);if(h>-1){const d=c[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${c.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=Z.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,n)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}if(vt(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${o?"["+o.startSN+"-"+o.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const A=this.config.progressive;let u;return A&&a?u=a.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,n)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,A?n:void 0),a]).then(([c])=>(!A&&c&&n&&n(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((s,o)=>{var a;const l=[],A=(a=i.details)==null?void 0:a.partList,u=c=>{this.fragmentLoader.loadPart(e,c,n).then(h=>{l[c.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=$d(i.details,e.sn,c.index+1)||Hd(A,e.sn,c.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:l})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===V.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Z.PARSING){!this.fragCurrent&&this.state!==Z.STOPPED&&this.state!==Z.ERROR&&(this.state=Z.IDLE);return}const{frag:i,part:n,level:s}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),A=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=A),this.updateLevelTiming(i,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var i;const s=e.partList[0],o=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:s,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],l=a.details,A=o>-1?$d(l,s,o):null,u=A?A.fragment:Gd(l,s,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:A,level:a}):null}bufferFragmentData(e,t,i,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:l}=e;let A=a;if(a&&l&&(A=Kt(a,l)),!((o=A)!=null&&o.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:A};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Le.bufferInfo(t,i,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(s.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(s.nextStart,o.end)-t,n);return Le.bufferInfo(e,t,a)}}return s}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return s>=n?(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var i;const n=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:s}=this,o=i[0].start,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=s.initialLiveManifestSize;if(n<c)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var A;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t,i);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=l?(h!==-1&&h>=o?h:d)||l.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(A=l)==null?void 0:A.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(l=i[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Et.OK||i===Et.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(a!==null&&i.len+a.len>=s){const l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(qd(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(qd(this.hls.config)&&e.type!==Ee.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=i==null?void 0:i.playerQueue;if(s)for(let o=s.length;o--;){const a=s[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,s=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const A=e[a];if(o=o&&!A.independent,n>-1&&i<A.start)break;const u=A.loaded;u?n=-1:(s||A.independent||o)&&A.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=IC(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=ud(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:A}=n,u=i.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&l&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-A||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:A;h=Ir(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-i.startSN,g=this.fragmentTracker.getState(h);if((g===Et.OK||g===Et.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!c||u[0].fragment.sn>h.sn||!i.live&&!c)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==Et.OK?h=v:h=null}}return h}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,o=!t,a=e.alignedSliding&&de(s);if(o||!a&&!s){rB(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(i=t+o,o<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&vt(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Z.FRAG_LOADING_WAITING_RETRY)&&(this.state=Z.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const f=this.getCurrentContext(t.chunkMeta);f&&(t.frag=f.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction,{action:a,flags:l,retryCount:A=0,retryConfig:u}=o||{},c=!!o&&!!u,h=c&&a===wt.RetryRequest,d=c&&!o.resolved&&l===ei.MoveAllAlternatesMatchingHost;if(!h&&d&&vt(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((h||d)&&A<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=bl(u,A);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${A+1}/${u.maxNumRetry} in ${f}ms`),o.resolved=!0,this.retryDate=self.performance.now()+f,this.state=Z.FRAG_LOADING_WAITING_RETRY}else if(u&&o)if(this.resetFragmentErrors(e),A<u.maxNumRetry)!s&&a!==wt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${A})`);return}else a===wt.SendAlternateToPenaltyBox?this.state=Z.WAITING_LEVEL:this.state=Z.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Z.PARSING||this.state===Z.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!s;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===Ee.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Z.STOPPED&&(this.state=Z.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Z.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const s=i.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,A)=>{const u=e.elementaryStreams[A];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${A} duration reliably (${c})`),l||!1;const h=n?0:Pd(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:A,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var a;if(i.fragmentError===0&&this.treatAsGap(e,i),((a=this.transmuxer)==null?void 0:a.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Z.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Ee.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!i?e.endPTS:(i||e).end)!=null?s:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function qd(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Jd{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=sB(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function sB(r,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<r.length;n++){const s=r[n];t.set(s,i),i+=s.length}return t}var Gl={exports:{}},jd;function oB(){return jd||(jd=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,A,u){this.fn=l,this.context=A,this.once=u||!1}function s(l,A,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,c||l,h),f=t?t+A:A;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],d]:l._events[f].push(d):(l._events[f]=d,l._eventsCount++),l}function o(l,A){--l._eventsCount===0?l._events=new i:delete l._events[A]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var A=[],u,c;if(this._eventsCount===0)return A;for(c in u=this._events)e.call(u,c)&&A.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(u)):A},a.prototype.listeners=function(A){var u=t?t+A:A,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,d=c.length,f=new Array(d);h<d;h++)f[h]=c[h].fn;return f},a.prototype.listenerCount=function(A){var u=t?t+A:A,c=this._events[u];return c?c.fn?1:c.length:0},a.prototype.emit=function(A,u,c,h,d,f){var g=t?t+A:A;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(A,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,c),!0;case 4:return p.fn.call(p.context,u,c,h),!0;case 5:return p.fn.call(p.context,u,c,h,d),!0;case 6:return p.fn.call(p.context,u,c,h,d,f),!0}for(C=1,B=new Array(v-1);C<v;C++)B[C-1]=arguments[C];p.fn.apply(p.context,B)}else{var y=p.length,x;for(C=0;C<y;C++)switch(p[C].once&&this.removeListener(A,p[C].fn,void 0,!0),v){case 1:p[C].fn.call(p[C].context);break;case 2:p[C].fn.call(p[C].context,u);break;case 3:p[C].fn.call(p[C].context,u,c);break;case 4:p[C].fn.call(p[C].context,u,c,h);break;default:if(!B)for(x=1,B=new Array(v-1);x<v;x++)B[x-1]=arguments[x];p[C].fn.apply(p[C].context,B)}}return!0},a.prototype.on=function(A,u,c){return s(this,A,u,c,!1)},a.prototype.once=function(A,u,c){return s(this,A,u,c,!0)},a.prototype.removeListener=function(A,u,c,h){var d=t?t+A:A;if(!this._events[d])return this;if(!u)return o(this,d),this;var f=this._events[d];if(f.fn)f.fn===u&&(!h||f.once)&&(!c||f.context===c)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||c&&f[g].context!==c)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(A){var u;return A?(u=t?t+A:A,this._events[u]&&o(this,u)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a}(Gl)),Gl.exports}var aB=oB(),$l=My(aB);const Gn="1.6.2",Gr={};function lB(){return typeof __HLS_WORKER_BUNDLE__=="function"}function AB(){const r=Gr[Gn];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return Gr[Gn]=n,n}function cB(r){const e=Gr[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Gr[r]=n,n}function uB(r){const e=Gr[r||Gn];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete Gr[r||Gn],n&&self.URL.revokeObjectURL(n),i.terminate()}}function Xd(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Hl(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Co(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function $n(r,e){const t=e;let i=0;for(;Hl(r,e);){i+=10;const n=Co(r,e+6);i+=n,Xd(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function hB(r,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[t+2],o=s>>2&15;if(o>12){const d=new Error(`invalid ADTS sampling index:${o}`);r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}const a=(s>>6&3)+1,l=e[t+3]>>6&3|(s&1)<<2,A="mp4a.40."+a,u=n[o];let c=o;(a===5||a===29)&&(c-=3);const h=[a<<3|(c&14)>>1,(c&1)<<7|l<<3];return Oe.log(`manifest codec:${i}, parsed codec:${A}, channels:${l}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:l,codec:A,parsedCodec:A,manifestCodec:i}}function zd(r,e){return r[e]===255&&(r[e+1]&246)===240}function Zd(r,e){return r[e+1]&1?7:9}function Yl(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function dB(r,e){return e+5<r.length}function Bo(r,e){return e+1<r.length&&zd(r,e)}function fB(r,e){return dB(r,e)&&zd(r,e)&&Yl(r,e)<=r.length-e}function gB(r,e){if(Bo(r,e)){const t=Zd(r,e);if(e+t>=r.length)return!1;const i=Yl(r,e);if(i<=t)return!1;const n=e+i;return n===r.length||Bo(r,n)}return!1}function ef(r,e,t,i,n){if(!r.samplerate){const s=hB(e,t,i,n);if(!s)return;We(r,s)}}function tf(r){return 9216e4/r}function pB(r,e){const t=Zd(r,e);if(e+t<=r.length){const i=Yl(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function rf(r,e,t,i,n){const s=tf(r.samplerate),o=i+n*s,a=pB(e,t);let l;if(a){const{frameLength:c,headerLength:h}=a,d=h+c,f=Math.max(0,t+d-e.length);f?(l=new Uint8Array(d-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+d);const g={unit:l,pts:o};return f||r.samples.push(g),{sample:g,length:d,missing:f}}const A=e.length-t;return l=new Uint8Array(A),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:A,missing:-1}}function mB(r,e){return Hl(r,e)&&Co(r,e+6)+10<=r.length-e}function EB(r){if(r.size<2)return;const e=Ut(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function IB(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=Ut(r.data.subarray(t),!0);t+=i.length+1;const n=Ut(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=Ut(r.data.subarray(1));return{key:r.type,info:"",data:e}}function vB(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=Ut(r.data.subarray(t),!0);t+=i.length+1;const n=Ut(r.data.subarray(t));return{key:r.type,info:i,data:n}}const e=Ut(r.data);return{key:r.type,info:"",data:e}}function yB(r){return btoa(String.fromCharCode(...r))}function nf(r,e){if(r<0)return-nf(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const n=Math.floor(r*t);return(n%2===0?n:n+1)/t}else return Math.round(r*t)/t}function CB(r,e){const t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;const n=t.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1);for(;n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}function BB(){try{return crypto.randomUUID()}catch{try{const 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,n=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?s:s&3|8).toString(16)})}}}function TB(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Vl(r,e=0,t=1/0){return SB(r,e,t,Uint8Array)}function SB(r,e,t,i){const n=bB(r);let s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);const o=xB(r)?r.byteOffset:0,a=(o+r.byteLength)/s,l=(o+e)/s,A=Math.floor(Math.max(0,Math.min(l,a))),u=Math.floor(Math.min(A+Math.max(t,0),a));return new i(n,A,u-A)}function bB(r){return r instanceof ArrayBuffer?r:r.buffer}function xB(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function QB(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const n=Ut(Vl(r.data,1,i)),s=r.data[2+i],o=r.data.subarray(3+i).indexOf(0);if(o===-1)return;const a=Ut(Vl(r.data,3+i,o));let l;return n==="-->"?l=Ut(Vl(r.data,4+i+o)):l=TB(r.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=l,e}function _B(r){return r.type==="PRIV"?EB(r):r.type[0]==="W"?vB(r):r.type==="APIC"?QB(r):IB(r)}function wB(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Co(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const To=10,RB=10;function sf(r){let e=0;const t=[];for(;Hl(r,e);){const i=Co(r,e+6);r[e+5]>>6&1&&(e+=To),e+=To;const n=e+i;for(;e+RB<n;){const s=wB(r.subarray(e)),o=_B(s);o&&t.push(o),e+=s.size+To}Xd(r,e)&&(e+=To)}return t}function of(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function DB(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Kl(r){const e=sf(r);for(let t=0;t<e.length;t++){const i=e[t];if(of(i))return DB(i)}}let Gt=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function hi(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Wl{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Kt(this.cachedData,e),this.cachedData=null);let i=$n(e,0),n=i?i.length:0,s;const o=this._audioTrack,a=this._id3Track,l=i?Kl(i):void 0,A=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=LB(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Gt.audioId3,duration:Number.POSITIVE_INFINITY});n<A;){if(this.canParse(e,n)){const u=this.appendFrame(o,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,n+=u.length,s=n):n=A}else mB(e,n)?(i=$n(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Gt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,s=n):n++;if(n===A&&s!==A){const u=e.slice(s);this.cachedData?this.cachedData=Kt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:hi(),id3Track:a,textTrack:hi()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:hi(),id3Track:this._id3Track,textTrack:hi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const LB=(r,e,t)=>{if(de(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let So=null;const kB=[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],MB=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],FB=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],PB=[0,1,1,4];function af(r,e,t,i,n){if(t+24>e.length)return;const s=lf(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=i+n*o,l={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=s.channelCount,r.samplerate=s.sampleRate,r.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function lf(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,n=r[e+2]>>4&15,s=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,l=t===3?3-i:i===3?3:4,A=kB[l*14+n-1]*1e3,c=MB[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=FB[t][i],f=PB[i],g=d*8*f,p=Math.floor(d*A/c+o)*f;if(So===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);So=C?parseInt(C[1]):0}return!!So&&So<=87&&i===2&&A>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:c,channelCount:h,frameLength:p,samplesPerFrame:g}}}function ql(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Af(r,e){return e+1<r.length&&ql(r,e)}function NB(r,e){return ql(r,e)&&4<=r.length-e}function cf(r,e){if(e+1<r.length&&ql(r,e)){const i=lf(r,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const s=e+n;return s===r.length||Af(r,s)}return!1}class OB extends Wl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=$n(e,0);let n=(i==null?void 0:i.length)||0;if(cf(e,n))return!1;for(let s=e.length;n<s;n++)if(gB(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return fB(e,t)}appendFrame(e,t,i){ef(e,this.observer,t,i,e.manifestCodec);const n=rf(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const uf=(r,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=r[e];const a=Math.min(i,8),l=8-a;s[0]=4278190080>>>24+l<<l,n[0]=(o[0]&s[0])>>l,t=t?t<<a|n[0]:n[0],e+=1,i-=a}return t};class UB extends Wl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=hf(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=$n(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&Kl(t)!==void 0&&uf(e,i)<16}}function hf(r,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const s=e[t+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],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+s]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][c]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|c<<3|d<<2|l>>4,l<<4&224]),C=1536/a*9e4,y=i+n*C,x=e.subarray(t,t+u);return r.config=B,r.channelCount=g,r.samplerate=a,r.samples.push({unit:x,pts:y}),u}class GB extends Wl{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=$n(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Kl(t)!==void 0&&uf(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(cf(e,i))return Oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return NB(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return af(e,t,i,this.basePTS,this.frameIndex)}}const $B=/\/emsg[-/]ID3/i;class HB{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,n){const s=this.videoTrack=hi("video",1),o=this.audioTrack=hi("audio",1),a=this.txtTrack=hi("text",1);if(this.id3Track=hi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Yh(e);if(l.video){const{id:A,timescale:u,codec:c,supplemental:h}=l.video;s.id=A,s.timescale=a.timescale=u,s.codec=c,s.supplemental=h}if(l.audio){const{id:A,timescale:u,codec:c}=l.audio;o.id=A,o.timescale=u,o.codec=c}a.id=Uh.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Uy(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Kt(this.remainderData,e));const a=qy(i);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=i;const o=this.extractID3Track(n,t);return s.samples=Kh(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=Kh(e,t),{videoTrack:t,audioTrack:hi(),id3Track:n,textTrack:hi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=we(e.samples,["emsg"]);n&&n.forEach(s=>{const o=jy(s);if($B.test(o.schemeIdUri)){const a=df(o,t);let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const A=o.payload;i.samples.push({data:A,len:A.byteLength,dts:a,pts:a,type:Gt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=df(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Gt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function df(r,e){return de(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class YB{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new xl(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,qi.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),o=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)i.set(e.subarray(s,s+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(i.subarray(n,n+16),s);return e}decryptAvcSample(e,t,i,n,s){const o=Wh(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(i>=s.length);i++){const o=s[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class ff{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const s=i.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const s=i[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let l=0,A,u,c,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,l=1);l<n;){if(A=t[l++],!s){s=A?0:1;continue}if(s===1){s=A?0:2;continue}if(!A)s=3;else if(A===1){if(u=l-s-1,h>=0){const f={data:t.subarray(h,u),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(o&&l<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=Kt(f.data,t.subarray(0,u)),f.state=0))}l<n?(c=this.getNALuType(t,l),h=l,d=c,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,n),type:d,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Kt(f.data,t))}return e.naluState=s,a}}class Hn{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(i,i+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}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);const i=this.word>>>32-t;if(e>32&&Oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class gf extends ff{parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 1:{let g=!1;a=!0;const p=A.data;if(l&&p.length>4){const v=this.readSliceType(p);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=g;break}case 5:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,yl(A.data,1,i.pts,t.samples);break}case 7:{var d,f;a=!0,l=!0;const g=A.data,p=this.readSPS(g);if(!e.sps||e.width!==p.width||e.height!==p.height||((d=e.pixelRatio)==null?void 0:d[0])!==p.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let B="avc1.";for(let C=0;C<3;C++){let y=v[C].toString(16);y.length<2&&(y="0"+y),B+=y}e.codec=B}break}case 8:a=!0,e.pps=[A.data];break;case 9:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Hn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(i+s+256)%256),i=n===0?i:n}readSPS(e){const t=new Hn(e);let i=0,n=0,s=0,o=0,a,l,A;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const B=u();if(c(5),f(3),u(),p(),B===100||B===110||B===122||B===244||B===44||B===83||B===86||B===118||B===128){const F=h();if(F===3&&f(1),p(),p(),f(1),d())for(l=F!==3?8:12,A=0;A<l;A++)d()&&(A<6?v(16,t):v(64,t))}p();const C=h();if(C===0)h();else if(C===1)for(f(1),g(),g(),a=h(),A=0;A<a;A++)g();p(),f(1);const y=h(),x=h(),w=c(1);w===0&&f(1),f(1),d()&&(i=h(),n=h(),s=h(),o=h());let D=[1,1];if(d()&&d())switch(u()){case 1:D=[1,1];break;case 2:D=[12,11];break;case 3:D=[10,11];break;case 4:D=[16,11];break;case 5:D=[40,33];break;case 6:D=[24,11];break;case 7:D=[20,11];break;case 8:D=[32,11];break;case 9:D=[80,33];break;case 10:D=[18,11];break;case 11:D=[15,11];break;case 12:D=[64,33];break;case 13:D=[160,99];break;case 14:D=[4,3];break;case 15:D=[3,2];break;case 16:D=[2,1];break;case 255:{D=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((y+1)*16-i*2-n*2),height:(2-w)*(x+1)*16-(w?2:4)*(s+o),pixelRatio:D}}}class pf extends ff{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const s=this.parseNALu(e,i.data,n);let o=this.VideoSample,a,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(A=>{var u,c;switch(A.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,yl(A.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=We(e.params,this.readVPS(A.data)),this.initVPS=A.data),e.vps=[A.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],A.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(A.data);e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in d.params)e.params[f]=d.params[f]}this.pushParameterSet(e.sps,A.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(A.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,A.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=o)!=null&&c.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}o&&a&&o.units.push(A)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Hn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new Hn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),A=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),B=[],C=[];for(let ye=0;ye<i;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(i>0)for(let ye=i;ye<8;ye++)t.readBits(2);for(let ye=0;ye<i;ye++)B[ye]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),C[ye]&&t.readUByte();t.readUEG();const y=t.readUEG();y==3&&t.skipBits(1);const x=t.readUEG(),w=t.readUEG(),D=t.readBoolean();let F=0,O=0,M=0,j=0;D&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG());const X=t.readUEG(),le=t.readUEG(),oe=t.readUEG(),L=t.readBoolean();for(let ye=L?0:i;ye<=i;ye++)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 ke=0;ke<4;ke++)for(let Ue=0;Ue<(ke===3?2:6);Ue++)if(!t.readBoolean())t.readUEG();else{const Ge=Math.min(64,1<<4+(ke<<1));ke>1&&t.readEG();for(let $e=0;$e<Ge;$e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const R=t.readUEG();let _=0;for(let ye=0;ye<R;ye++){let ke=!1;if(ye!==0&&(ke=t.readBoolean()),ke){ye===R&&t.readUEG(),t.readBoolean(),t.readUEG();let Ue=0;for(let Xe=0;Xe<=_;Xe++){const Ge=t.readBoolean();let $e=!1;Ge||($e=t.readBoolean()),(Ge||$e)&&Ue++}_=Ue}else{const Ue=t.readUEG(),Xe=t.readUEG();_=Ue+Xe;for(let Ge=0;Ge<Ue;Ge++)t.readUEG(),t.readBoolean();for(let Ge=0;Ge<Xe;Ge++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ye=t.readUEG();for(let ke=0;ke<ye;ke++){for(let Ue=0;Ue<oe+4;Ue++)t.readBits(1);t.readBits(1)}}let K=0,Y=1,te=1,ie=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let _e=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),et=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ot=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ce>0&&Ce<16?(Y=et[Ce-1],te=ot[Ce-1]):Ce===255&&(Y=t.readBits(16),te=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(),_e=t.readBoolean(),_e&&(F+=t.readUEG(),O+=t.readUEG(),M+=t.readUEG(),j+=t.readUEG()),t.readBoolean()&&(he=t.readBits(32),fe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const ot=t.readBoolean(),Ze=t.readBoolean();let ze=!1;(ot||Ze)&&(ze=t.readBoolean(),ze&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ze&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let T=0;T<=i;T++){ie=t.readBoolean();const m=ie||t.readBoolean();let E=!1;m?t.readEG():E=t.readBoolean();const Q=E?1:t.readUEG()+1;if(ot)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),ze&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Ze)for(let N=0;N<Q;N++)t.readUEG(),t.readUEG(),ze&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),K=t.readUEG())}let Fe=x,pe=w;if(D||_e){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=w-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Ne=a<<24|l<<16|A<<8|u;let Re=0;for(let ye=0;ye<32;ye++)Re=(Re|(Ne>>ye&1)<<31-ye)>>>0;let Ke=Re.toString(16);return o===1&&Ke==="2"&&(Ke="6"),{codecString:`hvc1.${Qe}${o}.${Ke}.${s?"H":"L"}${v}.B0`,params:{general_tier_flag:s,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[a,l,A,u],general_constraint_indicator_flags:[c,h,d,f,g,p],general_level_idc:v,bit_depth:X+8,bit_depth_luma_minus8:X,bit_depth_chroma_minus8:le,min_spatial_segmentation_idc:K,chroma_format_idc:y,frame_rate:{fixed:ie,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,te]}}readPPS(e){const t=new Hn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),s=t.readBoolean();let o=1;return s&&n?o=0:s?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const yt=188;class Ji{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=Ji.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(yt*5,t-yt)+1,n=0;for(;n<i;){let s=!1,o=-1,a=0;for(let l=n;l<t;l+=yt)if(e[l]===71&&(t-l===yt||e[l+yt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+yt*99,e.length-yt)+1)),s||(s=Jl(e,l)===0),s&&a>1&&(o===0&&a>2||l+yt>i))return o}else{if(a)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Uh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ji.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Ji.createTrack("audio",n),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,A=this._txtTrack;let u=o.pid,c=o.pesData,h=a.pid,d=l.pid,f=a.pesData,g=l.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=Kt(this.remainderData,e),C=e.length,this.remainderData=null),C<yt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};const y=Math.max(0,Ji.syncOffset(e));C-=(C-y)%yt,C<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,C,e.buffer.byteLength-C));let x=0;for(let D=y;D<C;D+=yt)if(e[D]===71){const F=!!(e[D+1]&64),O=Jl(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+yt)continue}else j=D+4;switch(O){case u:if(F){if(c&&(s=$r(c,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new gf;break;case"hevc":this.videoParser=new pf;break}this.videoParser!==null&&this.videoParser.parsePES(o,A,s,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(j,D+yt)),c.size+=D+yt-j);break;case h:if(F){if(f&&(s=$r(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(j,D+yt)),f.size+=D+yt-j);break;case d:F&&(g&&(s=$r(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+yt)),g.size+=D+yt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=VB(e,j);break;case B:{F&&(j+=e[j]+1);const X=KB(e,j,this.typeSupported,i,this.observer,this.logger);u=X.videoPid,u>0&&(o.pid=u,o.segmentCodec=X.segmentVideoCodec),h=X.audioPid,h>0&&(a.pid=h,a.segmentCodec=X.segmentAudioCodec),d=X.id3Pid,d>0&&(l.pid=d),p!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${p}'. Backtracking to sync byte @${y} to parse all TS packets.`),p=null,D=y-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=O;break}}else x++;x>0&&jl(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=c,a.pesData=f,l.pesData=g;const w={audioTrack:a,videoTrack:o,id3Track:l,textTrack:A};return n&&this.extractRemainingSamples(w),w}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:s}=e,o=i.pesData,a=t.pesData,l=n.pesData;let A;if(o&&(A=$r(o,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new gf;break;case"hevc":this.videoParser=new pf;break}this.videoParser!==null&&(this.videoParser.parsePES(i,s,A,!0),i.pesData=null)}else i.pesData=o;if(a&&(A=$r(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,A);break;case"mp3":this.parseMPEGPES(t,A);break;case"ac3":this.parseAC3PES(t,A);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(A=$r(l,this.logger))?(this.parseID3PES(n,A),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new YB(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const c=n.missing,h=n.sample.unit.byteLength;if(c===-1)s=Kt(n.sample.unit,s);else{const d=h-c;n.sample.unit.set(s.subarray(0,c),d),e.samples.push(n.sample),i=n.missing}}let o,a;for(o=i,a=s.length;o<a-1&&!Bo(s,o);o++);if(o!==i){let c;const h=o<a-1;if(h?c=`AAC PES did not start with ADTS header,offset:${o}`:c="No ADTS header found in AAC PES",jl(this.observer,new Error(c),h,this.logger),!h)return}ef(e,this.observer,s,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const c=tf(e.samplerate);l=n.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let A=0,u;for(;o<a;)if(u=rf(e,s,o,l,A),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(A++;o<a-1&&!Bo(s,o);o++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let s=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(Af(i,o)){const l=af(e,i,o,a,s);if(l)o+=l.length,s++;else break}else o++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=i.length;let o=0,a=0,l;for(;a<s&&(l=hf(e,i,a,n,o++))>0;)a+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=We({},t,{type:this._videoTrack?Gt.emsg:Gt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Jl(r,e){return((r[e+1]&31)<<8)+r[e+2]}function VB(r,e){return(r[e+10]&31)<<8|r[e+11]}function KB(r,e,t,i,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(r[e+1]&15)<<8|r[e+2],l=e+3+a-4,A=(r[e+10]&15)<<8|r[e+11];for(e+=12+A;e<l;){const u=Jl(r,e),c=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){Xl("ADTS AAC",s);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!i){Xl("H.264",s);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?s.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!i){Xl("AC-3",s);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&c>0){let h=e+5,d=c;for(;d>2;){switch(r[h]){case 106:t.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const g=r[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return jl(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=c+5}return o}function jl(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Xl(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function $r(r,e){let t=0,i,n,s,o,a;const l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Kt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>r.size-6)return null;const u=i[7];u&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(a=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-a>54e5&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),s=i[8];let c=s+9;if(r.size<=c)return null;r.size-=c;const h=new Uint8Array(r.size);for(let d=0,f=l.length;d<f;d++){i=l[d];let g=i.byteLength;if(c)if(c>g){c-=g;continue}else i=i.subarray(c),g-=c,c=0;h.set(i,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class WB{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}}}const ji=Math.pow(2,32)-1;class H{static init(){H.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in H.types)H.types.hasOwnProperty(e)&&(H.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);H.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);H.STTS=H.STSC=H.STCO=s,H.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),H.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),H.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),H.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);H.FTYP=H.box(H.types.ftyp,o,l,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let i=8,n=t.length;const s=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n<s;n++)o.set(t[n],i),i+=t[n].byteLength;return o}static hdlr(e){return H.box(H.types.hdlr,H.HDLR_TYPES[e])}static mdat(e){return H.box(H.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(ji+1)),n=Math.floor(t%(ji+1));return H.box(H.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return H.box(H.types.mdia,H.mdhd(e.timescale||0,e.duration||0),H.hdlr(e.type),H.minf(e))}static mfhd(e){return H.box(H.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?H.box(H.types.minf,H.box(H.types.smhd,H.SMHD),H.DINF,H.stbl(e)):H.box(H.types.minf,H.box(H.types.vmhd,H.VMHD),H.DINF,H.stbl(e))}static moof(e,t,i){return H.box(H.types.moof,H.mfhd(e),H.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(H.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(ji+1)),n=Math.floor(t%(ji+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return H.box(H.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,i[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,i)}static stbl(e){return H.box(H.types.stbl,H.stsd(e),H.box(H.types.stts,H.STTS),H.box(H.types.stsc,H.STSC),H.box(H.types.stsz,H.STSZ),H.box(H.types.stco,H.STCO))}static avc1(e){let t=[],i=[],n,s,o;for(n=0;n<e.sps.length;n++)s=e.sps[n],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(n=0;n<e.pps.length;n++)s=e.pps[n],o=s.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(s));const a=H.box(H.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,A=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return H.box(H.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,A>>8&255,A&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]),a,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.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){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||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 H.box(H.types.mp4a,H.audioStsd(e),H.box(H.types.esds,H.esds(e)))}static mp3(e){return H.box(H.types[".mp3"],H.audioStsd(e))}static ac3(e){return H.box(H.types["ac-3"],H.audioStsd(e),H.box(H.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return H.box(H.types.stsd,H.STSD,H.mp4a(e));if(t==="ac3"&&e.config)return H.box(H.types.stsd,H.STSD,H.ac3(e));if(t==="mp3"&&e.codec==="mp3")return H.box(H.types.stsd,H.STSD,H.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return H.box(H.types.stsd,H.STSD,H.avc1(e));if(t==="hevc"&&e.vps)return H.box(H.types.stsd,H.STSD,H.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){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(i/(ji+1)),a=Math.floor(i%(ji+1));return H.box(H.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,t){const i=H.sdtp(e),n=e.id,s=Math.floor(t/(ji+1)),o=Math.floor(t%(ji+1));return H.box(H.types.traf,H.box(H.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),H.box(H.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),H.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,H.box(H.types.trak,H.tkhd(e),H.mdia(e))}static trex(e){const t=e.id;return H.box(H.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,s=12+16*n,o=new Uint8Array(s);let a,l,A,u,c,h;for(t+=8+s,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<n;a++)l=i[a],A=l.duration,u=l.size,c=l.flags,h=l.cts,o.set([A>>>24&255,A>>>16&255,A>>>8&255,A&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*a);return H.box(H.types.trun,o)}static initSegment(e){H.types||H.init();const t=H.moov(e);return Kt(H.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,s=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),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=s.length;for(let f=0;f<i.length;f+=1){o+=3;for(let g=0;g<i[f].length;g+=1)o+=2+i[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){a.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),o),o+=3;for(let g=0;g<i[f].length;g+=1)a.set(new Uint8Array([i[f][g].length>>8,i[f][g].length&255]),o),o+=2,a.set(i[f][g],o),o+=i[f][g].length}const A=H.box(H.types.hvcC,a),u=e.width,c=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return H.box(H.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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]),A,H.box(H.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),H.box(H.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}}H.types=void 0,H.HDLR_TYPES=void 0,H.STTS=void 0,H.STSC=void 0,H.STCO=void 0,H.STSZ=void 0,H.VMHD=void 0,H.SMHD=void 0,H.STSD=void 0,H.FTYP=void 0,H.DINF=void 0;const mf=9e4;function zl(r,e,t=1,i=!1){const n=r*e*t;return i?Math.round(n):n}function qB(r,e,t=1,i=!1){return zl(r,e,1/t,i)}function Yn(r,e=!1){return zl(r,1e3,1/mf,e)}function JB(r,e=1){return zl(r,mf,1/e)}const jB=10*1e3,XB=1024,zB=1152,ZB=1536;let Hr=null,Zl=null;function Ef(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class bo{constructor(e,t,i,n){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.ISGenerated=!1,Hr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Hr=o?parseInt(o[1]):0}if(Zl===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Zl=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,l=a-s;return l<-4294967296&&(t=!0,a=Wt(a,i),l=a-s),l>0?s:a},i);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,i,n,s,o,a,l){let A,u,c,h,d,f,g=s,p=s;const v=e.pid>-1,B=t.pid>-1,C=t.samples.length,y=e.samples.length>0,x=a&&C>0||C>1;if((!v||y)&&(!B||x)||this.ISGenerated||a){if(this.ISGenerated){var D,F,O,M;const oe=this.videoTrackConfig;(oe&&(t.width!==oe.width||t.height!==oe.height||((D=t.pixelRatio)==null?void 0:D[0])!==((F=oe.pixelRatio)==null?void 0:F[0])||((O=t.pixelRatio)==null?void 0:O[1])!==((M=oe.pixelRatio)==null?void 0:M[1]))||!oe&&x||this.nextAudioPts===null&&y)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=eT(t.samples),!j&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,X>0){this.logger.warn(`[mp4-remuxer]: Dropped ${X} out of ${C} video samples due to a missing keyframe`);const oe=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(X),t.dropped+=X,p+=(t.samples[0].pts-oe)/t.inputTimeScale,le=p}else X===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${C} video samples`),f=!1);if(this.ISGenerated){if(y&&x){const oe=this.getVideoStartPts(t.samples),U=(Wt(e.samples[0].pts,oe)-oe)/t.inputTimeScale;g+=Math.max(0,U),p+=Math.max(0,-U)}if(y){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||l===Ee.AUDIO?p:void 0),x){const oe=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,o)),A=this.remuxVideo(t,p,j,oe)}}else x&&(A=this.remuxVideo(t,p,j,0));A&&(A.firstKeyFrame=X,A.independent=X!==-1,A.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=If(i,s,this._initPTS,this._initDTS)),n.samples.length&&(h=vf(n,s,this._initPTS))),{audio:u,video:A,initSegment:c,independent:f,text:h,id3:d}}generateIS(e,t,i,n){const s=e.samples,o=t.samples,a=this.typeSupported,l={},A=this._initPTS;let u=!A||n,c="audio/mp4",h,d,f;if(u&&(h=d=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!A||f!==A.timescale?h=d=s[0].pts-Math.round(f*i):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:H.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(f=t.inputTimeScale,!A||f!==A.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*i);d=Math.min(d,Wt(o[0].dts,g)-p),h=Math.min(h,g-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:l,initPTS:h,timescale:f}}remuxVideo(e,t,i,n){const s=e.inputTimeScale,o=e.samples,a=[],l=o.length,A=this._initPTS;let u=this.nextAvcDts,c=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const _=t*s,k=o[0].pts-Wt(o[0].dts,o[0].pts);Hr&&u!==null&&Math.abs(_-k-u)<15e3?i=!0:u=_-k}const B=A.baseTime*s/A.timescale;for(let _=0;_<l;_++){const k=o[_];k.pts=Wt(k.pts-B,u),k.dts=Wt(k.dts-B,u),k.dts<o[_>0?_-1:_].dts&&(v=!0)}v&&o.sort(function(_,k){const K=_.dts-k.dts,Y=_.pts-k.pts;return K||Y}),d=o[0].dts,f=o[o.length-1].dts;const C=f-d,y=C?Math.round(C/(l-1)):h||e.inputTimeScale/30;if(i){const _=d-u,k=_>y,K=_<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yn(_,!0)} ms (${_}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Yn(-_,!0)} ms (${_}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Hr)){d=u;const Y=o[0].pts-_;if(k)o[0].dts=d,o[0].pts=Y;else{let te=!0;for(let ie=0;ie<o.length&&!(o[ie].dts>Y&&te);ie++){const he=o[ie].pts;if(o[ie].dts-=_,o[ie].pts-=_,ie<o.length-1){const fe=o[ie+1].pts,_e=o[ie].pts,Te=fe<=_e,Fe=fe<=he;te=Te==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${Yn(Y,!0)}/${Yn(d,!0)}, delta: ${Yn(_,!0)} ms`)}}d=Math.max(0,d);let x=0,w=0,D=d;for(let _=0;_<l;_++){const k=o[_],K=k.units,Y=K.length;let te=0;for(let ie=0;ie<Y;ie++)te+=K[ie].data.length;w+=te,x+=Y,k.length=te,k.dts<D?(k.dts=D,D+=y/4|0||1):D=k.dts,g=Math.min(k.pts,g),p=Math.max(k.pts,p)}f=o[l-1].dts;const F=w+4*x+8;let O;try{O=new Uint8Array(F)}catch(_){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:_,bytes:F,reason:`fail allocating video mdat ${F}`});return}const M=new DataView(O.buffer);M.setUint32(0,F),O.set(H.types.mdat,4);let j=!1,X=Number.POSITIVE_INFINITY,le=Number.POSITIVE_INFINITY,oe=Number.NEGATIVE_INFINITY,L=Number.NEGATIVE_INFINITY;for(let _=0;_<l;_++){const k=o[_],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const _e=K[he],Te=_e.data,Fe=_e.data.byteLength;M.setUint32(c,Fe),c+=4,O.set(Te,c),c+=Fe,Y+=4+Fe}let te;if(_<l-1)h=o[_+1].dts-k.dts,te=o[_+1].pts-k.pts;else{const he=this.config,fe=_>0?k.dts-o[_-1].dts:y;if(te=_>0?k.pts-o[_-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const _e=Math.floor(he.maxBufferHole*s),Te=(n?g+n*s:this.nextAudioPts)-k.pts;Te>_e?(h=Te-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${Te/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const ie=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,te),L=Math.max(L,te),a.push(Ef(k.key,h,Y,ie))}if(a.length){if(Hr){if(Hr<70){const _=a[0].flags;_.dependsOn=2,_.isNonSync=0}}else if(Zl&&L-le<oe-X&&y/oe<.025&&a[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let _=d;for(let k=0,K=a.length;k<K;k++){const Y=_+a[k].duration,te=_+a[k].cts;if(k<K-1){const ie=Y+a[k+1].cts;a[k].duration=ie-te}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,_=Y}}}h=j||!h?y:h,this.nextAvcDts=u=f+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;const R={data1:H.moof(e.sequenceNumber++,d,We(e,{samples:a})),data2:O,startPTS:g/s,endPTS:(p+h)/s,startDTS:d/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,R}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return zB;case"ac3":return ZB;default:return XB}}remuxAudio(e,t,i,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,A=this.getSamplesPerFrame(e),u=A*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,d=[],f=s!==void 0;let g=e.samples,p=h?0:8,v=this.nextAudioPts||-1;const B=t*o,C=c.baseTime*o/c.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(Wt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=Wt(U.pts-C,B)}),!i||v<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;s===0?v=0:n&&!f?v=Math.max(0,B):v=g[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let q=0,R=v;q<g.length;q++){const _=g[q],k=_.pts,K=k-R,Y=Math.abs(1e3*K/o);if(K<=-U*u&&f)q===0&&(this.logger.warn(`Audio frame @ ${(k/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*K/o)} ms.`),this.nextAudioPts=v=R=k);else if(K>=U*u&&Y<jB&&f){let te=Math.round(K/u);R=k-te*u,R<0&&(te--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${te} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let ie=0;ie<te;ie++){const he=Math.max(R,0);let fe=WB.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);fe||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),fe=_.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}_.pts=R,R+=u}}let y=null,x=null,w,D=0,F=g.length;for(;F--;)D+=g[F].unit.byteLength;for(let U=0,q=g.length;U<q;U++){const R=g[U],_=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/l)}else if(i&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{w=new Uint8Array(D)}catch(Y){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:D,reason:`fail allocating audio mdat ${D}`});return}h||(new DataView(w.buffer).setUint32(0,D),w.set(H.types.mdat,4))}else return;w.set(_,p);const K=_.byteLength;p+=K,d.push(Ef(!0,A,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+l*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/l,We({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:w,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function Wt(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function eT(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function If(r,e,t,i){const n=r.samples.length;if(!n)return;const s=r.inputTimeScale;for(let a=0;a<n;a++){const l=r.samples[a];l.pts=Wt(l.pts-t.baseTime*s/t.timescale,e*s)/s,l.dts=Wt(l.dts-i.baseTime*s/i.timescale,e*s)/s}const o=r.samples;return r.samples=[],{samples:o}}function vf(r,e,t){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let o=0;o<i;o++){const a=r.samples[o];a.pts=Wt(a.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((o,a)=>o.pts-a.pts);const s=r.samples;return r.samples=[],{samples:s}}class tT{constructor(e,t,i,n){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=n}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Hy(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=Yh(e);n.audio&&(t=yf(n.audio,qe.AUDIO)),n.video&&(i=yf(n.video,qe.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:i,supplemental:n.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,n,s,o){var a,l;let{initPTS:A,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return c;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((l=f)!=null&&l.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=Vy(h,f),p=Yy(f,h),v=p===null?s:p;(o||!A)&&(iT(A,v,s,g)||d.timescale!==A.timescale)&&(d.initPTS=v-s,A&&A.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${A.baseTime/A.timescale} to ${d.initPTS}`),this.initPTS=A={baseTime:d.initPTS,timescale:1});const B=e?v-A.baseTime/A.timescale:u,C=B+g;Wy(f,h,A.baseTime/A.timescale),g>0?this.lastEndTime=C:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!f.audio,x=!!f.video;let w="";y&&(w+="audio"),x&&(w+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:w,hasAudio:y,hasVideo:x,nb:1,dropped:0};return c.audio=D.type==="audio"?D:void 0,c.video=D.type!=="audio"?D:void 0,c.initSegment=d,c.id3=If(i,s,A,A),n.samples.length&&(c.text=vf(n,s,A)),c}}function iT(r,e,t,i){if(r===null)return!0;const n=Math.max(i,1),s=e-r.baseTime/r.timescale;return Math.abs(s-t)>n}function yf(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===qe.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?ao(t,!1):(Oe.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(Oe.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let xi;try{xi=self.performance.now.bind(self.performance)}catch{xi=Date.now}const xo=[{demux:HB,remux:tT},{demux:Ji,remux:bo},{demux:OB,remux:bo},{demux:GB,remux:bo}];xo.splice(2,0,{demux:UB,remux:bo});class Cf{constructor(e,t,i,n,s,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const s=i.transmuxing;s.executeStart=xi();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:A,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=l,y=rT(o,t);if(y&&Ur(y.method)){const F=this.getDecrypter(),O=wl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(i.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=xi(),eA(i);o=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=F.webCryptoDecrypt(o,y.key.buffer,y.iv.buffer,O).then(M=>{const j=this.push(M,null,i);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,c);if(x){const F=this.configureTransmuxer(o);if(F)return this.logger.warn(`[transmuxer] ${F.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:F,reason:F.message}),s.executeEnd=xi(),eA(i)}(u||c||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),A||this.resetContiguity();const w=this.transmux(o,y,d,h,i);this.asyncResult=Vn(w);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=xi(),w}flush(e){const t=e.transmuxing;t.executeStart=xi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(i){const c=i.flush();c&&o.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:A}=this;if(!l||!A){t.executeEnd=xi();const c=[eA(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(a);return Vn(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(o,c,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:A}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${i.level}`);const u=this.remuxer.remux(n,s,o,a,A,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=xi()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,n),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,s):o=this.transmuxUnencrypted(e,i,n,s),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,s){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let s;for(let c=0,h=xo.length;c<h;c++){var o;if((o=xo[c].demux)!=null&&o.probe(e,this.logger)){s=xo[c];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,A=s.remux,u=s.demux;(!l||!(l instanceof A))&&(this.remuxer=new A(i,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(i,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new xl(this.config)),e}}function rT(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const eA=r=>({remuxResult:{},chunkMeta:r});function Vn(r){return"then"in r&&r.then instanceof Function}class nT{constructor(e,t,i,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=s||null}}class sT{constructor(e,t,i,n,s,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}}let Bf=0;class Tf{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Bf++,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=>{const A=l.data,u=this.hls;if(!(!u||!(A!=null&&A.event)||A.instanceNo!==this.instanceNo))switch(A.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(A.data);break}case"flush":{this.onFlush(A.data);break}case"workerLog":{u.logger[A.data.logType]&&u.logger[A.data.logType](A.data.message);break}default:{A.data=A.data||{},A.data.frag=this.frag,A.data.part=this.part,A.data.id=this.id,u.trigger(A.event,A.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const A=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(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:A})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(l,A)=>{A=A||{},A.frag=this.frag||void 0,l===I.ERROR&&(A=A,A.parent=this.id,A.part=this.part,this.error=A.error),this.hls.trigger(l,A)};this.observer=new $l,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=zh(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||lB()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=cB(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=AB());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:it(s)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Cf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new Cf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Bf++;const t=this.hls.config,i=zh(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),uB(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,s,o,a,l,A,u){var c,h;A.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=o?o.start:s.start,p=s.decryptdata,v=this.frag,B=!(v&&s.cc===v.cc),C=!(v&&A.level===v.level),y=v?A.sn-v.sn:-1,x=this.part?A.part-this.part.index:-1,w=y===0&&A.id>1&&A.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||w&&x<=0)),F=self.performance.now();(C||y||s.stats.parsing.start===0)&&(s.stats.parsing.start=F),o&&(x||!D)&&(o.stats.parsing.start=F);const O=!(v&&((c=s.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),M=new sT(B,D,l,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${A.sn}${A.part>-1?" part: "+A.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${A.level} id: ${A.id}
2501
2501
  discontinuity: ${B}
2502
2502
  trackSwitch: ${C}
2503
2503
  contiguous: ${D}
2504
2504
  accurateTimeOffset: ${l}
2505
2505
  timeOffset: ${g}
2506
- initSegmentChange: ${O}`);const j=new nT(i,n,t,a,u);this.configureTransmuxer(j)}if(this.frag=s,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:A,state:M},e instanceof ArrayBuffer?[e]:[]);else if(f){const j=f.push(e,p,A,M);Vn(j)?j.then(X=>{this.handleTransmuxComplete(X)}).catch(X=>{this.transmuxerError(X,A,"transmuxer-interface push error")}):this.handleTransmuxComplete(j)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);Vn(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Sf=100;class oT extends Ul{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Ee.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:s}){if(i===Ee.MAIN){const o=t.cc,a=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${o} found from main: ${n}/${s}`),this.mainAnchor=t,this.state===Z.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&a&&a.cc!==o?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,a.abortRequests(),this.resetLoadingState()):this.state===Z.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return CC(t,i,e)||t&&ud(t.fragments,i)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Z.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Sf),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Z.IDLE):this.state=Z.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Z.IDLE:this.doTickIdle();break;case Z.WAITING_TRACK:{const{levels:t,trackId:i}=this,n=t==null?void 0:t[i],s=n==null?void 0:n.details;if(s&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(s))break;this.state=Z.WAITING_INIT_PTS}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:s}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[s])||null),this.state=Z.IDLE}break}case Z.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:n,cache:s,complete:o}=t,a=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=Z.FRAG_LOADING;const l=s.flush().buffer,A={frag:i,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(A),o&&super._handleFragmentLoadComplete(A)}else a&&a.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${a.cc}`),this.nextLoadPosition=this.findSyncFrag(a).start,this.clearWaitingFragment())}else this.state=Z.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:s}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[s]))return;const a=i[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=Z.WAITING_TRACK,this.startFragRequested=!1;return}const A=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&A&&(this.bufferFlushed=!1,this.afterBufferFlushed(A,qe.AUDIO,Ee.AUDIO));const u=this.getFwdBufferInfo(A,Ee.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=Z.ENDED;return}const c=u.len,h=t.maxBufferLength,d=l.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:u.end;if(this.switchingTrack&&n){const C=g;l.PTSKnown&&C<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<d[d.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,u,Ee.MAIN,h)),!v){this.bufferFlushed=!0;return}let B=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&B&&vt(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(B)===Et.OK&&(this.mainFragLoading=B=null),B&&vt(B))){if(v.start>B.end){const y=this.fragmentTracker.getFragAtPos(p,Ee.MAIN);y&&y.end>B.end&&(B=y,this.mainFragLoading={frag:y,targetBufferTime:null})}if(v.start>B.end)return}this.loadFragment(v,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Pn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Z.STOPPED&&(this.setInterval(Sf),this.state=Z.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:s,id:o,groupId:a,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}const A=this.mainDetails;if(!A||s.endCC>A.endCC||A.expired){this.cachedTrackLoadedData=t,this.state!==Z.STOPPED&&(this.state=Z.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=n[o];let c=0;if(s.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(Wd(s,A),s.alignedSliding||yo(s,A),c=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(A,c),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:o,groupId:t.groupId}),this.state===Z.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Z.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:s}=e,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const A=l[a];if(!A){this.warn("Audio track is undefined on fragment load progress");return}const u=A.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=o.defaultAudioCodec||A.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Tf(this.hls,Ee.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(d!==void 0){const p=n?n.index:-1,v=p!==-1,B=new Ql(i.level,i.sn,i.stats.chunkCount,s.byteLength,p,v);h.push(s,f,c,"",i,n,u.totalduration,!1,B,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Jd,complete:!1};g.push(new Uint8Array(s)),this.state!==Z.STOPPED&&(this.state=Z.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;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ee.MAIN&&vt(t.frag)&&(this.mainFragLoading=t,this.state===Z.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Ee.AUDIO){!this.audioOnly&&i.type===Ee.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(vt(i)){this.fragPrevious=i;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,Ye({},s)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case V.FRAG_GAP:case V.FRAG_PARSING_ERROR:case V.FRAG_DECRYPT_ERROR:case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ee.AUDIO,t);break;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Me.AUDIO_TRACK&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==qe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==qe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Z.ENDED&&(this.state=Z.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Ee.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:A,level:u}=a,{details:c}=u,{audio:h,text:d,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=Z.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(u,g.tracks,p,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(h){const{startPTS:p,endPTS:v,startDTS:B,endDTS:C}=h;A&&(A.elementaryStreams[qe.AUDIO]={startPTS:p,endPTS:v,startDTS:B,endDTS:C}),l.setElementaryStreamInfo(qe.AUDIO,p,v,B,C),this.bufferFragmentData(h,l,A,o)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=We({id:i,frag:l,details:c},f);n.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=We({id:i,frag:l,details:c},d);n.trigger(I.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,n){if(this.state!==Z.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=Ee.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${o}/${s.codec}]`),o&&o.split(",").length===1&&(s.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Et.NOT_LOADED||n===Et.PARTIAL){var s;if(!vt(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.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=Z.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&yo(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a}=this.bufferedTrack;mr({name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a},e,Er)||(uo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,Ye({},e))}}class tA extends Ti{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let s=-1;for(let o=0;o<n.length;o++){const a=n[o];let l;try{l=new self.URL(a.URI,t.url).href}catch(A){this.warn(`Could not construct new URL for Rendition Report: ${A}`),l=a.URI||""}if(l===e){s=o;break}else l===e.substring(0,l.length)&&(s=o)}if(s!==-1){const o=n[s],a=parseInt(o["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(o["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const A=i&&nd(i);return new sd(a,l>=0?l:void 0,A)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:s}=t,o=self.performance.now(),a=s.loading.first?Math.max(0,o-s.loading.first):0;n.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const u=Math.max(l||0,0);n.appliedTimelineOffset=u,n.fragments.forEach(c=>{c.start=c.playlistOffset+u})}if(n.live||i!=null&&i.live){const u="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){zC(i,n);const B=n.playlistParsingError;if(B){this.warn(B);const C=this.hls;if(!C.config.ignorePlaylistParsingErrors){var A;const{networkDetails:y}=t;C.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:B,reason:B.message,level:t.level||void 0,parent:(A=n.fragments[0])==null?void 0:A.type,networkDetails:y,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,d=(n.edge-h)*1e3,f=Ud(n,d);if(n.requestScheduled+f<o?n.requestScheduled=o:n.requestScheduled+=f,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let g,p,v;if(n.canBlockReload&&n.endSN&&n.advanced){const B=this.hls.config.lowLatencyMode,C=n.lastPartSn,y=n.endSN,x=n.lastPartIndex,w=x!==-1,D=C===y;w?D?(p=y+1,v=B?0:x):(p=C,v=B?x+1:n.maxPartIndex):p=y+1;const F=n.age,O=F+n.ageHeader;let M=Math.min(O-n.partTarget,n.targetduration*1.5);if(M>0){if(O>n.targetduration*3)this.log(`Playlist last advanced ${F.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&O-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${M} with playlist age: ${n.age}`),M=0;else{const j=Math.floor(M/n.targetduration);if(p+=j,v!==void 0){const X=Math.round(M%n.targetduration/n.partTarget);v+=X}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${F.toFixed(2)}s goal: ${M} skip sn ${j} to part ${v}`)}n.tuneInGoal=M}if(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v),B||!D){n.requestScheduled=o,this.loadingPlaylist(u,g);return}}else(n.canBlockReload||n.canSkipUntil)&&(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v));g&&p!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(f-a*2,f/2)),this.scheduleLoading(u,g,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),o=n.requestScheduled;if(s>=o){this.loadingPlaylist(e,t);return}const a=o-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,n){let s=nd(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,s=co.No),new sd(i,n,s)}checkRetry(e){const t=e.details,i=ho(e),n=e.errorAction,{action:s,retryCount:o=0,retryConfig:a}=n||{},l=!!n&&!!a&&(s===_t.RetryRequest||!n.resolved&&s===_t.SendAlternateToPenaltyBox);if(l){var A;if(o>=a.maxNumRetry)return!1;if(i&&(A=e.context)!=null&&A.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=bl(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function bf(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Kn(r[t].attrs,e[t].attrs))return!1;return!0}function Kn(r,e,t){const i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function iA(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class aT extends tA{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,d)=>{h.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=ci(l,a,Er);if(h>-1)s=a[h];else{const d=ci(l,this.tracks);s=this.tracks[d]}}let A=this.findTrackId(s);A===-1&&s&&(A=this.findTrackId(null));const u={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(A!==-1&&c===-1)this.setAudioTrack(A);else if(a.length&&c===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Me.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&mr(e,n,Er))return n;const s=ci(e,this.tracksInGroup,Er);if(s>-1){const o=this.tracksInGroup[s];return this.setAudioTrack(s),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=mC(e,t.levels,i,o,Er);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=ci(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===i&&s||(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(I.AUDIO_TRACK_SWITCHING,Ye({},n)),s))return;const o=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||mr(e,n,Er)))return i}if(e){const{name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l}=e;for(let A=0;A<t.length;A++){const u=t[A];if(mr({name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l},u,Er))return A}for(let A=0;A<t.length;A++){const u=t[A];if(Kn(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return A}for(let A=0;A<t.length;A++){const u=t[A];if(Kn(e.attrs,u.attrs,["LANGUAGE"]))return A}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&uo(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class lT{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var i;if(n.onError(s),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.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(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
2506
+ initSegmentChange: ${O}`);const j=new nT(i,n,t,a,u);this.configureTransmuxer(j)}if(this.frag=s,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:A,state:M},e instanceof ArrayBuffer?[e]:[]);else if(f){const j=f.push(e,p,A,M);Vn(j)?j.then(X=>{this.handleTransmuxComplete(X)}).catch(X=>{this.transmuxerError(X,A,"transmuxer-interface push error")}):this.handleTransmuxComplete(j)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);Vn(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Sf=100;class oT extends Ul{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Ee.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:s}){if(i===Ee.MAIN){const o=t.cc,a=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${o} found from main: ${n}/${s}`),this.mainAnchor=t,this.state===Z.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&a&&a.cc!==o?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,a.abortRequests(),this.resetLoadingState()):this.state===Z.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return CC(t,i,e)||t&&ud(t.fragments,i)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Z.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Sf),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Z.IDLE):this.state=Z.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Z.IDLE:this.doTickIdle();break;case Z.WAITING_TRACK:{const{levels:t,trackId:i}=this,n=t==null?void 0:t[i],s=n==null?void 0:n.details;if(s&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(s))break;this.state=Z.WAITING_INIT_PTS}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:s}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[s])||null),this.state=Z.IDLE}break}case Z.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:n,cache:s,complete:o}=t,a=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=Z.FRAG_LOADING;const l=s.flush().buffer,A={frag:i,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(A),o&&super._handleFragmentLoadComplete(A)}else a&&a.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${a.cc}`),this.nextLoadPosition=this.findSyncFrag(a).start,this.clearWaitingFragment())}else this.state=Z.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:s}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[s]))return;const a=i[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=Z.WAITING_TRACK,this.startFragRequested=!1;return}const A=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&A&&(this.bufferFlushed=!1,this.afterBufferFlushed(A,qe.AUDIO,Ee.AUDIO));const u=this.getFwdBufferInfo(A,Ee.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=Z.ENDED;return}const c=u.len,h=t.maxBufferLength,d=l.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:u.end;if(this.switchingTrack&&n){const C=g;l.PTSKnown&&C<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<d[d.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,u,Ee.MAIN,h)),!v){this.bufferFlushed=!0;return}let B=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&B&&vt(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(B)===Et.OK&&(this.mainFragLoading=B=null),B&&vt(B))){if(v.start>B.end){const y=this.fragmentTracker.getFragAtPos(p,Ee.MAIN);y&&y.end>B.end&&(B=y,this.mainFragLoading={frag:y,targetBufferTime:null})}if(v.start>B.end)return}this.loadFragment(v,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Pn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Z.STOPPED&&(this.setInterval(Sf),this.state=Z.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:s,id:o,groupId:a,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}const A=this.mainDetails;if(!A||s.endCC>A.endCC||A.expired){this.cachedTrackLoadedData=t,this.state!==Z.STOPPED&&(this.state=Z.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=n[o];let c=0;if(s.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(Wd(s,A),s.alignedSliding||yo(s,A),c=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(A,c),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:o,groupId:t.groupId}),this.state===Z.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Z.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:s}=e,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const A=l[a];if(!A){this.warn("Audio track is undefined on fragment load progress");return}const u=A.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=o.defaultAudioCodec||A.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Tf(this.hls,Ee.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(d!==void 0){const p=n?n.index:-1,v=p!==-1,B=new Ql(i.level,i.sn,i.stats.chunkCount,s.byteLength,p,v);h.push(s,f,c,"",i,n,u.totalduration,!1,B,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Jd,complete:!1};g.push(new Uint8Array(s)),this.state!==Z.STOPPED&&(this.state=Z.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;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ee.MAIN&&vt(t.frag)&&(this.mainFragLoading=t,this.state===Z.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Ee.AUDIO){!this.audioOnly&&i.type===Ee.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(vt(i)){this.fragPrevious=i;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,Ye({},s)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case V.FRAG_GAP:case V.FRAG_PARSING_ERROR:case V.FRAG_DECRYPT_ERROR:case V.FRAG_LOAD_ERROR:case V.FRAG_LOAD_TIMEOUT:case V.KEY_LOAD_ERROR:case V.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ee.AUDIO,t);break;case V.AUDIO_TRACK_LOAD_ERROR:case V.AUDIO_TRACK_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Me.AUDIO_TRACK&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==qe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==qe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Z.ENDED&&(this.state=Z.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Ee.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:A,level:u}=a,{details:c}=u,{audio:h,text:d,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=Z.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=l.initSegment||l;this._bufferInitSegment(u,g.tracks,p,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(h){const{startPTS:p,endPTS:v,startDTS:B,endDTS:C}=h;A&&(A.elementaryStreams[qe.AUDIO]={startPTS:p,endPTS:v,startDTS:B,endDTS:C}),l.setElementaryStreamInfo(qe.AUDIO,p,v,B,C),this.bufferFragmentData(h,l,A,o)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=We({id:i,frag:l,details:c},f);n.trigger(I.FRAG_PARSING_METADATA,p)}if(d){const p=We({id:i,frag:l,details:c},d);n.trigger(I.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,n){if(this.state!==Z.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=Ee.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${o}/${s.codec}]`),o&&o.split(",").length===1&&(s.levelCodec=o),this.hls.trigger(I.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Et.NOT_LOADED||n===Et.PARTIAL){var s;if(!vt(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.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=Z.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&yo(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a}=this.bufferedTrack;mr({name:t,lang:i,assocLang:n,characteristics:s,audioCodec:o,channels:a},e,Er)||(uo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,Ye({},e))}}class tA extends Ti{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let s=-1;for(let o=0;o<n.length;o++){const a=n[o];let l;try{l=new self.URL(a.URI,t.url).href}catch(A){this.warn(`Could not construct new URL for Rendition Report: ${A}`),l=a.URI||""}if(l===e){s=o;break}else l===e.substring(0,l.length)&&(s=o)}if(s!==-1){const o=n[s],a=parseInt(o["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(o["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const A=i&&nd(i);return new sd(a,l>=0?l:void 0,A)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:s}=t,o=self.performance.now(),a=s.loading.first?Math.max(0,o-s.loading.first):0;n.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const u=Math.max(l||0,0);n.appliedTimelineOffset=u,n.fragments.forEach(c=>{c.start=c.playlistOffset+u})}if(n.live||i!=null&&i.live){const u="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){zC(i,n);const B=n.playlistParsingError;if(B){this.warn(B);const C=this.hls;if(!C.config.ignorePlaylistParsingErrors){var A;const{networkDetails:y}=t;C.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:B,reason:B.message,level:t.level||void 0,parent:(A=n.fragments[0])==null?void 0:A.type,networkDetails:y,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,d=(n.edge-h)*1e3,f=Ud(n,d);if(n.requestScheduled+f<o?n.requestScheduled=o:n.requestScheduled+=f,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let g,p,v;if(n.canBlockReload&&n.endSN&&n.advanced){const B=this.hls.config.lowLatencyMode,C=n.lastPartSn,y=n.endSN,x=n.lastPartIndex,w=x!==-1,D=C===y;w?D?(p=y+1,v=B?0:x):(p=C,v=B?x+1:n.maxPartIndex):p=y+1;const F=n.age,O=F+n.ageHeader;let M=Math.min(O-n.partTarget,n.targetduration*1.5);if(M>0){if(O>n.targetduration*3)this.log(`Playlist last advanced ${F.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&O-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${M} with playlist age: ${n.age}`),M=0;else{const j=Math.floor(M/n.targetduration);if(p+=j,v!==void 0){const X=Math.round(M%n.targetduration/n.partTarget);v+=X}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${F.toFixed(2)}s goal: ${M} skip sn ${j} to part ${v}`)}n.tuneInGoal=M}if(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v),B||!D){n.requestScheduled=o,this.loadingPlaylist(u,g);return}}else(n.canBlockReload||n.canSkipUntil)&&(g=this.getDeliveryDirectives(n,t.deliveryDirectives,p,v));g&&p!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(f-a*2,f/2)),this.scheduleLoading(u,g,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),o=n.requestScheduled;if(s>=o){this.loadingPlaylist(e,t);return}const a=o-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,n){let s=nd(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,s=co.No),new sd(i,n,s)}checkRetry(e){const t=e.details,i=ho(e),n=e.errorAction,{action:s,retryCount:o=0,retryConfig:a}=n||{},l=!!n&&!!a&&(s===wt.RetryRequest||!n.resolved&&s===wt.SendAlternateToPenaltyBox);if(l){var A;if(o>=a.maxNumRetry)return!1;if(i&&(A=e.context)!=null&&A.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=bl(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function bf(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Kn(r[t].attrs,e[t].attrs))return!1;return!0}function Kn(r,e,t){const i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function iA(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class aT extends tA{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,d)=>{h.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=ci(l,a,Er);if(h>-1)s=a[h];else{const d=ci(l,this.tracks);s=this.tracks[d]}}let A=this.findTrackId(s);A===-1&&s&&(A=this.findTrackId(null));const u={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(A!==-1&&c===-1)this.setAudioTrack(A);else if(a.length&&c===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Me.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&mr(e,n,Er))return n;const s=ci(e,this.tracksInGroup,Er);if(s>-1){const o=this.tracksInGroup[s];return this.setAudioTrack(s),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=mC(e,t.levels,i,o,Er);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=ci(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===i&&s||(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(I.AUDIO_TRACK_SWITCHING,Ye({},n)),s))return;const o=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||mr(e,n,Er)))return i}if(e){const{name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l}=e;for(let A=0;A<t.length;A++){const u=t[A];if(mr({name:i,lang:n,assocLang:s,characteristics:o,audioCodec:a,channels:l},u,Er))return A}for(let A=0;A<t.length;A++){const u=t[A];if(Kn(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return A}for(let A=0;A<t.length;A++){const u=t[A];if(Kn(e.attrs,u.attrs,["LANGUAGE"]))return A}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&uo(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class lT{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var i;if(n.onError(s),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.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(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
2507
2507
  ${this.list("video")}
2508
2508
  ${this.list("audio")}
2509
2509
  ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i==null?void 0:i.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const xf=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Qf="HlsJsTrackRemovedError";class AT extends Error{constructor(e){super(e),this.name=Qf}}class cT extends Ti{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:s}=this;i&&this.log("Media source opened"),!(!n||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(I.MEDIA_ATTACHED,{media:n,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ky(Wi(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_APPENDING,this.onBufferAppending,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.BUFFER_EOS,this.onBufferEos,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.FRAG_PARSED,this.onFragParsed,this),e.on(I.FRAG_CHANGED,this.onFragChanged,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_APPENDING,this.onBufferAppending,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_EOS,this.onBufferEos,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.FRAG_PARSED,this.onFragParsed,this),e.off(I.FRAG_CHANGED,this.onFragChanged,this),e.off(I.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const o=this.isQueued();(s||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?We(i,n.tracks):this.sourceBuffers.forEach(s=>{const[o]=s;o&&(i[o]=We({},this.tracks[o]),this.removeBuffer(o)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,n=Wi(this.appendSource);if(this.transferData=this.overrides=void 0,i&&n){const s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),s)this._objectUrl=i.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&o instanceof l,_f(i),uT(i,a),i.load()}catch{i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,s=n?Object.keys(n):null,o=s?s.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(n&&s&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
2510
2510
  required tracks: ${it(i,(l,A)=>l==="initSegment"?void 0:A)};
2511
- transfer tracks: ${it(n,(l,A)=>l==="initSegment"?void 0:A)}}`),!Fh(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,A=this.details,u=Math.max(l,(A==null?void 0:A.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(n)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const A=l,u=n[A];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(c);h.detectEvictedFragments(A,p,d,null,!0)}const f=rA(A),g=[A,c];this.sourceBuffers[f]=g,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(A),this.trackSourceBuffer(A,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let A=l.length;A--;)a&&l[A].abort(),s.removeSourceBuffer(l[A]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&_f(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[rA(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new lT(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!i[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var l,A,u;const c=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=c;let B=i[a];const C=(l=this.transferData)==null||(A=l.tracks)==null?void 0:A[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),w=y==null?void 0:y.levelCodec;B||(B=i[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=lo(x,w),F=D==null?void 0:D.replace(xf,"$1");let O=lo(d,f);const M=(u=O)==null?void 0:u.replace(xf,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=ao(O,this.appendSource)),this.log(`switching codec ${x} to ${O}`),O!==(B.pendingCodec||B.codec)&&(B.pendingCodec=O),B.container=g,this.appendChangeType(a,g,O))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,s={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Le.isBuffered(l.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,Ee.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:s,parent:o,frag:a,part:l,chunkMeta:A}=t,u=A.buffering[s],c=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=l?l.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=i.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||A.id===1||this.lastMpegAudioChunk.sn!==A.sn,this.lastMpegAudioChunk=A);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&c!=="initSegment"){const x=l||a,w=this.blockedAudioAppend;if(s==="audio"&&o!=="main"&&!this.blockedAudioAppend){const F=x.start+x.duration*.05,O=B.buffered,M=this.currentOp("video");!O.length&&!M?this.blockAudio(x):!M&&!Le.isBuffered(B,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(x)}else if(s==="video"){const D=x.end;if(w){const F=w.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(l||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const w=x.buffer;if(w){const D=C-w.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${c})`),w.timestampOffset=C)}}}this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,d.first===0&&(d.first=x),f&&f.first===0&&(f.first=x);const w={};this.sourceBuffers.forEach(([D,F])=>{D&&(w[D]=Le.getBuffered(F))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:A,parent:a.type,timeRanges:w})},onError:x=>{var w;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:A,error:x,err:x,fatal:!1},F=(w=this.media)==null?void 0:w.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)D.details=V.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!F)D.errorAction=Nn(!0);else if(x.name===Qf&&this.sourceBufferCount===0)D.errorAction=Nn(!0);else{const O=++this.appendErrors[s];this.warn(`Failed ${O}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${F||"no media error"})`),(O>=this.hls.config.appendErrorMaxRetry||F)&&(D.fatal=!0)}this.hls.trigger(I.ERROR,D)}};this.append(y,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:s}=t;i?this.append(this.getFlushOp(i,n,s),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[qe.AUDIOVIDEO]?s.push("audiovideo"):(o[qe.AUDIO]&&s.push("audio"),o[qe.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const A=n?n.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:n,stats:A,id:i.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,i;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((i=this.tracks[e])==null?void 0:i.ending))})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})&&(n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(I.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===V.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,s=i.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const l=Math.max(a,o),A=Math.floor(s/o)*o-l;this.flushBackBuffer(s,o,A)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const l=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),A=Math.max(l,o),u=Math.floor(s/o)*o+A;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&i>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const l=o.start(a-1),A=o.end(a-1);if(i>l||e>=l&&e<=A)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const A=Math.max(0,t.fragmentStart),u=Math.max(A,n);return{duration:1/0,start:A,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return de(s)?{duration:s}:null;const o=this.media.duration,a=de(i.duration)?i.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${it(i)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(I.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const o=s,a=e[o];if(this.isPending(a)){const l=this.getTrackCodec(a,o),A=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${A})${this.currentOp(o)?" Queued":""} ${it(a)}`);try{const u=i.addSourceBuffer(A),c=rA(o),h=[o,u];t[c]=h,a.buffer=u}catch(u){var n;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:A,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Cl(i,"video")&&(n=rC(n,i));const s=lo(n,e.levelCodec);return s?t.slice(0,5)==="audio"?ao(s,this.appendSource):s:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,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",(s,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}removeExecutor(e,t,i){const{media:n,mediaSource:s}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!n||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,A=de(s.duration)?s.duration:1/0,u=Math.max(0,t),c=Math.min(i,l,A);c>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new AT(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),s.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function _f(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function uT(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function rA(r){return r==="audio"?1:0}class nA{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,nA.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let s=e.length-1;const o=Math.max(t,i);for(let a=0;a<e.length;a+=1){const l=e[a];if((l.width>=o||l.height>=o)&&n(l,e[a+1])){s=a;break}}return s}}const Pt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},hT={HLS:"h"},Wn={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},dT={[Wn.OBJECT]:["br","d","ot","tb"],[Wn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Wn.SESSION]:["cid","pr","sf","sid","st","v"],[Wn.STATUS]:["bs","rtp"]};class Yr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Yr?i:new Yr(i))),this.value=e,this.params=t}}const fT="Dict";function gT(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function pT(r,e,t,i){return new Error(`failed to ${r} "${gT(e)}" as ${t}`,{cause:i})}function di(r,e,t){return pT("serialize",r,e,t)}class wf{constructor(e){this.description=e}}const Rf="Bare Item",mT="Boolean";function ET(r){if(typeof r!="boolean")throw di(r,mT);return r?"?1":"?0"}const IT="Byte Sequence";function vT(r){if(ArrayBuffer.isView(r)===!1)throw di(r,IT);return`:${yB(r)}:`}const yT="Integer";function CT(r){return r<-999999999999999||999999999999999<r}function Df(r){if(CT(r))throw di(r,yT);return r.toString()}function BT(r){return`@${Df(r.getTime()/1e3)}`}const TT="Decimal";function ST(r){const e=nf(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw di(r,TT);const t=e.toString();return t.includes(".")?t:`${t}.0`}const bT="String",xT=/[\x00-\x1f\x7f]+/;function QT(r){if(xT.test(r))throw di(r,bT);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function _T(r){return r.description||r.toString().slice(7,-1)}const wT="Token";function Lf(r){const e=_T(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw di(e,wT);return e}function sA(r){switch(typeof r){case"number":if(!de(r))throw di(r,Rf);return Number.isInteger(r)?Df(r):ST(r);case"string":return QT(r);case"symbol":return Lf(r);case"boolean":return ET(r);case"object":if(r instanceof Date)return BT(r);if(r instanceof Uint8Array)return vT(r);if(r instanceof wf)return Lf(r);default:throw di(r,Rf)}}const RT="Key";function oA(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw di(r,RT);return r}function aA(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${oA(e)}`:`;${oA(e)}=${sA(t)}`).join("")}function kf(r){return r instanceof Yr?`${sA(r.value)}${aA(r.params)}`:sA(r)}function DT(r){return`(${r.value.map(kf).join(" ")})${aA(r.params)}`}function LT(r,e={whitespace:!0}){if(typeof r!="object")throw di(r,fT);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof Yr||(s=new Yr(s));let o=oA(n);return s.value===!0?o+=aA(s.params):(o+="=",Array.isArray(s.value)?o+=DT(s):o+=kf(s)),o}).join(`,${i}`)}function kT(r,e){return LT(r,e)}function MT(r){return r==="ot"||r==="sf"||r==="st"}function FT(r){return typeof r=="number"?de(r):r!=null&&r!==""&&r!==!1}const Qo=r=>Math.round(r),PT=(r,e)=>(e!=null&&e.baseUrl&&(r=CB(r,e.baseUrl)),encodeURIComponent(r)),_o=r=>Qo(r/100)*100,NT={br:Qo,d:Qo,bl:_o,dl:_o,mtp:_o,nor:PT,rtp:_o,tb:Qo};function OT(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),n=We({},NT,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return i.forEach(o=>{if(s!=null&&s(o))return;let a=r[o];const l=n[o];l&&(a=l(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||FT(a)&&(MT(o)&&typeof a=="string"&&(a=new wf(a)),t[o]=a))}),t}function Mf(r,e={}){return r?kT(OT(r,e),We({whitespace:!1},e)):""}function UT(r,e={}){const t={};if(!r)return t;const i=Object.entries(r),n=Object.entries(dT).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=i.reduce((o,a)=>{var l,A;const[u,c]=a,h=((l=n.find(d=>d[1].includes(u)))===null||l===void 0?void 0:l[0])||Wn.REQUEST;return(A=o[h])!==null&&A!==void 0||(o[h]={}),o[h][u]=c,o},{});return Object.entries(s).reduce((o,[a,l])=>(o[a]=Mf(l,e),o),t)}function GT(r,e,t){return We(r,UT(e,t))}const $T="CMCD";function HT(r,e={}){if(!r)return"";const t=Mf(r,e);return`${$T}=${encodeURIComponent(t)}`}const Ff=/CMCD=[^&#]+/;function YT(r,e,t){const i=HT(e,t);if(!i)return r;if(Ff.test(r))return r.replace(Ff,i);const n=r.includes("?")?"&":"?";return`${r}${n}${i}`}class VT{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Pt.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:o}=n,a=this.hls.levels[s.level],l=this.getObjectType(s),A={d:(o||s).duration*1e3,ot:l};(l===Pt.VIDEO||l===Pt.AUDIO||l==Pt.MUXED)&&(A.br=a.bitrate/1e3,A.tb=this.getTopBandwidth(l)/1e3,A.bl=this.getBufferLength(l));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(A.nor=u.url),this.apply(n,A)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:hT.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){We(t,this.createData());const i=t.ot===Pt.INIT||t.ot===Pt.VIDEO||t.ot===Pt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,a)=>(n.includes(a)&&(o[a]=t[a]),o),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),GT(e.headers,t,s)):e.url=YT(e.url,t,s)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t,i;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(i=t.details)==null?void 0:i.partList;if(o){const{sn:a}=s;for(let l=o.length-1;l>=0;l--){const A=o[l];if(A.index===n&&A.fragment.sn===a)return o[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Pt.TIMED_TEXT;if(e.sn==="initSegment")return Pt.INIT;if(t==="audio")return Pt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Pt.VIDEO:Pt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Pt.AUDIO)i=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;i=n.levels.slice(0,o)}for(const s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Pt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Le.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}}const KT=3e5;class WT extends Ti{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.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){const 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){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===_t.SendAlternateToPenaltyBox&&i.flags===ei.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:A}=t.context;a&&n?o=this.getPathwayForGroupId(a,A,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==o),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${it(s)} penalized: ${it(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(s=>{n-i[s]>KT&&delete i[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in i)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Yd(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const A=this.hls.levels[a];l&&A&&this.levels&&(A.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&A.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${A.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Me.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Me.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===o))return;const A=this.getLevelsForPathway(a).map(u=>{const c=new st(u.attrs);c["PATHWAY-ID"]=o;const h=c.AUDIO&&`${c.AUDIO}_clone_${o}`,d=c.SUBTITLES&&`${c.SUBTITLES}_clone_${o}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),d&&(n[c.SUBTITLES]=d,c.SUBTITLES=d);const f=Nf(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Pn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)g.addGroupId("audio",`${u.audioGroups[p]}_clone_${o}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)g.addGroupId("text",`${u.subtitleGroups[p]}_clone_${o}`);return g});t.push(...A),Pf(this.audioTracks,i,l,o),Pf(this.subtitleTracks,n,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:n.href},o=t.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},A={onSuccess:(u,c,h,d)=>{this.log(`Loaded steering manifest: "${n}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=f;if(g)try{this.uri=new self.URL(g,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);const B={steeringManifest:f,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,B),v&&this.updatePathwayPriority(v)},onError:(u,c,h,d)=>{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 f=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,l,A)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Pf(r,e,t,i){r&&Object.keys(e).forEach(n=>{const s=r.filter(o=>o.groupId===n).map(o=>{const a=We({},o);return a.details=void 0,a.attrs=new st(a.attrs),a.url=a.attrs.URI=Nf(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=i,a});r.push(...s)})}function Nf(r,e,t,i){const{HOST:n,PARAMS:s,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return n&&!a&&(l.host=n),s&&Object.keys(s).sort().forEach(A=>{A&&l.searchParams.set(A,s[A])}),l.href}class Vr extends Ti{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Vr.CDMCleanupPromise?[Vr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,s=`"${t.type}" event: init data type: "${i}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Io(this.config));const a=o.map(Ml).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Ll(o);let l,A;if(i==="sinf"){if(a!==Ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=mt(new Uint8Array(n));try{const g=Rl(JSON.parse(f).sinf),p=Vh(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24)),A=Ve.FAIRPLAY}catch(g){this.warn(`${s} Failed to parse sinf: ${g}`);return}}else{if(a!==Ve.WIDEVINE&&a!==Ve.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=Zy(n),g=f.filter(v=>!!v.systemId&&kl(v.systemId)===a);g.length>1&&this.warn(`${s} Using first of ${g.length} pssh found for selected key-system ${a}`);const p=g[0];if(!p){f.length===0||f.some(v=>!v.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${f.map(v=>kl(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(A=kl(p.systemId),p.version===0&&p.data)if(A===Ve.WIDEVINE){const v=p.data.length-22;l=new Uint8Array(p.data.subarray(v,v+16))}else A===Ve.PLAYREADY&&(l=bd(p.data))}if(!A||!l)return;const u=ai.hexDump(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let d=c[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=ai.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=c[v],p.pssh)break;delete c[v],p.pssh=new Uint8Array(n),p.keyId=l,d=c[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,i,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(A!==a){this.log(`Ignoring "${t.type}" event with ${A} init data for selected key-system ${a}`);return}d=c[u]=this.getKeySystemSelectionPromise([A]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new On("ISO-23001-7",u,(p=Ml(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,i,n,"encrypted-event-no-match")})}),d.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ve.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,n=t.map(o=>o.audioCodec).filter(i),s=t.map(o=>o.videoCodec).filter(i);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const l=A=>{const u=A.shift();this.getMediaKeysPromise(u,n,s).then(c=>o({keySystem:u,mediaKeys:c})).catch(c=>{A.length?l(A):c instanceof qt?a(c):a(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Sd===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=YC(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let o=s==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${it(n)}`),o=this.requestMediaKeySystemAccess(e,n);const a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const A=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),A.then(c=>c?this.setMediaKeysServerCertificate(u,e,c):u))),a.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),a.mediaKeys})}return o.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ai.hexDump(e.keyId||[])}`);const n=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return ai.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${ai.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
2511
+ transfer tracks: ${it(n,(l,A)=>l==="initSegment"?void 0:A)}}`),!Fh(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,A=this.details,u=Math.max(l,(A==null?void 0:A.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(n)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const A=l,u=n[A];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(c);h.detectEvictedFragments(A,p,d,null,!0)}const f=rA(A),g=[A,c];this.sourceBuffers[f]=g,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(A),this.trackSourceBuffer(A,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let A=l.length;A--;)a&&l[A].abort(),s.removeSourceBuffer(l[A]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&_f(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[rA(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new lT(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!i[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var l,A,u;const c=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=c;let B=i[a];const C=(l=this.transferData)==null||(A=l.tracks)==null?void 0:A[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),w=y==null?void 0:y.levelCodec;B||(B=i[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=lo(x,w),F=D==null?void 0:D.replace(xf,"$1");let O=lo(d,f);const M=(u=O)==null?void 0:u.replace(xf,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=ao(O,this.appendSource)),this.log(`switching codec ${x} to ${O}`),O!==(B.pendingCodec||B.codec)&&(B.pendingCodec=O),B.container=g,this.appendChangeType(a,g,O))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,s={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Le.isBuffered(l.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,Ee.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:s,parent:o,frag:a,part:l,chunkMeta:A}=t,u=A.buffering[s],c=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=l?l.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=i.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||A.id===1||this.lastMpegAudioChunk.sn!==A.sn,this.lastMpegAudioChunk=A);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&c!=="initSegment"){const x=l||a,w=this.blockedAudioAppend;if(s==="audio"&&o!=="main"&&!this.blockedAudioAppend){const F=x.start+x.duration*.05,O=B.buffered,M=this.currentOp("video");!O.length&&!M?this.blockAudio(x):!M&&!Le.isBuffered(B,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(x)}else if(s==="video"){const D=x.end;if(w){const F=w.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(l||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const w=x.buffer;if(w){const D=C-w.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${c})`),w.timestampOffset=C)}}}this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,d.first===0&&(d.first=x),f&&f.first===0&&(f.first=x);const w={};this.sourceBuffers.forEach(([D,F])=>{D&&(w[D]=Le.getBuffered(F))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:A,parent:a.type,timeRanges:w})},onError:x=>{var w;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:A,error:x,err:x,fatal:!1},F=(w=this.media)==null?void 0:w.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)D.details=V.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!F)D.errorAction=Nn(!0);else if(x.name===Qf&&this.sourceBufferCount===0)D.errorAction=Nn(!0);else{const O=++this.appendErrors[s];this.warn(`Failed ${O}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${F||"no media error"})`),(O>=this.hls.config.appendErrorMaxRetry||F)&&(D.fatal=!0)}this.hls.trigger(I.ERROR,D)}};this.append(y,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:s}=t;i?this.append(this.getFlushOp(i,n,s),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[qe.AUDIOVIDEO]?s.push("audiovideo"):(o[qe.AUDIO]&&s.push("audio"),o[qe.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const A=n?n.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:n,stats:A,id:i.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,i;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((i=this.tracks[e])==null?void 0:i.ending))})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})&&(n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(I.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===V.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,s=i.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const l=Math.max(a,o),A=Math.floor(s/o)*o-l;this.flushBackBuffer(s,o,A)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const l=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),A=Math.max(l,o),u=Math.floor(s/o)*o+A;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&i>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const l=o.start(a-1),A=o.end(a-1);if(i>l||e>=l&&e<=A)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const A=Math.max(0,t.fragmentStart),u=Math.max(A,n);return{duration:1/0,start:A,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return de(s)?{duration:s}:null;const o=this.media.duration,a=de(i.duration)?i.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${it(i)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(I.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const o=s,a=e[o];if(this.isPending(a)){const l=this.getTrackCodec(a,o),A=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${A})${this.currentOp(o)?" Queued":""} ${it(a)}`);try{const u=i.addSourceBuffer(A),c=rA(o),h=[o,u];t[c]=h,a.buffer=u}catch(u){var n;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:A,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Cl(i,"video")&&(n=rC(n,i));const s=lo(n,e.levelCodec);return s?t.slice(0,5)==="audio"?ao(s,this.appendSource):s:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,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",(s,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}removeExecutor(e,t,i){const{media:n,mediaSource:s}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!n||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,A=de(s.duration)?s.duration:1/0,u=Math.max(0,t),c=Math.min(i,l,A);c>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new AT(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),s.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function _f(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function uT(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function rA(r){return r==="audio"?1:0}class nA{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,nA.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let s=e.length-1;const o=Math.max(t,i);for(let a=0;a<e.length;a+=1){const l=e[a];if((l.width>=o||l.height>=o)&&n(l,e[a+1])){s=a;break}}return s}}const Pt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},hT={HLS:"h"},Wn={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},dT={[Wn.OBJECT]:["br","d","ot","tb"],[Wn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Wn.SESSION]:["cid","pr","sf","sid","st","v"],[Wn.STATUS]:["bs","rtp"]};class Yr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Yr?i:new Yr(i))),this.value=e,this.params=t}}const fT="Dict";function gT(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function pT(r,e,t,i){return new Error(`failed to ${r} "${gT(e)}" as ${t}`,{cause:i})}function di(r,e,t){return pT("serialize",r,e,t)}class wf{constructor(e){this.description=e}}const Rf="Bare Item",mT="Boolean";function ET(r){if(typeof r!="boolean")throw di(r,mT);return r?"?1":"?0"}const IT="Byte Sequence";function vT(r){if(ArrayBuffer.isView(r)===!1)throw di(r,IT);return`:${yB(r)}:`}const yT="Integer";function CT(r){return r<-999999999999999||999999999999999<r}function Df(r){if(CT(r))throw di(r,yT);return r.toString()}function BT(r){return`@${Df(r.getTime()/1e3)}`}const TT="Decimal";function ST(r){const e=nf(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw di(r,TT);const t=e.toString();return t.includes(".")?t:`${t}.0`}const bT="String",xT=/[\x00-\x1f\x7f]+/;function QT(r){if(xT.test(r))throw di(r,bT);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function _T(r){return r.description||r.toString().slice(7,-1)}const wT="Token";function Lf(r){const e=_T(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw di(e,wT);return e}function sA(r){switch(typeof r){case"number":if(!de(r))throw di(r,Rf);return Number.isInteger(r)?Df(r):ST(r);case"string":return QT(r);case"symbol":return Lf(r);case"boolean":return ET(r);case"object":if(r instanceof Date)return BT(r);if(r instanceof Uint8Array)return vT(r);if(r instanceof wf)return Lf(r);default:throw di(r,Rf)}}const RT="Key";function oA(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw di(r,RT);return r}function aA(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${oA(e)}`:`;${oA(e)}=${sA(t)}`).join("")}function kf(r){return r instanceof Yr?`${sA(r.value)}${aA(r.params)}`:sA(r)}function DT(r){return`(${r.value.map(kf).join(" ")})${aA(r.params)}`}function LT(r,e={whitespace:!0}){if(typeof r!="object")throw di(r,fT);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof Yr||(s=new Yr(s));let o=oA(n);return s.value===!0?o+=aA(s.params):(o+="=",Array.isArray(s.value)?o+=DT(s):o+=kf(s)),o}).join(`,${i}`)}function kT(r,e){return LT(r,e)}function MT(r){return r==="ot"||r==="sf"||r==="st"}function FT(r){return typeof r=="number"?de(r):r!=null&&r!==""&&r!==!1}const Qo=r=>Math.round(r),PT=(r,e)=>(e!=null&&e.baseUrl&&(r=CB(r,e.baseUrl)),encodeURIComponent(r)),_o=r=>Qo(r/100)*100,NT={br:Qo,d:Qo,bl:_o,dl:_o,mtp:_o,nor:PT,rtp:_o,tb:Qo};function OT(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),n=We({},NT,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return i.forEach(o=>{if(s!=null&&s(o))return;let a=r[o];const l=n[o];l&&(a=l(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||FT(a)&&(MT(o)&&typeof a=="string"&&(a=new wf(a)),t[o]=a))}),t}function Mf(r,e={}){return r?kT(OT(r,e),We({whitespace:!1},e)):""}function UT(r,e={}){const t={};if(!r)return t;const i=Object.entries(r),n=Object.entries(dT).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=i.reduce((o,a)=>{var l,A;const[u,c]=a,h=((l=n.find(d=>d[1].includes(u)))===null||l===void 0?void 0:l[0])||Wn.REQUEST;return(A=o[h])!==null&&A!==void 0||(o[h]={}),o[h][u]=c,o},{});return Object.entries(s).reduce((o,[a,l])=>(o[a]=Mf(l,e),o),t)}function GT(r,e,t){return We(r,UT(e,t))}const $T="CMCD";function HT(r,e={}){if(!r)return"";const t=Mf(r,e);return`${$T}=${encodeURIComponent(t)}`}const Ff=/CMCD=[^&#]+/;function YT(r,e,t){const i=HT(e,t);if(!i)return r;if(Ff.test(r))return r.replace(Ff,i);const n=r.includes("?")?"&":"?";return`${r}${n}${i}`}class VT{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Pt.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:o}=n,a=this.hls.levels[s.level],l=this.getObjectType(s),A={d:(o||s).duration*1e3,ot:l};(l===Pt.VIDEO||l===Pt.AUDIO||l==Pt.MUXED)&&(A.br=a.bitrate/1e3,A.tb=this.getTopBandwidth(l)/1e3,A.bl=this.getBufferLength(l));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(A.nor=u.url),this.apply(n,A)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:hT.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){We(t,this.createData());const i=t.ot===Pt.INIT||t.ot===Pt.VIDEO||t.ot===Pt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,a)=>(n.includes(a)&&(o[a]=t[a]),o),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),GT(e.headers,t,s)):e.url=YT(e.url,t,s)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t,i;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(i=t.details)==null?void 0:i.partList;if(o){const{sn:a}=s;for(let l=o.length-1;l>=0;l--){const A=o[l];if(A.index===n&&A.fragment.sn===a)return o[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Pt.TIMED_TEXT;if(e.sn==="initSegment")return Pt.INIT;if(t==="audio")return Pt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Pt.VIDEO:Pt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Pt.AUDIO)i=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;i=n.levels.slice(0,o)}for(const s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Pt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Le.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}}const KT=3e5;class WT extends Ti{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.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){const 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){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===wt.SendAlternateToPenaltyBox&&i.flags===ei.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:A}=t.context;a&&n?o=this.getPathwayForGroupId(a,A,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==o),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${it(s)} penalized: ${it(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(s=>{n-i[s]>KT&&delete i[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in i)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Yd(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const A=this.hls.levels[a];l&&A&&this.levels&&(A.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&A.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${A.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Me.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Me.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===o))return;const A=this.getLevelsForPathway(a).map(u=>{const c=new st(u.attrs);c["PATHWAY-ID"]=o;const h=c.AUDIO&&`${c.AUDIO}_clone_${o}`,d=c.SUBTITLES&&`${c.SUBTITLES}_clone_${o}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),d&&(n[c.SUBTITLES]=d,c.SUBTITLES=d);const f=Nf(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Pn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)g.addGroupId("audio",`${u.audioGroups[p]}_clone_${o}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)g.addGroupId("text",`${u.subtitleGroups[p]}_clone_${o}`);return g});t.push(...A),Pf(this.audioTracks,i,l,o),Pf(this.subtitleTracks,n,l,o)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:n.href},o=t.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},A={onSuccess:(u,c,h,d)=>{this.log(`Loaded steering manifest: "${n}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=f;if(g)try{this.uri=new self.URL(g,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);const B={steeringManifest:f,url:n.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,B),v&&this.updatePathwayPriority(v)},onError:(u,c,h,d)=>{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 f=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,l,A)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Pf(r,e,t,i){r&&Object.keys(e).forEach(n=>{const s=r.filter(o=>o.groupId===n).map(o=>{const a=We({},o);return a.details=void 0,a.attrs=new st(a.attrs),a.url=a.attrs.URI=Nf(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=i,a});r.push(...s)})}function Nf(r,e,t,i){const{HOST:n,PARAMS:s,[t]:o}=i;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const l=new self.URL(r);return n&&!a&&(l.host=n),s&&Object.keys(s).sort().forEach(A=>{A&&l.searchParams.set(A,s[A])}),l.href}class Vr extends Ti{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Vr.CDMCleanupPromise?[Vr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,s=`"${t.type}" event: init data type: "${i}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Io(this.config));const a=o.map(Ml).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Ll(o);let l,A;if(i==="sinf"){if(a!==Ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=mt(new Uint8Array(n));try{const g=Rl(JSON.parse(f).sinf),p=Vh(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24)),A=Ve.FAIRPLAY}catch(g){this.warn(`${s} Failed to parse sinf: ${g}`);return}}else{if(a!==Ve.WIDEVINE&&a!==Ve.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}const f=Zy(n),g=f.filter(v=>!!v.systemId&&kl(v.systemId)===a);g.length>1&&this.warn(`${s} Using first of ${g.length} pssh found for selected key-system ${a}`);const p=g[0];if(!p){f.length===0||f.some(v=>!v.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${f.map(v=>kl(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(A=kl(p.systemId),p.version===0&&p.data)if(A===Ve.WIDEVINE){const v=p.data.length-22;l=new Uint8Array(p.data.subarray(v,v+16))}else A===Ve.PLAYREADY&&(l=bd(p.data))}if(!A||!l)return;const u=ai.hexDump(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let d=c[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=ai.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=c[v],p.pssh)break;delete c[v],p.pssh=new Uint8Array(n),p.keyId=l,d=c[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,i,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(A!==a){this.log(`Ignoring "${t.type}" event with ${A} init data for selected key-system ${a}`);return}d=c[u]=this.getKeySystemSelectionPromise([A]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new On("ISO-23001-7",u,(p=Ml(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,i,n,"encrypted-event-no-match")})}),d.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ve.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,n=t.map(o=>o.audioCodec).filter(i),s=t.map(o=>o.videoCodec).filter(i);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const l=A=>{const u=A.shift();this.getMediaKeysPromise(u,n,s).then(c=>o({keySystem:u,mediaKeys:c})).catch(c=>{A.length?l(A):c instanceof qt?a(c):a(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Sd===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=YC(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let o=s==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${it(n)}`),o=this.requestMediaKeySystemAccess(e,n);const a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const A=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),A.then(c=>c?this.setMediaKeysServerCertificate(u,e,c):u))),a.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),a.mediaKeys})}return o.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ai.hexDump(e.keyId||[])}`);const n=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,s,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return ai.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${ai.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
2512
2512
  } (data length: ${t&&t.byteLength})`),n.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const n=Io(this.config),s=e.map(Ll).filter(o=>!!o&&n.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:o})=>{const a=Ml(o);a?t(a):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(a,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:a,mediaKeys:l,decryptdata:t}))))),(this.keyIdToKeySessionPromise[i]=s.then(a=>{const l="cenc",A=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(a,l,A,"playlist-key")})).catch(a=>this.handleError(a))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof qt?this.hls.trigger(I.ERROR,e.data):this.hls.trigger(I.ERROR,{type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Ll(e.keyFormat),s=n?[n]:Io(this.config);return this.attemptKeySystemAccess(s)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Io(this.config)),e.length===0)throw new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${it({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>i.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var s,o;const a=(s=this.config.drmSystems)==null||(o=s[e.keySystem])==null?void 0:o.generateRequest;if(a)try{const f=a.call(this.hls,t,i,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,i=f.initData?f.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(f){var l;if(this.warn(f.message),(l=this.hls)!=null&&l.config.debug)throw f}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const A=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${A} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new $l,c=e._onmessage=f=>{const g=e.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}const{messageType:p,message:v}=f;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,v).catch(B=>{u.eventNames().length?u.emit("error",B):this.handleError(B)}):p==="license-release"?e.keySystem===Ve.FAIRPLAY&&(this.updateKeySession(e,Dl("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},h=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${A}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",h);const d=new Promise((f,g)=>{u.on("error",g),u.on("keyStatus",p=>{p.startsWith("usable")?f():p==="output-restricted"?g(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${A}`)}).catch(f=>{throw new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{throw u.removeAllListeners(),this.removeSession(e),f}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{if(typeof i=="string"&&typeof t=="object"){const n=i;i=t,t=n}this.log(`key status change "${t}" for keyStatuses keyId: ${ai.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ai.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:s},A=t.certLoadPolicy.default,u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,d,f,g)=>{o(h.data)},onError:(h,d,f,g)=>{a(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:Ye({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,d,f)=>{a(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,d,f)=>{a(new Error("aborted"))}};n.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,s)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),n(e)}).catch(o=>{s(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),s=n.querySelectorAll("HttpHeader");if(s.length>0){let u;for(let c=0,h=s.length;c<h;c++){var o,a;u=s[c];const d=(o=u.querySelector("name"))==null?void 0:o.textContent,f=(a=u.querySelector("value"))==null?void 0:a.textContent;d&&f&&e.setRequestHeader(d,f)}}const l=n.querySelector("Challenge"),A=l==null?void 0:l.textContent;if(!A)throw new Error("Cannot find <Challenge> in key message");return Dl(atob(A))}setupLicenseXHR(e,t,i,n){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),s.call(this.hls,e,t,i,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){const i=this.config.keyLoadPolicy.default;return new Promise((n,s)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const A=this.config.licenseResponseCallback;if(A)try{l=A.call(this.hls,a,o,e)}catch(u){this.error(u)}n(l)}else{const l=i.errorRetry,A=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>A||a.status>=400&&a.status<500)s(new qt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else{const u=A-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:A})=>{e.keySystem==Ve.PLAYREADY&&(A=this.unpackPlayReadyKeyMessage(l,A)),l.send(A)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},On.clearKeyUriToKeyIdMap();const n=i.length;Vr.CDMCleanupPromise=Promise.all(i.map(s=>this.removeSession(s)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(s=>{var o;this.log(`Could not clear media keys: ${s}`),(o=this.hls)==null||o.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${s}`)})}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)}).catch(s=>{var o;this.log(`Could not close sessions and clear media keys: ${s}`),(o=this.hls)==null||o.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${s}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,s)=>(n.indexOf(s.keyFormat)===-1&&n.push(s.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{drmSystemOptions:s}=this.config;return(KC(s)?new Promise((a,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(a)}):Promise.resolve()).catch(a=>{var l;this.log(`Could not remove session: ${a}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${a}`)})}).then(()=>t.close()).catch(a=>{var l;this.log(`Could not close session: ${a}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${a}`)})})}}}Vr.CDMCleanupPromise=void 0;class qt extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class qT{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(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const s=n-this.lastTime,o=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/s,A=this.hls;if(A.trigger(I.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>A.config.fpsDroppedMonitoringThreshold*a){let u=A.currentLevel;A.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(A.autoLevelCapping===-1||A.autoLevelCapping>=u)&&(u=u-1,A.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:A.currentLevel}),A.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Of(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function Uf(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Oe.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,r.addCue(n)}catch(n){Oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(r.mode=t)}function Kr(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let i=r.cues.length;i--;)e&&r.cues[i].removeEventListener("enter",e),r.removeCue(r.cues[i]);t==="disabled"&&(r.mode=t)}function lA(r,e,t,i){const n=r.mode;if(n==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const s=jT(r.cues,e,t);for(let o=0;o<s.length;o++)(!i||i(s[o]))&&r.removeCue(s[o])}n==="disabled"&&(r.mode=n)}function JT(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let i=0,n=t,s;for(;i<=n;)if(s=Math.floor((n+i)/2),e<r[s].startTime)n=s-1;else if(e>r[s].startTime&&i<t)i=s+1;else return s;return r[i].startTime-e<e-r[n].startTime?i:n}function jT(r,e,t){const i=[],n=JT(r,e);if(n>-1)for(let s=n,o=r.length;s<o;s++){const a=r[s];if(a.startTime>=e&&a.endTime<=t)i.push(a);else if(a.startTime>t)return i}return i}function wo(r){const e=[];for(let t=0;t<r.length;t++){const i=r[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(r[t])}return e}class XT extends tA{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=wo(this.media.textTracks);for(let s=0;s<i.length;s++)if(i[s].mode==="hidden")t=i[s];else if(i[s].mode==="showing"){t=i[s];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;wo(i.textTracks).forEach(o=>{Kr(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:s}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let s=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,c)=>{u.id=c});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;const u=ci(a,o);if(u>-1)s=o[u];else{const c=ci(a,this.tracks);s=this.tracks[c]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const A={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,A),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const s=t[n];if(!(i&&!s.default||!i&&!e)&&(!e||mr(s,e)))return n}if(e){for(let n=0;n<t.length;n++){const s=t[n];if(Kn(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const s=t[n];if(Kn(e.attrs,s.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(iA(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Me.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&mr(e,i))return i;const n=ci(e,this.tracksInGroup);if(n>-1){const s=this.tracksInGroup[n];return this.setSubtitleTrack(n),s}else{if(i)return null;{const s=ci(e,t);if(s>-1)return t[s]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=wo(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(s=>iA(i,s))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(s=>{s.mode!=="disabled"&&s!==n&&(s.mode="disabled")}),n){const s=this.subtitleDisplay?"showing":"hidden";n.mode!==s&&(n.mode=s)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!de(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:a="",name:l,type:A,url:u}=n;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:A,url:u});const c=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(c)}}function qn(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const Wr=.025;let Ro=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function zT(r,e,t){return`${r.identifier}-${t+1}-${qn(e)}`}class ZT{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){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;return e<=0||isNaN(t)?!1:this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return AA(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=AA(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=de(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return AA(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Wr))}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(){const e=this.playoutLimit;let 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"?Ro.Range:Ro.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 e1(this)}}function AA(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<Wr)?e.start:e.start+e.duration}function Gf(r,e,t){const i=new self.URL(r,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function e1(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function cA(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class t1{constructor(e,t,i,n){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=()=>{const A=this.interstitial.playoutLimit,u=this.currentTime;this.startOffset+u>=A&&this.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=i,this.assetItem=n;let o=n.uri;try{o=Gf(o,s.sessionId).href}catch{}s.loadSource(o);const a=()=>{this.hasDetails=!0};s.once(I.LEVEL_LOADED,a),s.once(I.AUDIO_TRACK_LOADED,a),s.once(I.SUBTITLE_TRACK_LOADED,a),s.on(I.MEDIA_ATTACHING,(l,{media:A})=>{this.removeMediaListeners(),this.mediaAttached=A,this.interstitial.playoutLimit&&A.addEventListener("timeupdate",this.checkPlayout)})}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,n=Le.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=this._bufferedEosTime-.02}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(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Le.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>11111111111111112e-21){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const 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.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${cA(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const $f=.033;class i1 extends Ti{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(s=n[i])!=null&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;n<i.length;n++){let s=i[n];if(t&&t!=="primary"&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return n}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let n=e;n<=t&&i[n];n++){const s=i[n].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var i;if(((i=t[n].event)==null?void 0:i.identifier)===e)return n}return-1}findAssetIndex(e,t){const i=e.assetList,n=i.length;if(n>1)for(let s=0;s<n;s++){const o=i[s];if(!o.error){const a=o.timelineStart;if(t===a||t>a&&t<a+(o.duration||0))return s}}return 0}get assetIdAtEnd(){var e,t;const i=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(i){const n=i.assetList,s=n[n.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:n}=i,s=this.events,o=this.parseDateRanges(n,{url:i.url},t),a=Object.keys(n),l=s?s.filter(A=>!a.includes(A.identifier)):[];o.length&&o.sort((A,u)=>{const c=A.cue.pre,h=A.cue.post,d=u.cue.pre,f=u.cue.post;if(c&&!d)return-1;if(d&&!c||h&&!f)return 1;if(f&&!h)return-1;if(!c&&!d&&!h&&!f){const g=A.startTime,p=u.startTime;if(g!==p)return g-p}return A.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,l.forEach(A=>{this.removeEvent(A)}),this.updateSchedule(e,l)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const n=this.items,s=this.parseSchedule(i,e);(t.length||(n==null?void 0:n.length)!==s.length||s.some((a,l)=>Math.abs(a.playout.start-n[l].playout.start)>.005||Math.abs(a.playout.end-n[l].playout.end)>.005))&&(this.items=s,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,i){const n=[],s=Object.keys(e);for(let o=0;o<s.length;o++){const a=s[o],l=e[a];if(l.isInterstitial){let A=this.eventMap[a];A?A.setDateRange(l):(A=new ZT(l,t),this.eventMap[a]=A,i===!1&&(A.appendInPlace=i)),n.push(A)}}return n}parseSchedule(e,t){const i=[],n=t.main.details,s=n.live?1/0:n.edge;let o=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,A=0;if(e.forEach((u,c)=>{const h=u.cue.pre,d=u.cue.post,f=e[c-1]||null,g=u.appendInPlace,p=d?s:u.startOffset,v=u.duration,B=u.timelineOccupancy===Ro.Range?v:0,C=u.resumptionOffset,y=(f==null?void 0:f.startTime)===p,x=p+u.cumulativeDuration;let w=g?x+v:p+C;if(h||!d&&p<=0){const F=A;A+=B,u.timelineStart=x;const O=o;o+=v,i.push({event:u,start:x,end:w,playout:{start:O,end:o},integrated:{start:F,end:A}})}else if(p<=s){if(!y){const M=p-l;if(M>$f){const j=l,X=A;A+=M;const le=o;o+=M;const oe={previousEvent:e[c-1]||null,nextEvent:u,start:j,end:j+M,playout:{start:le,end:o},integrated:{start:X,end:A}};i.push(oe)}else M>0&&f&&(f.cumulativeDuration+=M,i[i.length-1].end=p)}d&&(w=x),u.timelineStart=x;const F=A;A+=B;const O=o;o+=v,i.push({event:u,start:x,end:w,playout:{start:O,end:o},integrated:{start:F,end:A}})}else return;const D=u.resumeTime;d||D>s?l=s:l=D}),l<s){var a;const u=l,c=A,h=s-l;A+=h;const d=o;o+=h,i.push({previousEvent:((a=i[i.length-1])==null?void 0:a.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:d,end:o},integrated:{start:c,end:A}})}this.setDurations(s,o,A)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,n=i.live?1/0:i.edge;let s=0,o=-1;e.forEach((a,l)=>{const A=a.cue.pre,u=a.cue.post,c=A?0:u?n:a.startTime;this.updateAssetDurations(a),o===c?a.cumulativeDuration=s:(s=0,o=c),!u&&a.snapOptions.in&&(a.resumeAnchor=Ir(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<$f&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const d=de(a.resumeOffset)?a.resumeOffset:a.duration;s+=d})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>Wr?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):t?!Object.keys(t).some(o=>{const a=t[o].details,l=a.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${l}`),!1;const A=Ir(null,a.fragments,i);if(!A)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const u=o==="audio"?.175:0;return Math.abs(A.start-i)<Wr+u||Math.abs(A.end-i)<Wr+u?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${o} fragment bounds (${A.start}-${A.end} sn: ${A.sn} cc: ${A.cc})`),!0)}):(this.log(`"${e.identifier}" resumption ${i} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,n=!1,s=!1;e.assetList.forEach((o,a)=>{const l=t+i;o.startOffset=i,o.timelineStart=l,n||(n=o.duration===null),s||(s=!!o.error);const A=o.error?0:o.duration||0;i+=A}),n&&!s?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Xi(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class r1{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let n;try{n=Gf(i,this.hls.sessionId,e.baseUrl)}catch(h){const d=this.assignAssetListError(e,V.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(I.ERROR,d);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,o=s.loader,a=new o(s),l={responseType:"json",url:n.href},A=s.interstitialAssetListLoadPolicy.default,u={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,d,f,g)=>{const p=h.data,v=p==null?void 0:p.ASSETS;if(!Array.isArray(v)){const B=this.assignAssetListError(e,V.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,d,g);this.hls.trigger(I.ERROR,B);return}e.assetListResponse=p,this.hls.trigger(I.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:g})},onError:(h,d,f,g)=>{const p=this.assignAssetListError(e,V.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${d.url})`),d.url,g,f);this.hls.trigger(I.ERROR,p)},onTimeout:(h,d,f)=>{const g=this.assignAssetListError(e,V.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${d.url})`),d.url,h,f);this.hls.trigger(I.ERROR,g)}};return a.load(l,u,c),this.hls.trigger(I.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,n,s,o){return e.error=i,{type:Ie.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:s}}}function Qi(r,e,t){fi(r,e,t),r.addEventListener(e,t)}function fi(r,e,t){r.removeEventListener(e,t)}function Hf(r){r==null||r.play().catch(()=>{})}class n1 extends Ti{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(),this.checkBuffer(),o&&i<a.start||i>=a.end){var l;const h=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(a)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!o){const d=this.findItemIndex(a);if(h>d){const f=this.schedule.findJumpRestrictedIndex(d+1,h);if(f>d){this.setSchedulePosition(f);return}}}this.setSchedulePosition(h);return}const A=this.playingAsset;if(!A){if(this.playingLastItem&&this.isInterstitial(a)){const h=a.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,h))}return}const u=A.timelineStart,c=A.duration||0;(o&&i<u||i>=u+c)&&this.setScheduleToAssetAtTime(i,A)},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const a=this.findItemIndex(n);this.setSchedulePosition(a+1)}const s=this.playingAsset;if(!s)return;const o=s.timelineStart+(s.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,s)},this.onScheduleUpdate=(i,n)=>{const s=this.schedule,o=this.playingItem,a=s.events||[],l=s.items||[],A=s.durations,u=i.map(d=>d.identifier),c=!!(a.length||u.length);if(c&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
2513
2513
  Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.playerQueue.forEach(d=>{if(d.interstitial.appendInPlace){const f=d.assetItem.timelineStart,g=d.timelineOffset-f;if(g)try{d.timelineOffset=f}catch(p){Math.abs(g)>Wr&&this.warn(`${p} ("${d.assetId}" ${d.timelineOffset}->${f})`)}}}),o){const d=this.updateItem(o,this.timelinePos);this.itemsMatch(o,d)&&(this.playingItem=d,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const d=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,d)?this.bufferingItem=d:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(i.forEach(d=>{d.assetList.forEach(f=>{this.clearAssetPlayer(f.identifier,null)})}),c||n){if(this.hls.trigger(I.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:l.slice(0),durations:A,removedIds:u}),this.isInterstitial(o)&&u.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new r1(e),this.schedule=new i1(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(I.MEDIA_ENDED,this.onMediaEnded,this),e.on(I.ERROR,this.onError,this),e.on(I.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(I.MEDIA_ENDED,this.onMediaEnded,this),e.off(I.ERROR,this.onError,this),e.off(I.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.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){fi(e,"play",this.onPlay),fi(e,"pause",this.onPause),fi(e,"seeking",this.onSeeking),fi(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Qi(i,"seeking",this.onSeeking),Qi(i,"timeupdate",this.onTimeupdate),Qi(i,"play",this.onPlay),Qi(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(i);this.setSchedulePosition(s)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),n=(c,h,d,f,g)=>{if(c){let p=c[h].start;const v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==Ro.Point){const B=i(d);(B==null?void 0:B.interstitial)===v&&(p+=B.assetItem.startOffset+B[g])}}else{const B=f==="bufferedPos"?o():e[f];p+=B-c.start}return p}return 0},s=(c,h)=>{if(c!==0&&h!=="primary"&&e.schedule.length){var d;const f=e.schedule.findItemIndexAtTime(c),g=(d=e.schedule.items)==null?void 0:d[f];if(g){const p=g[h].start-g.start;return c+p}}return c},o=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?a("primary"):Math.max(c,0)},a=c=>{var h;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:e.schedule.durations[c]},l=(c,h)=>{var d,f;const g=e.effectivePlayingItem;if(g!=null&&(d=g.event)!=null&&d.restrictions.skip)return;e.log(`seek to ${c} "${h}"`);const p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),B=(f=e.schedule.items)==null?void 0:f[v],C=e.getBufferingPlayer(),y=C==null?void 0:C.interstitial,x=y==null?void 0:y.appendInPlace,w=p&&e.itemsMatch(p,B);if(p&&(x||w)){const F=i(e.playingAsset),O=(F==null?void 0:F.media)||e.primaryMedia;if(O){const M=h==="primary"?O.currentTime:n(p,h,e.playingAsset,"timelinePos","currentTime"),j=c-M,X=(x?M:O.currentTime)+j;if(X>=0&&(!F||x||X<=F.duration)){O.currentTime=X;return}}}if(B){let F=c;if(h!=="primary"){const M=B[h].start,j=c-M;F=B.start+j}const O=!e.isInterstitial(B);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(O||B.event.appendInPlace)){const M=e.media||(x?C==null?void 0:C.media:null);M&&(M.currentTime=F)}else if(p){const M=e.findItemIndex(p);if(v>M){const X=e.schedule.findJumpRestrictedIndex(M+1,v);if(X>M){e.setSchedulePosition(X);return}}let j=0;if(O)e.timelinePos=F,e.checkBuffer();else{var D;const X=B==null||(D=B.event)==null?void 0:D.assetList;if(X){const le=c-(B[h]||B).start;for(let oe=X.length;oe--;){const L=X[oe];if(L.duration&&le>=L.startOffset&&le<L.startOffset+L.duration){j=oe;break}}}}e.setSchedulePosition(v,j)}}},A=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},u={get currentTime(){const c=A(),h=e.effectivePlayingItem;return h&&h===c?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=A(),d=e.effectivePlayingItem;d&&d===h&&l(c+d.playout.start,"playout")},get duration(){const c=A();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=A())==null?void 0:c.event.assetList;return h?h.map(d=>e.getAssetPlayer(d.identifier)):[]},get playingIndex(){var c;const h=(c=A())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return A()}};this.manager={get events(){var c,h;return((c=e.schedule)==null||(h=c.events)==null?void 0:h.slice(0))||[]},get schedule(){var c,h;return((c=e.schedule)==null||(h=c.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return A()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return o()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return a("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return a("integrated")},get seekableStart(){var c;return s(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){const d=e.findItemIndex(c);if(h.appendInPlace){const f=c.playout.start+c.event.duration;l(f+.001,"playout")}else e.advanceAfterAssetEnded(h,d,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,i;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(s=this.primaryMedia);const o=(i=s)==null?void 0:i.currentTime;if(!(o===void 0||!de(o)))return o}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){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${it(s)}`),this.detachedData=s}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let s=null;const o=this.hls,a=e!==o,l=a&&e.interstitial.appendInPlace,A=(i=this.detachedData)==null?void 0:i.mediaSource;let u;if(o.media)l&&(s=o.transferMedia(),this.detachedData=s),u="Primary";else if(A){const d=this.getBufferingPlayer();d?(s=d.transferMedia(),u=`${d}`):u="detached MediaSource"}else u="detached media";if(!s){if(A)s=this.detachedData,this.log(`using detachedData: MediaSource ${it(s)}`);else if(!this.detachedData||o.media===t){const d=this.playerQueue;d.length>1&&d.forEach(f=>{if(a&&f.interstitial.appendInPlace!==l){const g=f.interstitial;this.clearInterstitial(f.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}}}const c=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",h=c&&s?s:t;if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${u}`),h===s){const d=a&&e.assetId===this.schedule.assetIdAtEnd;h.overrides={duration:this.schedule.duration,endOfStream:!a||d,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const s=this.hls.startPosition;if(this.timelinePos=s,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(s>=0||!this.primaryLive){const o=this.timelinePos=s>0?s:0,a=e.findItemIndexAtTime(o);this.setSchedulePosition(a)}}else if(n&&!this.playingItem){const s=e.findItemIndex(n);this.setSchedulePosition(s)}}advanceAfterAssetEnded(e,t,i){const n=i+1;if(!e.isAssetPastPlayoutLimit(n)&&!e.assetList[n].error)this.setSchedulePosition(t,n);else{const s=this.schedule.items;if(s){const o=t+1,a=s.length;if(o>=a){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.timelinePos=l,this.checkBuffer()),this.setSchedulePosition(o)}}}setScheduleToAssetAtTime(e,t){const i=this.schedule,n=t.parentIdentifier,s=i.getEvent(n);if(s){const o=i.findEventIndex(n),a=i.findAssetIndex(s,e);this.setSchedulePosition(o,a)}}setSchedulePosition(e,t){const i=this.schedule.items;if(!i||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const n=e>=0?i[e]:null,s=this.playingItem,o=this.playingLastItem;if(this.isInterstitial(s)){var a;const A=s.event,u=this.playingAsset,c=u==null?void 0:u.identifier,h=c?this.getAssetPlayer(c):null;if(h&&c&&(!this.eventItemsMatch(s,n)||t!==void 0&&c!==((a=A.assetList)==null?void 0:a[t].identifier))){var l;const d=A.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${d+1}/${A.assetList.length} ${cA(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:d,event:A,schedule:i.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(c,n),h.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&h.detachMedia()}if(!this.eventItemsMatch(s,n)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${A} ${Xi(s)}`),A.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:A,schedule:i.slice(0),scheduleIndex:e}),A.cue.once)){this.updateSchedule();const d=this.schedule.items;if(n&&d){const f=this.schedule.findItemIndex(n);this.advanceSchedule(f,d,t,s,o)}return}}this.advanceSchedule(e,i,t,s,o)}advanceSchedule(e,t,i,n,s){const o=e>=0?t[e]:null,a=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(A=>{const u=A.interstitial,c=this.schedule.findEventIndex(u.identifier);(c<e||c>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const A=o.event;i===void 0&&(i=this.schedule.findAssetIndex(A,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(o,a)||this.setBufferingItem(o);let c=this.preloadAssets(A,i);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Xi(o)} ${A.appendInPlace?"append in place":""}`),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:A,schedule:t.slice(0),scheduleIndex:e})),!A.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${A}`);return}if(A.assetListLoader&&(A.assetListLoader.destroy(),A.assetListLoader=void 0),!a){this.log(`Waiting for attachMedia to start Interstitial ${A}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const h=A.assetList[i];if(!h){const d=t[e+1],f=this.media;d&&f&&!this.isInterstitial(d)&&f.currentTime<d.start&&(f.currentTime=this.timelinePos=d.start),this.advanceAfterAssetEnded(A,e,i||0);return}if(c||(c=this.getAssetPlayer(h.identifier)),c===null||c.destroyed){const d=A.assetList.length;this.warn(`asset ${i+1}/${d} player destroyed ${A}`),c=this.createAssetPlayer(A,h,i)}if(!this.eventItemsMatch(o,this.bufferingItem)&&A.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(c,i,t,e,a),this.shouldPlay&&Hf(c.media)}else o!==null?(this.resumePrimary(o,e,n),this.shouldPlay&&Hf(this.hls.media)):s&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e,t;return(e=this.mediaSelection)==null||(t=e.main)==null?void 0:t.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Xi(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;const s=this.schedule.items;s&&(this.log(`resumed ${Xi(e)}`),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(i<n.fragmentStart||i>n.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Le.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(I.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(I.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1)return;const i=this.hls.levels[t.level],n=Ye(Ye({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{audio:i});return}const s=Ye(Ye({},n),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{subtitles:i});return}const s=Ye(Ye({},n),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){const i=ld(t);this.playerQueue.forEach(n=>n.hls.setAudioOption(t)||n.hls.setAudioOption(i))}onSubtitleTrackSwitch(e,t){const i=ld(t);this.playerQueue.forEach(n=>n.hls.setSubtitleOption(t)||t.id!==-1&&n.hls.setSubtitleOption(i))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const s=t[n];if(s.cue.post){var i;const o=this.schedule.findEventIndex(s.identifier),a=(i=this.schedule.items)==null?void 0:i[o];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){const i=this.schedule.items;if(e&&i){const n=this.findItemIndex(e,t);return i[n]||null}return null}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const i=Le.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}updateBufferedPos(e,t,i){const n=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e)return;if(t.length===1&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}const o=this.playingItem,a=this.findItemIndex(o);let l=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var A,u;const c=this.findItemIndex(s),h=Math.min(c+1,t.length-1),d=t[h];if((l===-1&&s&&e>=s.end||(A=d.event)!=null&&A.appendInPlace&&e+.01>=d.start)&&(l=h),h-a>1&&(s==null||(u=s.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=e,l>c&&l>a)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&o&&!this.itemsMatch(o,s)&&(l===a?this.bufferedToItem(o):l===a+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const s=this.getAssetPlayer(n.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:n,events:s}=i;if(!n||!s)return t;const o=this.isInterstitial(e),a=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const l=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${Xi(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),o?e.event.assetList.forEach(A=>{const u=this.getAssetPlayer(A.identifier);u&&u.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(A=>A.pauseBuffering()))}this.hls.trigger(I.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,s=i.cue.once;if(n||!s){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const a=i.assetList[t],l=this.primaryMedia;a&&l&&this.bufferAssetPlayer(o,l)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,o=e.cue.once;if(s){const l=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let A,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const h=u-l;h>0&&(A=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${A?` live-start: ${u} start-offset: ${A}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const c=this.assetListLoader.loadAssetList(e,A);c&&(e.assetListLoader=c)}else if(!o&&n){for(let l=t;l<n;l++){const A=e.assetList[l],u=this.getAssetPlayerQueueIndex(A.identifier);(u===-1||this.playerQueue[u].destroyed)&&!A.error&&this.createAssetPlayer(e,A,l)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,n,s,o){const a={parentIdentifier:e.identifier,identifier:zT(e,o,t),duration:s,startOffset:i,timelineStart:n,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){this.log(`create HLSAssetPlayer for ${cA(t)}`);const n=this.hls,s=n.userConfig;let o=s.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(o||a)&&(o=We({},o),a.videoCodec&&(o.videoCodec=a.videoCodec),a.videoRange&&(o.allowedVideoRanges=[a.videoRange]));const l=n.audioTracks[n.audioTrack],A=n.subtitleTracks[n.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const C=this.timelinePos-t.timelineStart;if(C>1){const y=t.duration;y&&C<y&&(u=C)}}const c=t.identifier,h=Ye(Ye({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||s.audioPreference,subtitlePreference:A||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const d=h.cmcd;d!=null&&d.sessionId&&d.contentId&&(h.cmcd=We({},d,{contentId:qn(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new t1(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[i]=t;const g=C=>{if(C.live){const w=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:w};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),i,w.message);return}const y=C.edge-C.fragmentStart,x=t.duration;(x===null||y>x)&&(this.log(`Interstitial asset "${c}" duration change ${x} > ${y}`),t.duration=y,this.updateSchedule())};f.on(I.LEVEL_UPDATED,(C,{details:y})=>g(y)),f.on(I.LEVEL_PTS_UPDATED,(C,{details:y})=>g(y));const p=(C,y)=>{const x=this.getAssetPlayer(c);if(x&&y.tracks){x.off(I.BUFFER_CODECS,p),x.tracks=y.tracks;const w=this.primaryMedia;this.bufferingAsset===x.assetItem&&w&&!x.media&&this.bufferAssetPlayer(x,w)}};f.on(I.BUFFER_CODECS,p);const v=()=>{var C;const y=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${y}`),!y)return;const x=this.schedule.findEventIndex(e.identifier),w=e.findAssetIndex(t),D=w+1,F=(C=this.schedule.items)==null?void 0:C[x];if(this.isInterstitial(F))if(w!==-1&&!e.isAssetPastPlayoutLimit(D)&&!e.assetList[D].error)this.bufferedToItem(F,D);else{var O;const M=(O=this.schedule.items)==null?void 0:O[x+1];M&&this.bufferedToItem(M)}};f.on(I.BUFFERED_TO_END,v);const B=C=>()=>{if(!this.getAssetPlayer(c))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,C)};return f.once(I.MEDIA_ENDED,B(i)),f.once(I.PLAYOUT_LIMIT_REACHED,B(1/0)),f.on(I.ERROR,(C,y)=>{const x=this.getAssetPlayer(c);if(y.details===V.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const w=x.currentTime,D=x.duration-w;w&&e.appendInPlace&&D/x.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${c} ${e} at ${x.media.currentTime}`),v()):(this.warn(`Stalled at ${w} of ${w+D} in asset ${c} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(y,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${y.error} ${e}`)}),f.on(I.DESTROYING,()=>{if(!this.getAssetPlayer(c))return;const y=new Error(`Asset player destroyed unexpectedly ${c}`),x={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:y};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),i,y.message)}),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&Xi(t)}`);const n=this.playerQueue[i];this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,s){const{interstitial:o,assetItem:a,assetId:l}=e,A=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,i[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${A} ${e}`),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i,n;const{interstitial:s,assetItem:o,assetId:a}=e,l=this.schedule.findEventIndex(s.identifier),A=(i=this.schedule.items)==null?void 0:i[l];if(!A)return;this.setBufferingItem(A),this.bufferingAsset=o;const u=this.getBufferingPlayer();if(u===e)return;const c=s.appendInPlace;if(c&&(u==null?void 0:u.interstitial.appendInPlace)===!1)return;const h=(u==null?void 0:u.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(c&&o!==this.playingAsset){if(!e.tracks)return;if(h&&!Fh(h,e.tracks)){const d=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=s.findAssetIndex(o);this.handleAssetItemError(f,s,l,g,d.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,n,s){if(e.details===V.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;let a=null;if(o){const c=this.getAssetPlayerQueueIndex(o.identifier);a=this.playerQueue[c]||null}const l=this.schedule.items,A=We({},e,{fatal:!1,errorAction:Nn(!0),asset:o,assetListIndex:n,event:t,schedule:l,scheduleIndex:i,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,A),!e.fatal)return;const u=new Error(s);o&&(this.playingAsset!==o&&this.clearAssetPlayer(o.identifier,null),o.error=u),t.assetList.some(c=>!c.error)?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?Xi(i):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let n=this.timelinePos;n===-1&&(n=this.hls.startPosition);const s=this.updateItem(i,n);if(this.itemsMatch(i,s))this.clearInterstitial(e,null);else{const o=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const n=t.event,s=n.identifier,o=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(s))return;const a=n.timelineStart,l=n.duration;let A=0;o.forEach((f,g)=>{const p=parseFloat(f.DURATION);this.createAsset(n,g,A,a+A,p,f.URI),A+=p}),n.duration=A,this.log(`Loaded asset-list with duration: ${A} (was: ${l}) ${n}`);const u=this.waitingItem,c=(u==null?void 0:u.event.identifier)===s;this.updateSchedule();const h=(i=this.bufferingItem)==null?void 0:i.event;if(c){var d;const f=this.schedule.findEventIndex(s),g=(d=this.schedule.items)==null?void 0:d[f];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==f){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(f)}else if((h==null?void 0:h.identifier)===s&&h.appendInPlace){const f=n.assetList[0],g=this.getAssetPlayer(f.identifier),p=this.primaryMedia;f&&g&&p&&this.bufferAssetPlayer(g,p)}}onError(e,t){switch(t.details){case V.ASSET_LIST_PARSING_ERROR:case V.ASSET_LIST_LOAD_ERROR:case V.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&this.primaryFallback(i);break}case V.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Yf=500;class s1 extends Ul{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",Ee.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Z.IDLE,this.setInterval(Yf),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(vt(i)&&(this.fragPrevious=i),this.state=Z.IDLE,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let o;const a=i.start;for(let A=0;A<s.length;A++)if(a>=s[A].start&&a<=s[A].end){o=s[A];break}const l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},s.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const s=n-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=s){o.shift();continue}else if(o[a].start<s)o[a].start=s;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(i,s,Ee.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===Ee.SUBTITLE&&(t.details===V.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Z.STOPPED&&(this.state=Z.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&bf(this.levels,t)){this.levels=t.map(i=>new Pn(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new Pn(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ee.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Z.STOPPED&&this.setInterval(Yf)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:s}=this,{details:o,id:a}=t;if(!s){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=s[a];if(a>=s.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let A=0;if(o.live||(i=l.details)!=null&&i.live){const c=this.mainDetails;if(o.deltaUpdateFailed||!c)return;const h=c.fragments[0];if(!l.details)o.hasProgramDateTime&&c.hasProgramDateTime?(yo(o,c),A=o.fragmentStart):h&&(A=h.start,Ol(o,A));else{var u;A=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),A===0&&h&&(A=h.start,Ol(o,A))}}l.details=o,this.levelLastLoaded=l,a===n&&(this.hls.trigger(I.SUBTITLE_TRACK_UPDATED,{details:o,id:a,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===Z.IDLE&&(Ir(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Ur(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,wl(n.method)).catch(a=>{throw s.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const l=performance.now();s.trigger(I.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=Z.IDLE})}}doTick(){if(!this.media){this.state=Z.IDLE;return}if(this.state===Z.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,s=this.getLoadPosition(),o=Le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:l}=o,A=i.details,u=this.hls.maxBufferLength+A.levelTargetDuration;if(l>u)return;const c=A.fragments,h=c.length,d=A.edge;let f=null;const g=this.fragPrevious;if(a<d){const B=n.maxFragLookUpTolerance,C=a>d-B?0:B;f=Ir(g,c,Math.max(c[0].start,a),C),!f&&g&&g.start<c[0].start&&(f=c[0])}else f=c[h-1];if(f=this.filterReplacedPrimary(f,i.details),!f)return;const p=f.sn-A.startSN,v=c[p-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===Et.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===Et.NOT_LOADED){const B=this.mapToInitFragWhenRequired(f);B&&this.loadFragment(B,i,a)}}}loadFragment(e,t,i){vt(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new o1(this.tracksBuffered[this.currentTrackId]||[])}}class o1{constructor(e){this.buffered=void 0;const t=(i,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const a1={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},Vf=r=>String.fromCharCode(a1[r]||r),ti=15,_i=100,l1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},A1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},c1={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},u1={25:2,26:4,29:6,30:8,31:10,27:13,28:15},h1=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class d1{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Oe.log(`${this.time} [${e}] ${i}`)}}}const vr=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Kf{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const n=t[i];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class f1{constructor(){this.uchar=" ",this.penState=new Kf}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class g1{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Kf,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<_i;t++)this.chars.push(new f1);this.logger=e}equals(e){for(let t=0;t<_i;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<_i;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<_i;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>_i&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=_i)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Vf(e);if(this.pos>=_i){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<_i;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<_i;i++){const n=this.chars[i].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class uA{constructor(e){this.rows=[],this.currRow=ti-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ti;t++)this.rows.push(new g1(e));this.logger=e}reset(){for(let e=0;e<ti;e++)this.rows[e].clear();this.currRow=ti-1}equals(e){let t=!0;for(let i=0;i<ti;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<ti;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ti;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 = "+it(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<ti;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[s].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let A=0;A<this.nrRollUpRows;A++)this.rows[t-this.nrRollUpRows+A+1].copy(o.rows[s+A])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,o=Math.max(s-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+it(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let s=0;s<ti;s++){const o=this.rows[s].getTextString();o&&(n=s+1,e?t.push("Row "+n+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
2514
2514
  `)),i}getTextAndFormat(){return this.rows}}class Wf{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new uA(i),this.nonDisplayedMemory=new uA(i),this.lastOutputScreen=new uA(i),this.currRollUpRow=this.displayedMemory.rows[ti-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[ti-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const 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"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class qf{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=m1(),this.logger=void 0;const n=this.logger=new d1;this.channels=[null,new Wf(e,t,n),new Wf(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const n=t[i]&127,s=t[i+1]&127;let o=!1,a=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+vr([t[i],t[i+1]])+"] -> ("+vr([n,s])+")");const l=this.cmdHistory;if(n>=16&&n<=31){if(p1(n,s,l)){Do(null,null,l),this.logger.log(3,()=>"Repeated command ("+vr([n,s])+") is dropped");continue}Do(n,s,this.cmdHistory),o=this.parseCmd(n,s),o||(o=this.parseMidrow(n,s)),o||(o=this.parsePAC(n,s)),o||(o=this.parseBackgroundAttributes(n,s))}else Do(null,null,l);if(!o&&(a=this.parseChars(n,s),a)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+vr([n,s])+" orig: "+vr([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const s=e===20||e===21||e===23?1:2,o=this.channels[s];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+vr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(e===16||e===24)&&t>=64&&t<=95;if(!(n||s))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?l1[e]:c1[e]:i=o===1?A1[e]:u1[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let o;s===17?o=t+80:s===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+Vf(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+vr(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let s;const o={};e===16||e===24?(s=Math.floor((t-32)/2),o.background=h1[s],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Do(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Do(r,e,t){t.a=r,t.b=e}function p1(r,e,t){return t.a===r&&t.b===e}function m1(){return{a:null,b:null}}var hA=function(){if(mo!=null&&mo.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const A=l.toLowerCase();return~a.indexOf(A)?A:!1}function i(a){return t(r,a)}function n(a){return t(e,a)}function s(a,...l){let A=1;for(;A<arguments.length;A++){const u=arguments[A];for(const c in u)a[c]=u[c]}return a}function o(a,l,A){const u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",d=!1,f=a,g=l,p=A,v=null,B="",C=!0,y="auto",x="start",w=50,D="middle",F=50,O="middle";Object.defineProperty(u,"id",s({},c,{get:function(){return h},set:function(M){h=""+M}})),Object.defineProperty(u,"pauseOnExit",s({},c,{get:function(){return d},set:function(M){d=!!M}})),Object.defineProperty(u,"startTime",s({},c,{get:function(){return f},set:function(M){if(typeof M!="number")throw new TypeError("Start time must be set to a number.");f=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",s({},c,{get:function(){return g},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");g=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",s({},c,{get:function(){return p},set:function(M){p=""+M,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},c,{get:function(){return v},set:function(M){v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},c,{get:function(){return B},set:function(M){const j=i(M);if(j===!1)throw new SyntaxError("An invalid or illegal string was specified.");B=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},c,{get:function(){return C},set:function(M){C=!!M,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},c,{get:function(){return y},set:function(M){if(typeof M!="number"&&M!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",s({},c,{get:function(){return x},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");x=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",s({},c,{get:function(){return w},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");w=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},c,{get:function(){return D},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");D=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",s({},c,{get:function(){return F},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");F=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",s({},c,{get:function(){return O},set:function(M){const j=n(M);if(!j)throw new SyntaxError("An invalid or illegal string was specified.");O=j,this.hasBeenReset=!0}})),u.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class E1{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Jf(r){function e(i,n,s,o){return(i|0)*3600+(n|0)*60+(s|0)+parseFloat(o||0)}const t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class I1{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n<i.length;++n)if(t===i[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function jf(r,e,t,i){const n=i?r.split(i):[r];for(const s in n){if(typeof n[s]!="string")continue;const o=n[s].split(t);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const dA=new hA(0,0,""),Lo=dA.align==="middle"?"middle":"center";function v1(r,e,t){const i=r;function n(){const a=Jf(r);if(a===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function s(a,l){const A=new I1;jf(a,function(h,d){let f;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===d){A.set(h,t[g].region);break}break;case"vertical":A.alt(h,d,["rl","lr"]);break;case"line":f=d.split(","),A.integer(h,f[0]),A.percent(h,f[0])&&A.set("snapToLines",!1),A.alt(h,f[0],["auto"]),f.length===2&&A.alt("lineAlign",f[1],["start",Lo,"end"]);break;case"position":f=d.split(","),A.percent(h,f[0]),f.length===2&&A.alt("positionAlign",f[1],["start",Lo,"end","line-left","line-right","auto"]);break;case"size":A.percent(h,d);break;case"align":A.alt(h,d,["start",Lo,"end","left","right"]);break}},/:/,/\s/),l.region=A.get("region",null),l.vertical=A.get("vertical","");let u=A.get("line","auto");u==="auto"&&dA.line===-1&&(u=-1),l.line=u,l.lineAlign=A.get("lineAlign","start"),l.snapToLines=A.get("snapToLines",!0),l.size=A.get("size",100),l.align=A.get("align",Lo);let c=A.get("position","auto");c==="auto"&&dA.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function o(){r=r.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),o(),e.endTime=n(),o(),s(r,e)}function Xf(r){return r.replace(/<br(?: \/)?>/gi,`
@@ -2525,7 +2525,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2525
2525
  * @license
2526
2526
  * Copyright 2017 Google LLC
2527
2527
  * SPDX-License-Identifier: BSD-3-Clause
2528
- */const mg=(r,e,t)=>{const i=new Map;for(let n=e;n<=t;n++)i.set(r[n],n);return i},Eg=kr(class extends yn{constructor(r){if(super(r),r.type!==Lr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(r,e,t){let i;t===void 0?t=e:e!==void 0&&(i=e);const n=[],s=[];let o=0;for(const a of r)n[o]=i?i(a,o):o,s[o]=t(a,o),o++;return{values:s,keys:n}}render(r,e,t){return this.dt(r,e,t).values}update(r,[e,t,i]){const n=Ap(r),{values:s,keys:o}=this.dt(e,t,i);if(!Array.isArray(n))return this.ut=o,s;const a=this.ut??(this.ut=[]),l=[];let A,u,c=0,h=n.length-1,d=0,f=s.length-1;for(;c<=h&&d<=f;)if(n[c]===null)c++;else if(n[h]===null)h--;else if(a[c]===o[d])l[d]=ur(n[c],s[d]),c++,d++;else if(a[h]===o[f])l[f]=ur(n[h],s[f]),h--,f--;else if(a[c]===o[f])l[f]=ur(n[c],s[f]),vn(r,l[f+1],n[c]),c++,f--;else if(a[h]===o[d])l[d]=ur(n[h],s[d]),vn(r,n[c],n[h]),h--,d++;else if(A===void 0&&(A=mg(o,d,f),u=mg(a,c,h)),A.has(a[c]))if(A.has(a[h])){const g=u.get(o[d]),p=g!==void 0?n[g]:null;if(p===null){const v=vn(r,n[c]);ur(v,s[d]),l[d]=v}else l[d]=ur(p,s[d]),vn(r,n[c],p),n[g]=null;d++}else fa(n[h]),h--;else fa(n[c]),c++;for(;d<=f;){const g=vn(r,l[f+1]);ur(g,s[d]),l[d++]=g}for(;c<=h;){const g=n[c++];g!==null&&fa(g)}return this.ut=o,lp(r,l),Fi}});var Nt="top",Jt="bottom",jt="right",Ot="left",BA="auto",Jn=[Nt,Jt,jt,Ot],qr="start",jn="end",gS="clippingParents",Ig="viewport",Xn="popper",pS="reference",vg=Jn.reduce(function(r,e){return r.concat([e+"-"+qr,e+"-"+jn])},[]),yg=[].concat(Jn,[BA]).reduce(function(r,e){return r.concat([e,e+"-"+qr,e+"-"+jn])},[]),mS="beforeRead",ES="read",IS="afterRead",vS="beforeMain",yS="main",CS="afterMain",BS="beforeWrite",TS="write",SS="afterWrite",bS=[mS,ES,IS,vS,yS,CS,BS,TS,SS];function pi(r){return r?(r.nodeName||"").toLowerCase():null}function $t(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}function yr(r){var e=$t(r).Element;return r instanceof e||r instanceof Element}function Xt(r){var e=$t(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function TA(r){if(typeof ShadowRoot>"u")return!1;var e=$t(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}function xS(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];!Xt(s)||!pi(s)||(Object.assign(s.style,i),Object.keys(n).forEach(function(o){var a=n[o];a===!1?s.removeAttribute(o):s.setAttribute(o,a===!0?"":a)}))})}function QS(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(i){var n=e.elements[i],s=e.attributes[i]||{},o=Object.keys(e.styles.hasOwnProperty(i)?e.styles[i]:t[i]),a=o.reduce(function(l,A){return l[A]="",l},{});!Xt(n)||!pi(n)||(Object.assign(n.style,a),Object.keys(s).forEach(function(l){n.removeAttribute(l)}))})}}const Cg={name:"applyStyles",enabled:!0,phase:"write",fn:xS,effect:QS,requires:["computeStyles"]};function mi(r){return r.split("-")[0]}var Cr=Math.max,Po=Math.min,Jr=Math.round;function SA(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function Bg(){return!/^((?!chrome|android).)*safari/i.test(SA())}function jr(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var i=r.getBoundingClientRect(),n=1,s=1;e&&Xt(r)&&(n=r.offsetWidth>0&&Jr(i.width)/r.offsetWidth||1,s=r.offsetHeight>0&&Jr(i.height)/r.offsetHeight||1);var o=yr(r)?$t(r):window,a=o.visualViewport,l=!Bg()&&t,A=(i.left+(l&&a?a.offsetLeft:0))/n,u=(i.top+(l&&a?a.offsetTop:0))/s,c=i.width/n,h=i.height/s;return{width:c,height:h,top:u,right:A+c,bottom:u+h,left:A,x:A,y:u}}function bA(r){var e=jr(r),t=r.offsetWidth,i=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-i)<=1&&(i=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:i}}function Tg(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&TA(t)){var i=e;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function wi(r){return $t(r).getComputedStyle(r)}function _S(r){return["table","td","th"].indexOf(pi(r))>=0}function zi(r){return((yr(r)?r.ownerDocument:r.document)||window.document).documentElement}function No(r){return pi(r)==="html"?r:r.assignedSlot||r.parentNode||(TA(r)?r.host:null)||zi(r)}function Sg(r){return!Xt(r)||wi(r).position==="fixed"?null:r.offsetParent}function wS(r){var e=/firefox/i.test(SA()),t=/Trident/i.test(SA());if(t&&Xt(r)){var i=wi(r);if(i.position==="fixed")return null}var n=No(r);for(TA(n)&&(n=n.host);Xt(n)&&["html","body"].indexOf(pi(n))<0;){var s=wi(n);if(s.transform!=="none"||s.perspective!=="none"||s.contain==="paint"||["transform","perspective"].indexOf(s.willChange)!==-1||e&&s.willChange==="filter"||e&&s.filter&&s.filter!=="none")return n;n=n.parentNode}return null}function zn(r){for(var e=$t(r),t=Sg(r);t&&_S(t)&&wi(t).position==="static";)t=Sg(t);return t&&(pi(t)==="html"||pi(t)==="body"&&wi(t).position==="static")?e:t||wS(r)||e}function xA(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function Zn(r,e,t){return Cr(r,Po(e,t))}function RS(r,e,t){var i=Zn(r,e,t);return i>t?t:i}function bg(){return{top:0,right:0,bottom:0,left:0}}function xg(r){return Object.assign({},bg(),r)}function Qg(r,e){return e.reduce(function(t,i){return t[i]=r,t},{})}var DS=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,xg(typeof e!="number"?e:Qg(e,Jn))};function LS(r){var e,t=r.state,i=r.name,n=r.options,s=t.elements.arrow,o=t.modifiersData.popperOffsets,a=mi(t.placement),l=xA(a),A=[Ot,jt].indexOf(a)>=0,u=A?"height":"width";if(!(!s||!o)){var c=DS(n.padding,t),h=bA(s),d=l==="y"?Nt:Ot,f=l==="y"?Jt:jt,g=t.rects.reference[u]+t.rects.reference[l]-o[l]-t.rects.popper[u],p=o[l]-t.rects.reference[l],v=zn(s),B=v?l==="y"?v.clientHeight||0:v.clientWidth||0:0,C=g/2-p/2,y=c[d],x=B-h[u]-c[f],w=B/2-h[u]/2+C,D=Zn(y,w,x),F=l;t.modifiersData[i]=(e={},e[F]=D,e.centerOffset=D-w,e)}}function kS(r){var e=r.state,t=r.options,i=t.element,n=i===void 0?"[data-popper-arrow]":i;n!=null&&(typeof n=="string"&&(n=e.elements.popper.querySelector(n),!n)||Tg(e.elements.popper,n)&&(e.elements.arrow=n))}const MS={name:"arrow",enabled:!0,phase:"main",fn:LS,effect:kS,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Xr(r){return r.split("-")[1]}var FS={top:"auto",right:"auto",bottom:"auto",left:"auto"};function PS(r,e){var t=r.x,i=r.y,n=e.devicePixelRatio||1;return{x:Jr(t*n)/n||0,y:Jr(i*n)/n||0}}function _g(r){var e,t=r.popper,i=r.popperRect,n=r.placement,s=r.variation,o=r.offsets,a=r.position,l=r.gpuAcceleration,A=r.adaptive,u=r.roundOffsets,c=r.isFixed,h=o.x,d=h===void 0?0:h,f=o.y,g=f===void 0?0:f,p=typeof u=="function"?u({x:d,y:g}):{x:d,y:g};d=p.x,g=p.y;var v=o.hasOwnProperty("x"),B=o.hasOwnProperty("y"),C=Ot,y=Nt,x=window;if(A){var w=zn(t),D="clientHeight",F="clientWidth";if(w===$t(t)&&(w=zi(t),wi(w).position!=="static"&&a==="absolute"&&(D="scrollHeight",F="scrollWidth")),w=w,n===Nt||(n===Ot||n===jt)&&s===jn){y=Jt;var O=c&&w===x&&x.visualViewport?x.visualViewport.height:w[D];g-=O-i.height,g*=l?1:-1}if(n===Ot||(n===Nt||n===Jt)&&s===jn){C=jt;var M=c&&w===x&&x.visualViewport?x.visualViewport.width:w[F];d-=M-i.width,d*=l?1:-1}}var j=Object.assign({position:a},A&&FS),X=u===!0?PS({x:d,y:g},$t(t)):{x:d,y:g};if(d=X.x,g=X.y,l){var le;return Object.assign({},j,(le={},le[y]=B?"0":"",le[C]=v?"0":"",le.transform=(x.devicePixelRatio||1)<=1?"translate("+d+"px, "+g+"px)":"translate3d("+d+"px, "+g+"px, 0)",le))}return Object.assign({},j,(e={},e[y]=B?g+"px":"",e[C]=v?d+"px":"",e.transform="",e))}function NS(r){var e=r.state,t=r.options,i=t.gpuAcceleration,n=i===void 0?!0:i,s=t.adaptive,o=s===void 0?!0:s,a=t.roundOffsets,l=a===void 0?!0:a,A={placement:mi(e.placement),variation:Xr(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:n,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,_g(Object.assign({},A,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,_g(Object.assign({},A,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const OS={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:NS,data:{}};var Oo={passive:!0};function US(r){var e=r.state,t=r.instance,i=r.options,n=i.scroll,s=n===void 0?!0:n,o=i.resize,a=o===void 0?!0:o,l=$t(e.elements.popper),A=[].concat(e.scrollParents.reference,e.scrollParents.popper);return s&&A.forEach(function(u){u.addEventListener("scroll",t.update,Oo)}),a&&l.addEventListener("resize",t.update,Oo),function(){s&&A.forEach(function(u){u.removeEventListener("scroll",t.update,Oo)}),a&&l.removeEventListener("resize",t.update,Oo)}}const GS={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:US,data:{}};var $S={left:"right",right:"left",bottom:"top",top:"bottom"};function Uo(r){return r.replace(/left|right|bottom|top/g,function(e){return $S[e]})}var HS={start:"end",end:"start"};function wg(r){return r.replace(/start|end/g,function(e){return HS[e]})}function QA(r){var e=$t(r),t=e.pageXOffset,i=e.pageYOffset;return{scrollLeft:t,scrollTop:i}}function _A(r){return jr(zi(r)).left+QA(r).scrollLeft}function YS(r,e){var t=$t(r),i=zi(r),n=t.visualViewport,s=i.clientWidth,o=i.clientHeight,a=0,l=0;if(n){s=n.width,o=n.height;var A=Bg();(A||!A&&e==="fixed")&&(a=n.offsetLeft,l=n.offsetTop)}return{width:s,height:o,x:a+_A(r),y:l}}function VS(r){var e,t=zi(r),i=QA(r),n=(e=r.ownerDocument)==null?void 0:e.body,s=Cr(t.scrollWidth,t.clientWidth,n?n.scrollWidth:0,n?n.clientWidth:0),o=Cr(t.scrollHeight,t.clientHeight,n?n.scrollHeight:0,n?n.clientHeight:0),a=-i.scrollLeft+_A(r),l=-i.scrollTop;return wi(n||t).direction==="rtl"&&(a+=Cr(t.clientWidth,n?n.clientWidth:0)-s),{width:s,height:o,x:a,y:l}}function wA(r){var e=wi(r),t=e.overflow,i=e.overflowX,n=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+n+i)}function Rg(r){return["html","body","#document"].indexOf(pi(r))>=0?r.ownerDocument.body:Xt(r)&&wA(r)?r:Rg(No(r))}function es(r,e){var t;e===void 0&&(e=[]);var i=Rg(r),n=i===((t=r.ownerDocument)==null?void 0:t.body),s=$t(i),o=n?[s].concat(s.visualViewport||[],wA(i)?i:[]):i,a=e.concat(o);return n?a:a.concat(es(No(o)))}function RA(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function KS(r,e){var t=jr(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function Dg(r,e,t){return e===Ig?RA(YS(r,t)):yr(e)?KS(e,t):RA(VS(zi(r)))}function WS(r){var e=es(No(r)),t=["absolute","fixed"].indexOf(wi(r).position)>=0,i=t&&Xt(r)?zn(r):r;return yr(i)?e.filter(function(n){return yr(n)&&Tg(n,i)&&pi(n)!=="body"}):[]}function qS(r,e,t,i){var n=e==="clippingParents"?WS(r):[].concat(e),s=[].concat(n,[t]),o=s[0],a=s.reduce(function(l,A){var u=Dg(r,A,i);return l.top=Cr(u.top,l.top),l.right=Po(u.right,l.right),l.bottom=Po(u.bottom,l.bottom),l.left=Cr(u.left,l.left),l},Dg(r,o,i));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function Lg(r){var e=r.reference,t=r.element,i=r.placement,n=i?mi(i):null,s=i?Xr(i):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(n){case Nt:l={x:o,y:e.y-t.height};break;case Jt:l={x:o,y:e.y+e.height};break;case jt:l={x:e.x+e.width,y:a};break;case Ot:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var A=n?xA(n):null;if(A!=null){var u=A==="y"?"height":"width";switch(s){case qr:l[A]=l[A]-(e[u]/2-t[u]/2);break;case jn:l[A]=l[A]+(e[u]/2-t[u]/2);break}}return l}function ts(r,e){e===void 0&&(e={});var t=e,i=t.placement,n=i===void 0?r.placement:i,s=t.strategy,o=s===void 0?r.strategy:s,a=t.boundary,l=a===void 0?gS:a,A=t.rootBoundary,u=A===void 0?Ig:A,c=t.elementContext,h=c===void 0?Xn:c,d=t.altBoundary,f=d===void 0?!1:d,g=t.padding,p=g===void 0?0:g,v=xg(typeof p!="number"?p:Qg(p,Jn)),B=h===Xn?pS:Xn,C=r.rects.popper,y=r.elements[f?B:h],x=qS(yr(y)?y:y.contextElement||zi(r.elements.popper),l,u,o),w=jr(r.elements.reference),D=Lg({reference:w,element:C,placement:n}),F=RA(Object.assign({},C,D)),O=h===Xn?F:w,M={top:x.top-O.top+v.top,bottom:O.bottom-x.bottom+v.bottom,left:x.left-O.left+v.left,right:O.right-x.right+v.right},j=r.modifiersData.offset;if(h===Xn&&j){var X=j[n];Object.keys(M).forEach(function(le){var oe=[jt,Jt].indexOf(le)>=0?1:-1,L=[Nt,Jt].indexOf(le)>=0?"y":"x";M[le]+=X[L]*oe})}return M}function JS(r,e){e===void 0&&(e={});var t=e,i=t.placement,n=t.boundary,s=t.rootBoundary,o=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,A=l===void 0?yg:l,u=Xr(i),c=u?a?vg:vg.filter(function(f){return Xr(f)===u}):Jn,h=c.filter(function(f){return A.indexOf(f)>=0});h.length===0&&(h=c);var d=h.reduce(function(f,g){return f[g]=ts(r,{placement:g,boundary:n,rootBoundary:s,padding:o})[mi(g)],f},{});return Object.keys(d).sort(function(f,g){return d[f]-d[g]})}function jS(r){if(mi(r)===BA)return[];var e=Uo(r);return[wg(r),e,wg(e)]}function XS(r){var e=r.state,t=r.options,i=r.name;if(!e.modifiersData[i]._skip){for(var n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!0:o,l=t.fallbackPlacements,A=t.padding,u=t.boundary,c=t.rootBoundary,h=t.altBoundary,d=t.flipVariations,f=d===void 0?!0:d,g=t.allowedAutoPlacements,p=e.options.placement,v=mi(p),B=v===p,C=l||(B||!f?[Uo(p)]:jS(p)),y=[p].concat(C).reduce(function(ie,he){return ie.concat(mi(he)===BA?JS(e,{placement:he,boundary:u,rootBoundary:c,padding:A,flipVariations:f,allowedAutoPlacements:g}):he)},[]),x=e.rects.reference,w=e.rects.popper,D=new Map,F=!0,O=y[0],M=0;M<y.length;M++){var j=y[M],X=mi(j),le=Xr(j)===qr,oe=[Nt,Jt].indexOf(X)>=0,L=oe?"width":"height",U=ts(e,{placement:j,boundary:u,rootBoundary:c,altBoundary:h,padding:A}),q=oe?le?jt:Ot:le?Jt:Nt;x[L]>w[L]&&(q=Uo(q));var R=Uo(q),_=[];if(s&&_.push(U[X]<=0),a&&_.push(U[q]<=0,U[R]<=0),_.every(function(ie){return ie})){O=j,F=!1;break}D.set(j,_)}if(F)for(var k=f?3:1,K=function(he){var fe=y.find(function(_e){var Te=D.get(_e);if(Te)return Te.slice(0,he).every(function(Fe){return Fe})});if(fe)return O=fe,"break"},Y=k;Y>0;Y--){var te=K(Y);if(te==="break")break}e.placement!==O&&(e.modifiersData[i]._skip=!0,e.placement=O,e.reset=!0)}}const zS={name:"flip",enabled:!0,phase:"main",fn:XS,requiresIfExists:["offset"],data:{_skip:!1}};function kg(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function Mg(r){return[Nt,jt,Jt,Ot].some(function(e){return r[e]>=0})}function ZS(r){var e=r.state,t=r.name,i=e.rects.reference,n=e.rects.popper,s=e.modifiersData.preventOverflow,o=ts(e,{elementContext:"reference"}),a=ts(e,{altBoundary:!0}),l=kg(o,i),A=kg(a,n,s),u=Mg(l),c=Mg(A);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:A,isReferenceHidden:u,hasPopperEscaped:c},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":c})}const eb={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:ZS};function tb(r,e,t){var i=mi(r),n=[Ot,Nt].indexOf(i)>=0?-1:1,s=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,o=s[0],a=s[1];return o=o||0,a=(a||0)*n,[Ot,jt].indexOf(i)>=0?{x:a,y:o}:{x:o,y:a}}function ib(r){var e=r.state,t=r.options,i=r.name,n=t.offset,s=n===void 0?[0,0]:n,o=yg.reduce(function(u,c){return u[c]=tb(c,e.rects,s),u},{}),a=o[e.placement],l=a.x,A=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=A),e.modifiersData[i]=o}const rb={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:ib};function nb(r){var e=r.state,t=r.name;e.modifiersData[t]=Lg({reference:e.rects.reference,element:e.rects.popper,placement:e.placement})}const sb={name:"popperOffsets",enabled:!0,phase:"read",fn:nb,data:{}};function ob(r){return r==="x"?"y":"x"}function ab(r){var e=r.state,t=r.options,i=r.name,n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!1:o,l=t.boundary,A=t.rootBoundary,u=t.altBoundary,c=t.padding,h=t.tether,d=h===void 0?!0:h,f=t.tetherOffset,g=f===void 0?0:f,p=ts(e,{boundary:l,rootBoundary:A,padding:c,altBoundary:u}),v=mi(e.placement),B=Xr(e.placement),C=!B,y=xA(v),x=ob(y),w=e.modifiersData.popperOffsets,D=e.rects.reference,F=e.rects.popper,O=typeof g=="function"?g(Object.assign({},e.rects,{placement:e.placement})):g,M=typeof O=="number"?{mainAxis:O,altAxis:O}:Object.assign({mainAxis:0,altAxis:0},O),j=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,X={x:0,y:0};if(w){if(s){var le,oe=y==="y"?Nt:Ot,L=y==="y"?Jt:jt,U=y==="y"?"height":"width",q=w[y],R=q+p[oe],_=q-p[L],k=d?-F[U]/2:0,K=B===qr?D[U]:F[U],Y=B===qr?-F[U]:-D[U],te=e.elements.arrow,ie=d&&te?bA(te):{width:0,height:0},he=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:bg(),fe=he[oe],_e=he[L],Te=Zn(0,D[U],ie[U]),Fe=C?D[U]/2-k-Te-fe-M.mainAxis:K-Te-fe-M.mainAxis,pe=C?-D[U]/2+k+Te+_e+M.mainAxis:Y+Te+_e+M.mainAxis,Qe=e.elements.arrow&&zn(e.elements.arrow),Ne=Qe?y==="y"?Qe.clientTop||0:Qe.clientLeft||0:0,Re=(le=j==null?void 0:j[y])!=null?le:0,Ke=q+Fe-Re-Ne,Se=q+pe-Re,ye=Zn(d?Po(R,Ke):R,q,d?Cr(_,Se):_);w[y]=ye,X[y]=ye-q}if(a){var ke,Ue=y==="x"?Nt:Ot,Xe=y==="x"?Jt:jt,Ge=w[x],$e=x==="y"?"height":"width",Ce=Ge+p[Ue],et=Ge-p[Xe],ot=[Nt,Ot].indexOf(v)!==-1,Ze=(ke=j==null?void 0:j[x])!=null?ke:0,ze=ot?Ce:Ge-D[$e]-F[$e]-Ze+M.altAxis,T=ot?Ge+D[$e]+F[$e]-Ze-M.altAxis:et,m=d&&ot?RS(ze,Ge,T):Zn(d?ze:Ce,Ge,d?T:et);w[x]=m,X[x]=m-Ge}e.modifiersData[i]=X}}const lb={name:"preventOverflow",enabled:!0,phase:"main",fn:ab,requiresIfExists:["offset"]};function Ab(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function cb(r){return r===$t(r)||!Xt(r)?QA(r):Ab(r)}function ub(r){var e=r.getBoundingClientRect(),t=Jr(e.width)/r.offsetWidth||1,i=Jr(e.height)/r.offsetHeight||1;return t!==1||i!==1}function hb(r,e,t){t===void 0&&(t=!1);var i=Xt(e),n=Xt(e)&&ub(e),s=zi(e),o=jr(r,n,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!t)&&((pi(e)!=="body"||wA(s))&&(a=cb(e)),Xt(e)?(l=jr(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):s&&(l.x=_A(s))),{x:o.left+a.scrollLeft-l.x,y:o.top+a.scrollTop-l.y,width:o.width,height:o.height}}function db(r){var e=new Map,t=new Set,i=[];r.forEach(function(s){e.set(s.name,s)});function n(s){t.add(s.name);var o=[].concat(s.requires||[],s.requiresIfExists||[]);o.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&n(l)}}),i.push(s)}return r.forEach(function(s){t.has(s.name)||n(s)}),i}function fb(r){var e=db(r);return bS.reduce(function(t,i){return t.concat(e.filter(function(n){return n.phase===i}))},[])}function gb(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}function pb(r){var e=r.reduce(function(t,i){var n=t[i.name];return t[i.name]=n?Object.assign({},n,i,{options:Object.assign({},n.options,i.options),data:Object.assign({},n.data,i.data)}):i,t},{});return Object.keys(e).map(function(t){return e[t]})}var Fg={placement:"bottom",modifiers:[],strategy:"absolute"};function Pg(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function mb(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,i=t===void 0?[]:t,n=e.defaultOptions,s=n===void 0?Fg:n;return function(a,l,A){A===void 0&&(A=s);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},Fg,s),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},c=[],h=!1,d={state:u,setOptions:function(v){var B=typeof v=="function"?v(u.options):v;g(),u.options=Object.assign({},s,u.options,B),u.scrollParents={reference:yr(a)?es(a):a.contextElement?es(a.contextElement):[],popper:es(l)};var C=fb(pb([].concat(i,u.options.modifiers)));return u.orderedModifiers=C.filter(function(y){return y.enabled}),f(),d.update()},forceUpdate:function(){if(!h){var v=u.elements,B=v.reference,C=v.popper;if(Pg(B,C)){u.rects={reference:hb(B,zn(C),u.options.strategy==="fixed"),popper:bA(C)},u.reset=!1,u.placement=u.options.placement,u.orderedModifiers.forEach(function(M){return u.modifiersData[M.name]=Object.assign({},M.data)});for(var y=0;y<u.orderedModifiers.length;y++){if(u.reset===!0){u.reset=!1,y=-1;continue}var x=u.orderedModifiers[y],w=x.fn,D=x.options,F=D===void 0?{}:D,O=x.name;typeof w=="function"&&(u=w({state:u,options:F,name:O,instance:d})||u)}}}},update:gb(function(){return new Promise(function(p){d.forceUpdate(),p(u)})}),destroy:function(){g(),h=!0}};if(!Pg(a,l))return d;d.setOptions(A).then(function(p){!h&&A.onFirstUpdate&&A.onFirstUpdate(p)});function f(){u.orderedModifiers.forEach(function(p){var v=p.name,B=p.options,C=B===void 0?{}:B,y=p.effect;if(typeof y=="function"){var x=y({state:u,name:v,instance:d,options:C}),w=function(){};c.push(x||w)}})}function g(){c.forEach(function(p){return p()}),c=[]}return d}}var Eb=[GS,sb,OS,Cg,rb,zS,lb,MS,eb],Ib=mb({defaultModifiers:Eb}),vb="tippy-box",Ng="tippy-content",yb="tippy-backdrop",Og="tippy-arrow",Ug="tippy-svg-arrow",Br={passive:!0,capture:!0},Gg=function(){return document.body};function DA(r,e,t){if(Array.isArray(r)){var i=r[e];return i??(Array.isArray(t)?t[e]:t)}return r}function LA(r,e){var t={}.toString.call(r);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function $g(r,e){return typeof r=="function"?r.apply(void 0,e):r}function Hg(r,e){if(e===0)return r;var t;return function(i){clearTimeout(t),t=setTimeout(function(){r(i)},e)}}function Cb(r){return r.split(/\s+/).filter(Boolean)}function zr(r){return[].concat(r)}function Yg(r,e){r.indexOf(e)===-1&&r.push(e)}function Bb(r){return r.filter(function(e,t){return r.indexOf(e)===t})}function Tb(r){return r.split("-")[0]}function Go(r){return[].slice.call(r)}function Vg(r){return Object.keys(r).reduce(function(e,t){return r[t]!==void 0&&(e[t]=r[t]),e},{})}function is(){return document.createElement("div")}function $o(r){return["Element","Fragment"].some(function(e){return LA(r,e)})}function Sb(r){return LA(r,"NodeList")}function bb(r){return LA(r,"MouseEvent")}function xb(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function Qb(r){return $o(r)?[r]:Sb(r)?Go(r):Array.isArray(r)?r:Go(document.querySelectorAll(r))}function kA(r,e){r.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function Kg(r,e){r.forEach(function(t){t&&t.setAttribute("data-state",e)})}function _b(r){var e,t=zr(r),i=t[0];return i!=null&&(e=i.ownerDocument)!=null&&e.body?i.ownerDocument:document}function wb(r,e){var t=e.clientX,i=e.clientY;return r.every(function(n){var s=n.popperRect,o=n.popperState,a=n.props,l=a.interactiveBorder,A=Tb(o.placement),u=o.modifiersData.offset;if(!u)return!0;var c=A==="bottom"?u.top.y:0,h=A==="top"?u.bottom.y:0,d=A==="right"?u.left.x:0,f=A==="left"?u.right.x:0,g=s.top-i+c>l,p=i-s.bottom-h>l,v=s.left-t+d>l,B=t-s.right-f>l;return g||p||v||B})}function MA(r,e,t){var i=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(n){r[i](n,t)})}function Wg(r,e){for(var t=e;t;){var i;if(r.contains(t))return!0;t=t.getRootNode==null||(i=t.getRootNode())==null?void 0:i.host}return!1}var Ei={isTouch:!1},qg=0;function Rb(){Ei.isTouch||(Ei.isTouch=!0,window.performance&&document.addEventListener("mousemove",Jg))}function Jg(){var r=performance.now();r-qg<20&&(Ei.isTouch=!1,document.removeEventListener("mousemove",Jg)),qg=r}function Db(){var r=document.activeElement;if(xb(r)){var e=r._tippy;r.blur&&!e.state.isVisible&&r.blur()}}function Lb(){document.addEventListener("touchstart",Rb,Br),window.addEventListener("blur",Db)}var kb=typeof window<"u"&&typeof document<"u",Mb=kb?!!window.msCrypto:!1,Fb={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Pb={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ii=Object.assign({appendTo:Gg,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},Fb,Pb),Nb=Object.keys(ii),Ob=function(e){var t=Object.keys(e);t.forEach(function(i){ii[i]=e[i]})};function jg(r){var e=r.plugins||[],t=e.reduce(function(i,n){var s=n.name,o=n.defaultValue;if(s){var a;i[s]=r[s]!==void 0?r[s]:(a=ii[s])!=null?a:o}return i},{});return Object.assign({},r,t)}function Ub(r,e){var t=e?Object.keys(jg(Object.assign({},ii,{plugins:e}))):Nb,i=t.reduce(function(n,s){var o=(r.getAttribute("data-tippy-"+s)||"").trim();if(!o)return n;if(s==="content")n[s]=o;else try{n[s]=JSON.parse(o)}catch{n[s]=o}return n},{});return i}function Xg(r,e){var t=Object.assign({},e,{content:$g(e.content,[r])},e.ignoreAttributes?{}:Ub(r,e.plugins));return t.aria=Object.assign({},ii.aria,t.aria),t.aria={expanded:t.aria.expanded==="auto"?e.interactive:t.aria.expanded,content:t.aria.content==="auto"?e.interactive?null:"describedby":t.aria.content},t}var Gb=function(){return"innerHTML"};function FA(r,e){r[Gb()]=e}function zg(r){var e=is();return r===!0?e.className=Og:(e.className=Ug,$o(r)?e.appendChild(r):FA(e,r)),e}function Zg(r,e){$o(e.content)?(FA(r,""),r.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?FA(r,e.content):r.textContent=e.content)}function PA(r){var e=r.firstElementChild,t=Go(e.children);return{box:e,content:t.find(function(i){return i.classList.contains(Ng)}),arrow:t.find(function(i){return i.classList.contains(Og)||i.classList.contains(Ug)}),backdrop:t.find(function(i){return i.classList.contains(yb)})}}function e0(r){var e=is(),t=is();t.className=vb,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var i=is();i.className=Ng,i.setAttribute("data-state","hidden"),Zg(i,r.props),e.appendChild(t),t.appendChild(i),n(r.props,r.props);function n(s,o){var a=PA(e),l=a.box,A=a.content,u=a.arrow;o.theme?l.setAttribute("data-theme",o.theme):l.removeAttribute("data-theme"),typeof o.animation=="string"?l.setAttribute("data-animation",o.animation):l.removeAttribute("data-animation"),o.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?l.setAttribute("role",o.role):l.removeAttribute("role"),(s.content!==o.content||s.allowHTML!==o.allowHTML)&&Zg(A,r.props),o.arrow?u?s.arrow!==o.arrow&&(l.removeChild(u),l.appendChild(zg(o.arrow))):l.appendChild(zg(o.arrow)):u&&l.removeChild(u)}return{popper:e,onUpdate:n}}e0.$$tippy=!0;var $b=1,Ho=[],NA=[];function Hb(r,e){var t=Xg(r,Object.assign({},ii,jg(Vg(e)))),i,n,s,o=!1,a=!1,l=!1,A=!1,u,c,h,d=[],f=Hg(Ke,t.interactiveDebounce),g,p=$b++,v=null,B=Bb(t.plugins),C={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:p,reference:r,popper:is(),popperInstance:v,props:t,state:C,plugins:B,clearDelayTimeouts:ze,setProps:T,setContent:m,show:E,hide:Q,hideWithInteractivity:N,enable:ot,disable:Ze,unmount:J,destroy:z};if(!t.render)return y;var x=t.render(y),w=x.popper,D=x.onUpdate;w.setAttribute("data-tippy-root",""),w.id="tippy-"+y.id,y.popper=w,r._tippy=y,w._tippy=y;var F=B.map(function($){return $.fn(y)}),O=r.hasAttribute("aria-expanded");return Qe(),k(),q(),R("onCreate",[y]),t.showOnCreate&&Ce(),w.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),w.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&oe().addEventListener("mousemove",f)}),y;function M(){var $=y.props.touch;return Array.isArray($)?$:[$,0]}function j(){return M()[0]==="hold"}function X(){var $;return!!(($=y.props.render)!=null&&$.$$tippy)}function le(){return g||r}function oe(){var $=le().parentNode;return $?_b($):document}function L(){return PA(w)}function U($){return y.state.isMounted&&!y.state.isVisible||Ei.isTouch||u&&u.type==="focus"?0:DA(y.props.delay,$?0:1,ii.delay)}function q($){$===void 0&&($=!1),w.style.pointerEvents=y.props.interactive&&!$?"":"none",w.style.zIndex=""+y.props.zIndex}function R($,ae,ue){if(ue===void 0&&(ue=!0),F.forEach(function(me){me[$]&&me[$].apply(me,ae)}),ue){var ve;(ve=y.props)[$].apply(ve,ae)}}function _(){var $=y.props.aria;if($.content){var ae="aria-"+$.content,ue=w.id,ve=zr(y.props.triggerTarget||r);ve.forEach(function(me){var nt=me.getAttribute(ae);if(y.state.isVisible)me.setAttribute(ae,nt?nt+" "+ue:ue);else{var Rt=nt&&nt.replace(ue,"").trim();Rt?me.setAttribute(ae,Rt):me.removeAttribute(ae)}})}}function k(){if(!(O||!y.props.aria.expanded)){var $=zr(y.props.triggerTarget||r);$.forEach(function(ae){y.props.interactive?ae.setAttribute("aria-expanded",y.state.isVisible&&ae===le()?"true":"false"):ae.removeAttribute("aria-expanded")})}}function K(){oe().removeEventListener("mousemove",f),Ho=Ho.filter(function($){return $!==f})}function Y($){if(!(Ei.isTouch&&(l||$.type==="mousedown"))){var ae=$.composedPath&&$.composedPath()[0]||$.target;if(!(y.props.interactive&&Wg(w,ae))){if(zr(y.props.triggerTarget||r).some(function(ue){return Wg(ue,ae)})){if(Ei.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else R("onClickOutside",[y,$]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),a=!0,setTimeout(function(){a=!1}),y.state.isMounted||fe())}}}function te(){l=!0}function ie(){l=!1}function he(){var $=oe();$.addEventListener("mousedown",Y,!0),$.addEventListener("touchend",Y,Br),$.addEventListener("touchstart",ie,Br),$.addEventListener("touchmove",te,Br)}function fe(){var $=oe();$.removeEventListener("mousedown",Y,!0),$.removeEventListener("touchend",Y,Br),$.removeEventListener("touchstart",ie,Br),$.removeEventListener("touchmove",te,Br)}function _e($,ae){Fe($,function(){!y.state.isVisible&&w.parentNode&&w.parentNode.contains(w)&&ae()})}function Te($,ae){Fe($,ae)}function Fe($,ae){var ue=L().box;function ve(me){me.target===ue&&(MA(ue,"remove",ve),ae())}if($===0)return ae();MA(ue,"remove",c),MA(ue,"add",ve),c=ve}function pe($,ae,ue){ue===void 0&&(ue=!1);var ve=zr(y.props.triggerTarget||r);ve.forEach(function(me){me.addEventListener($,ae,ue),d.push({node:me,eventType:$,handler:ae,options:ue})})}function Qe(){j()&&(pe("touchstart",Re,{passive:!0}),pe("touchend",Se,{passive:!0})),Cb(y.props.trigger).forEach(function($){if($!=="manual")switch(pe($,Re),$){case"mouseenter":pe("mouseleave",Se);break;case"focus":pe(Mb?"focusout":"blur",ye);break;case"focusin":pe("focusout",ye);break}})}function Ne(){d.forEach(function($){var ae=$.node,ue=$.eventType,ve=$.handler,me=$.options;ae.removeEventListener(ue,ve,me)}),d=[]}function Re($){var ae,ue=!1;if(!(!y.state.isEnabled||ke($)||a)){var ve=((ae=u)==null?void 0:ae.type)==="focus";u=$,g=$.currentTarget,k(),!y.state.isVisible&&bb($)&&Ho.forEach(function(me){return me($)}),$.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||o)&&y.props.hideOnClick!==!1&&y.state.isVisible?ue=!0:Ce($),$.type==="click"&&(o=!ue),ue&&!ve&&et($)}}function Ke($){var ae=$.target,ue=le().contains(ae)||w.contains(ae);if(!($.type==="mousemove"&&ue)){var ve=$e().concat(w).map(function(me){var nt,Rt=me._tippy,Dt=(nt=Rt.popperInstance)==null?void 0:nt.state;return Dt?{popperRect:me.getBoundingClientRect(),popperState:Dt,props:t}:null}).filter(Boolean);wb(ve,$)&&(K(),et($))}}function Se($){var ae=ke($)||y.props.trigger.indexOf("click")>=0&&o;if(!ae){if(y.props.interactive){y.hideWithInteractivity($);return}et($)}}function ye($){y.props.trigger.indexOf("focusin")<0&&$.target!==le()||y.props.interactive&&$.relatedTarget&&w.contains($.relatedTarget)||et($)}function ke($){return Ei.isTouch?j()!==$.type.indexOf("touch")>=0:!1}function Ue(){Xe();var $=y.props,ae=$.popperOptions,ue=$.placement,ve=$.offset,me=$.getReferenceClientRect,nt=$.moveTransition,Rt=X()?PA(w).arrow:null,Dt=me?{getBoundingClientRect:me,contextElement:me.contextElement||le()}:r,nn={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(sn){var ir=sn.state;if(X()){var ls=L(),As=ls.box;["placement","reference-hidden","escaped"].forEach(function(on){on==="placement"?As.setAttribute("data-placement",ir.placement):ir.attributes.popper["data-popper-"+on]?As.setAttribute("data-"+on,""):As.removeAttribute("data-"+on)}),ir.attributes.popper={}}}},Lt=[{name:"offset",options:{offset:ve}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!nt}},nn];X()&&Rt&&Lt.push({name:"arrow",options:{element:Rt,padding:3}}),Lt.push.apply(Lt,(ae==null?void 0:ae.modifiers)||[]),y.popperInstance=Ib(Dt,w,Object.assign({},ae,{placement:ue,onFirstUpdate:h,modifiers:Lt}))}function Xe(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Ge(){var $=y.props.appendTo,ae,ue=le();y.props.interactive&&$===Gg||$==="parent"?ae=ue.parentNode:ae=$g($,[ue]),ae.contains(w)||ae.appendChild(w),y.state.isMounted=!0,Ue()}function $e(){return Go(w.querySelectorAll("[data-tippy-root]"))}function Ce($){y.clearDelayTimeouts(),$&&R("onTrigger",[y,$]),he();var ae=U(!0),ue=M(),ve=ue[0],me=ue[1];Ei.isTouch&&ve==="hold"&&me&&(ae=me),ae?i=setTimeout(function(){y.show()},ae):y.show()}function et($){if(y.clearDelayTimeouts(),R("onUntrigger",[y,$]),!y.state.isVisible){fe();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf($.type)>=0&&o)){var ae=U(!1);ae?n=setTimeout(function(){y.state.isVisible&&y.hide()},ae):s=requestAnimationFrame(function(){y.hide()})}}function ot(){y.state.isEnabled=!0}function Ze(){y.hide(),y.state.isEnabled=!1}function ze(){clearTimeout(i),clearTimeout(n),cancelAnimationFrame(s)}function T($){if(!y.state.isDestroyed){R("onBeforeUpdate",[y,$]),Ne();var ae=y.props,ue=Xg(r,Object.assign({},ae,Vg($),{ignoreAttributes:!0}));y.props=ue,Qe(),ae.interactiveDebounce!==ue.interactiveDebounce&&(K(),f=Hg(Ke,ue.interactiveDebounce)),ae.triggerTarget&&!ue.triggerTarget?zr(ae.triggerTarget).forEach(function(ve){ve.removeAttribute("aria-expanded")}):ue.triggerTarget&&r.removeAttribute("aria-expanded"),k(),q(),D&&D(ae,ue),y.popperInstance&&(Ue(),$e().forEach(function(ve){requestAnimationFrame(ve._tippy.popperInstance.forceUpdate)})),R("onAfterUpdate",[y,$])}}function m($){y.setProps({content:$})}function E(){var $=y.state.isVisible,ae=y.state.isDestroyed,ue=!y.state.isEnabled,ve=Ei.isTouch&&!y.props.touch,me=DA(y.props.duration,0,ii.duration);if(!($||ae||ue||ve)&&!le().hasAttribute("disabled")&&(R("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,X()&&(w.style.visibility="visible"),q(),he(),y.state.isMounted||(w.style.transition="none"),X()){var nt=L(),Rt=nt.box,Dt=nt.content;kA([Rt,Dt],0)}h=function(){var Lt;if(!(!y.state.isVisible||A)){if(A=!0,w.offsetHeight,w.style.transition=y.props.moveTransition,X()&&y.props.animation){var Qr=L(),sn=Qr.box,ir=Qr.content;kA([sn,ir],me),Kg([sn,ir],"visible")}_(),k(),Yg(NA,y),(Lt=y.popperInstance)==null||Lt.forceUpdate(),R("onMount",[y]),y.props.animation&&X()&&Te(me,function(){y.state.isShown=!0,R("onShown",[y])})}},Ge()}}function Q(){var $=!y.state.isVisible,ae=y.state.isDestroyed,ue=!y.state.isEnabled,ve=DA(y.props.duration,1,ii.duration);if(!($||ae||ue)&&(R("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,A=!1,o=!1,X()&&(w.style.visibility="hidden"),K(),fe(),q(!0),X()){var me=L(),nt=me.box,Rt=me.content;y.props.animation&&(kA([nt,Rt],ve),Kg([nt,Rt],"hidden"))}_(),k(),y.props.animation?X()&&_e(ve,y.unmount):y.unmount()}}function N($){oe().addEventListener("mousemove",f),Yg(Ho,f),f($)}function J(){y.state.isVisible&&y.hide(),y.state.isMounted&&(Xe(),$e().forEach(function($){$._tippy.unmount()}),w.parentNode&&w.parentNode.removeChild(w),NA=NA.filter(function($){return $!==y}),y.state.isMounted=!1,R("onHidden",[y]))}function z(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Ne(),delete r._tippy,y.state.isDestroyed=!0,R("onDestroy",[y]))}}function Tr(r,e){e===void 0&&(e={});var t=ii.plugins.concat(e.plugins||[]);Lb();var i=Object.assign({},e,{plugins:t}),n=Qb(r),s=n.reduce(function(o,a){var l=a&&Hb(a,i);return l&&o.push(l),o},[]);return $o(r)?s[0]:s}Tr.defaultProps=ii,Tr.setDefaultProps=Ob,Tr.currentInput=Ei,Object.assign({},Cg,{effect:function(e){var t=e.state,i={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,i.popper),t.styles=i,t.elements.arrow&&Object.assign(t.elements.arrow.style,i.arrow)}}),Tr.setDefaultProps({render:e0});function zt(r,e){return`${r}-${e}`}function Ii(r){var e,t;const i=[];return(((e=r.renderer)==null?void 0:e.type)==="video"||((t=r.renderer)==null?void 0:t.type)==="audio")&&i.push({...r.config,...r.options}),i.push(...r.childNodes.flatMap(Ii).filter(Boolean)),i}class Yo extends Error{constructor(e,t=new Error,i=!1){super(),this.fatal=!1,this.fatal=i,this.stack=t.stack,this.message=[e,t.message].filter(Boolean).join(" - ")}}function Zi(r,e,t){return Math.min(Math.max(e,r),t)}const Yb=5;function Vb(r,e){return r.length!==e.length||r.some((t,i)=>t!==e[i])}class Kb{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._canvas=xt(),this._controls=xt(),this.host=e}set activeScenes(e){Vb(e,this._activeScenes)&&(this._activeScenes=e,this.host.dispatchEvent(new CustomEvent("scenechange",{detail:e})),this.host.requestUpdate())}get activeScenes(){return this._activeScenes}set currentTime(e){var t,i,n;const s=Zi(0,e,this.host.duration);this.activeScenes=((t=this.host.composition)==null?void 0:t.tracks.reduce((a,l)=>a.concat(l.scenes.filter(({start:A,duration:u})=>s>=A&&s<A+u)),[]))??[];const o=s!==this.currentTime;this._currentTime=s,this._upcomingScenes=((i=this.host.composition)==null?void 0:i.tracks.reduce((a,l)=>a.concat(l.scenes.filter(({start:A})=>s>=A-Yb&&s<A)),[]))??[],this.loadScenes(),this.syncMediaState(),(n=this._controls.value)==null||n.setAttribute("currentTime",s.toString()),o&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:s})),this.draw(s)}get currentTime(){return this._currentTime}set caption(e){e!==this._caption&&(this._caption=e,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return Qt(this._canvas)}controls(){return Qt(this._controls)}loadScenes(){[...this.activeScenes,...this._upcomingScenes].forEach(e=>{Ii(e.layout.node).forEach(({key:i})=>{var n,s,o;const{id:a,start:l,duration:A}=e,u=this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused,c=zt(a,i);if(this.host.media[c]){const h=this.host.media[c],{speed:d,volume:f,hls:g,node:p,start:v,duration:B}=h,C=this.host.mediaState[c];p&&C&&(p.currentTime>=v+B||p.ended||u&&(g?(n=g.startLoadOnce)==null||n.call(g,v):C.initialised||(s=p.startLoadOnce)==null||s.call(p),p.volume=Zi(0,this.host.volume*(f??1),1),p.playbackRate=Zi(.1,this.host.playbackRate*(d??1),4)))}else if(u){const h=`${l}-${A}`,d=this.host._sceneController.mediaState[h];this.host.duration&&!((o=d==null?void 0:d.buffered)!=null&&o.length)&&(this.host._sceneController.mediaState={...this.host._sceneController.mediaState,[h]:{...d,buffered:[{start:Math.max(0,l/this.host.duration*100),end:Math.min((l+A)/this.host.duration*100,100)}]}})}})})}syncMediaState(){var e;return Promise.all(((e=this.host.composition)==null?void 0:e.tracks.flatMap(t=>t.scenes.flatMap(i=>Ii(i.layout.node).map(async({key:s})=>{const o=zt(i.id,s);if(this.host.media[o]){const a=this.host.media[o],{node:l}=a,A=this.host.mediaState[o],u=this.activeScenes.includes(i);if(A)if(u&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(l.paused&&A.initialised)try{await l.play()}catch(c){throw new Yo("Video play error",c,!0)}}else l.paused||l.pause()}}))))??[])}draw(e=this.currentTime){this.host.composition&&this._canvas.value&&this.host.composition.draw({currentTime:e,canvas:this._canvas.value})}clear(){var e;const t=this._canvas.value;(e=t==null?void 0:t.getContext("2d"))==null||e.clearRect(0,0,t.width,t.height)}}const Wb=Hi(async function(e){const{weight:t,family:i}=e,{client:n,server:s}=i.weights.find(a=>a.weight===t)??{};return!n&&!s?null:new FontFace(e.family.name,`url(${n??s})`,{weight:t,style:"normal"}).load()},{cacheKey:([r])=>JSON.stringify(r)}),qb=Hi(async({options:r})=>{const e=await Wb(r.font);return e&&document.fonts.add(e),{font:r.font}}),Jb=Hi(async({config:r})=>r.src?new Promise((e,t)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>{e({image:i})},i.onerror=n=>{t(n)},i.src=r.src}):{image:null},{cacheKey:([{config:r}])=>JSON.stringify(r)});async function t0(r){return r.duration===1/0?new Promise(e=>{r.currentTime=Number.MAX_SAFE_INTEGER,r.ontimeupdate=()=>{r.ontimeupdate=null,e(r.duration),r.currentTime=0}}):r.duration}function jb(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Xb(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function zb(r){return new Promise(async e=>{let t=null;const{type:i,key:n,src:s,duration:o}=r;i==="video"?(t=document.createElement("video"),t.playsInline=!0):t=document.createElement("audio"),t.muted=!0,t.loop=!1,t.crossOrigin="anonymous",t.src=s;let a=!1;if(t.startLoadOnce=()=>{a||(t.preload="auto",t.load(),a=!0)},i==="video"&&o&&r.aspectRatio)t.preload="none",e({key:n,hls:null,node:t,aspectRatio:r.aspectRatio,totalDuration:o});else{t.preload="metadata";const l=async()=>{const A=await t0(t);e({key:n,hls:null,node:t,totalDuration:A,aspectRatio:t instanceof HTMLVideoElement?t.videoWidth/t.videoHeight:null}),t.removeEventListener("loadedmetadata",l)};t.addEventListener("loadedmetadata",l)}})}function Zb({key:r,playlist:e,duration:t}){return new Promise(i=>{const n=document.createElement("video");n instanceof HTMLVideoElement&&(n.playsInline=!0),n.muted=!0,n.loop=!1,n.crossOrigin="anonymous";let s=!1;const o=new gi({autoStartLoad:!0,xhrSetup:a=>{const{open:l}=a,A=e.split("?")[1];a.open=function(u,c,h){A&&!c.toString().includes("?")&&(c+="?"+A),!(!s&&c.toString().includes(".ts"))&&l.apply(this,[u,c,h])}}});o.on(gi.Events.LEVEL_LOADED,async()=>{s||o==null||o.stopLoad();const a=t??await t0(n);i({key:r,hls:o,node:n,aspectRatio:o.levels[0].width/o.levels[0].height,totalDuration:a})}),o.loadSource(e),o.attachMedia(n),o.startLoadOnce=(a=-1,l)=>{if(o&&!s){const A=o.levels.findIndex(u=>Math.min(u.height,u.width)===l);s=!0,o.startLevel=o.firstLevel,o.startLoad(a),o.currentLevel=A!==-1?A:o.firstLevel}}})}function ex(r){const{playlist:e}=r;return e&&!jb()&&gi.isSupported()?Zb({...r,playlist:e}):zb(r)}let tx=class{constructor(e){this._hasPlayed=!1,this._duration=0,this._composition=null,this._media={},this._mediaState={},this._compositionController=new AbortController,this._delayProcessing=(t=100)=>{const i=new AbortController,n=setTimeout(()=>{i.signal.aborted||(this.host._processing=!0)},t);return i.signal.addEventListener("abort",()=>{clearTimeout(n)}),i},this._mediaFactory=Hi(async(t,i)=>{const{key:n}=i,s=await ex(i),o={loadeddata:this._handleLoadedData,waiting:this._handleWaiting,canplay:this._handleCanPlay,progress:this._handleProgress,seeking:this._handleSeeking,seeked:this._handleSeeked,play:this._handlePlay,playing:this._handlePlaying,pause:this._handlePause,stalled:this._handleStalled,timeupdate:this._handleTimeUpdate,ended:this._handleEnded,error:this._handleError},a=Object.keys(o).reduce((l,A)=>{const u=A,c=o[u]({id:t,key:n,node:s.node});return l[u]=c,s.node.addEventListener(A,c),l},{});return{media:s,listeners:a,aspectRatio:s.aspectRatio,source:()=>s.node}},{cacheKey:([t,{key:i,src:n,playlist:s}])=>JSON.stringify({id:t,key:i,src:n==null?void 0:n.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._handleLoadedData=({id:t,key:i,node:n})=>()=>{const s=zt(t,i),o=this.mediaState[s];o!=null&&o.initialised||(this.mediaState={...this.mediaState,[s]:{...o,initialised:!0,waiting:!1,buffered:(o==null?void 0:o.buffered)??[]}},this.setMediaCurrentTime(this.host.currentTime),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{id:t,key:i,node:n}})))},this._handleWaiting=({id:t,key:i})=>()=>{const n=zt(t,i),s=this.mediaState[n];s!=null&&s.initialised&&!(s!=null&&s.waiting)&&(this.mediaState={...this.mediaState,[n]:{...s,waiting:!0}})},this._handleCanPlay=({id:t,key:i})=>()=>{const n=zt(t,i),s=this.mediaState[n];s!=null&&s.initialised&&(s!=null&&s.waiting)&&(this.mediaState={...this.mediaState,[n]:{...s,waiting:!1}}),this.host.paused&&this.host.draw()},this._handleProgress=()=>()=>{},this._handleSeeking=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:seeking",{detail:{id:t,key:i,node:n}}))},this._handleSeeked=({id:t,key:i,node:n})=>()=>{const s=zt(t,i),o=this.mediaState[s];o!=null&&o.initialised&&(this.host.draw(),this.host.activeScenes.flatMap(a=>Ii(a.layout.node).map(({id:A})=>A)).includes(t)&&this.host.dispatchEvent(new CustomEvent("seeked",{detail:this.host.currentTime})),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:t,key:i,node:n}})))},this._handlePlay=({id:t,key:i,node:n})=>()=>{this.hasPlayed=!0,this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:t,key:i,node:n}}))},this._handlePlaying=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:t,key:i,node:n}}))},this._handlePause=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:t,key:i,node:n}}))},this._handleStalled=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:t,key:i,node:n}}))},this._handleTimeUpdate=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:t,key:i,node:n}}))},this._handleEnded=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:t,key:i,node:n}}))},this._handleError=({id:t,key:i,node:n})=>()=>{const s=new Yo(`Video error - answer ${t} failed to load`);this.host.dispatchEvent(new ErrorEvent("error",{bubbles:!0,composed:!0,error:s,message:s.message})),this.host.dispatchEvent(new CustomEvent("video:error",{detail:{id:t,key:i,node:n}}))},this._cleanupMedia=t=>{var i;const n=this.media[t];n&&(n.node.pause(),n.node.src="",(i=n.hls)==null||i.destroy(),Object.keys(n.listeners??{}).forEach(s=>{var o,a;if((o=this.media)!=null&&o[t]){const l=(a=n.listeners)==null?void 0:a[s];l&&n.node.removeEventListener(s,l)}}),delete this._media[t],delete this._mediaState[t])},this.host=e,this.host.addController(this)}set hasPlayed(e){e!==this._hasPlayed&&(this._hasPlayed=e,this.host.requestUpdate())}get hasPlayed(){return this._hasPlayed}set duration(e){!isNaN(e)&&e!==this._duration&&(this._duration=e,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set composition(e){e!==this._composition&&(this._composition=e,this.host.requestUpdate())}get composition(){return this._composition}set media(e){e!==this._media&&(this._media=e,this.host.requestUpdate())}get media(){return this._media}set mediaState(e){e!==this._mediaState&&(this._mediaState=e,this.host.requestUpdate())}get mediaState(){return this._mediaState}_setupTask(){new ys(this.host,async([e,t,i,n])=>{var s,o;this._compositionController.abort(),this._compositionController=new AbortController;const a=this._compositionController,l=this._delayProcessing();try{if(this.host._errors=[],(!t||!this.host._languages.find(({value:A})=>t===A))&&(this.host._language=(s=this.host._languages[0])==null?void 0:s.value),e){const{width:A,height:u}=ol({aspectRatio:i,resolution:1080});try{(o=this.composition)==null||o.cleanup();const f=await _h({debug:n,config:e,resolvers:{text:qb,image:Jb,video:async({id:g,config:p,options:v})=>{const{media:B,source:C}=await this._mediaFactory(g,{...p,...v});return{video:C,aspectRatio:B.aspectRatio}}},rootWidth:A,rootHeight:u});if(a.signal.aborted)return;this.composition=f}catch(f){throw new Yo("Fatal composition error",f,!0)}this.duration=this.composition.duration;const c={...this.media},h={...this.mediaState},d=[];for(const f of this.composition.tracks)for(const g of f.scenes){const p=Ii(g.layout.node);for(const v of p){const{media:B,listeners:C}=await this._mediaFactory(g.id,v),y=zt(g.id,B.key);d.push(y);const x=(v.startOffset??0)*B.totalDuration,w=(1-(v.endOffset??0))*B.totalDuration;c[y]={...B,listeners:C,start:x,duration:w-x,speed:v.speed??1,volume:v.volume??1},h[y]={initialised:!B,waiting:!!B,...this.mediaState[y]}}}this.media=c,this.mediaState=h,Object.keys(this.media).forEach(f=>{d.includes(f)||this.media[f].node.pause()}),this.host.currentTime>this.duration?this.host.reset(this.duration,!1):this.host.paused?this.host.reset(this.host.currentTime,!this.host.paused):this.setMediaCurrentTime(this.host.currentTime)}this.host.dispatchEvent(new CustomEvent("compositionupdate",{detail:this.composition,bubbles:!0,composed:!0}))}catch(A){this.composition=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",{composed:!0,bubbles:!0,error:A,message:A.message}))}finally{l.abort(),this.host._processing=!1}},()=>[this.host.config,this.host.language,this.host.aspectRatio,this.host.debug])}_setMediaCurrentTime({time:e,scene:t}){const{id:i,layout:n,start:s}=t;Ii(n.node).forEach(({key:a})=>{const l=zt(i,a);if(this.media[l]){const A=this.media[l],u=(e-s)*A.speed;A.node.currentTime=Zi(A.start,u+A.start,A.start+A.duration)}})}setMediaCurrentTime(e){var t;(t=this.composition)==null||t.tracks.forEach(i=>{i.scenes.forEach(n=>{this._setMediaCurrentTime({time:e,scene:n})})})}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.media).forEach(e=>{this._cleanupMedia(e)}),this.media={}}};function ix(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function rx(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const OA=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen","preview"],nx={id:"captions",event:"captions:click",label:"Closed Captions"},sx={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},i0={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},ox={id:"playbackRate",label:"Playback playbackRate",subItems:i0};class ax extends wc{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==Lr.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var e;(e=this.observer)==null||e.disconnect(),this.observer=void 0}reconnected(){var e;this.element&&((e=this.observer)==null||e.observe(this.element))}update(e,[t]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(t),this.element=e.element,this.observer.observe(this.element)),Oi}}const UA=kr(ax),lx=fS(()=>{const r=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),e=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-SemiBold.woff2)",{style:"normal",weight:"600"}),t=new FontFace("Roobert","url(https://vouch-clients.s3.ap-southeast-2.amazonaws.com/vouch/fonts/Roobert-Bold.woff2",{style:"normal",weight:"700"}),i=new FontFace("Roobert Captions","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),n=Ch.map(s=>({load:!1,font:new FontFace(s.family,`url(${s.url})`,{style:s.style})}));return[{load:!0,font:r},{load:!0,font:e},{load:!0,font:t},{load:!0,font:i},...n]}),vi={"red-120":"#feeded","red-130":"#fcd5d0","red-400":"#e84a4a","red-500":"#c51c3a","red-700":"#a21c39","red-800":"#850231","red-900":"#580A2D","teal-80":"#f3fafa","teal-100":"#d6f1f1","teal-200":"#ace3e3","teal-300":"#7acace","teal-400":"#4faab2","teal-500":"#358f97","teal-600":"#287179","teal-700":"#22555c","teal-800":"#21484e","teal-900":"#1f3d42","teal-950":"#0d2126","purple-100":"#d7cfff","purple-700":"#5f2fe9","green-200":"#a4d7aa","green-500":"#38b319","green-800":"#2b3c2f","grey-100":"#f0f0f0","light-50":"rgba(255, 255, 255, .05)","light-100":"rgba(255, 255, 255, .1)","light-200":"rgba(255, 255, 255, .2)","light-400":"rgba(255, 255, 255, .4)","light-500":"rgba(255, 255, 255, .5)","light-640":"rgba(255, 255, 255, .64)","light-800":"rgba(255, 255, 255, .8)","light-1000":"#fff","dark-50":"rgba(0, 0, 0, .05)","dark-80":"rgba(0, 0, 0, .08)","dark-100":"rgba(0, 0, 0, .1)","dark-200":"rgba(0, 0, 0, .2)","dark-250":"rgba(0, 0, 0, .25)","dark-400":"rgba(0, 0, 0, .4)","dark-500":"rgba(0, 0, 0, .5)","dark-640":"rgba(0, 0, 0, .64)","dark-800":"rgba(0, 0, 0, .8)","dark-900":"rgba(0, 0, 0, .9)","dark-1000":"#000"},Ax={colors:vi,space:{xxs:".25rem",xs:".5rem",small:".75rem",medium:"1rem",large:"1.5rem",xl:"2.5rem"},sizes:{xxs:"1rem",xs:"1.5rem",small:"2rem",medium:"2.5rem",large:"3rem"},fontWeights:{regular:400,semibold:600},lineHeights:{small:1.1,medium:1.25,large:1.4},letterSpacings:{xxs:"-.04rem",xs:"-.03rem",small:"-.02rem",medium:"-.01rem",large:0},fontSizes:{micro:".625rem",small:".75rem",medium:".875rem",large:"1rem",xl:"1.25rem",xxl:"1.5rem",xxxl:"2rem",huge:"2.75rem"},fontFamilies:{sans:'Roobert, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial,"Noto Sans", "Noto Color Emoji", sans-serif, "Segoe UI Emoji", "Segoe UI Symbol", "Apple Color Emoji"',mono:'"Maison Neue Mono", Menlo, Monaco, Consolas, Liberation Mono, "Courier New", monospace'},borderWidths:{thin:".0625rem"},radii:{small:".25rem",medium:".5rem",large:".75rem",xl:"1rem"},shadows:{small:`.25rem .25rem .25rem ${vi["dark-100"]}`,medium:`0 .125rem .625rem ${vi["dark-100"]}`,large:`0 .25rem 1rem ${vi["dark-50"]}`,xl:`.25rem .25rem 1rem ${vi["dark-250"]}`,xxl:`0 .25rem 2rem ${vi["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${vi["dark-250"]}`,toolbar:`0 -.625rem .625rem ${vi["dark-50"]}`,text:`0 0 .25rem ${vi["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:vi["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},r0=uS(Ax,{delimiter:"-"}),cx=Object.keys(r0).map(r=>hn(`:host { --${r}: ${r0[r]}; }`)),Je=(r=>{const e=class extends r{firstUpdated(){lx().forEach(({load:s,font:o})=>{document.fonts.add(o),s&&o.load()})}};return e.styles=[(r==null?void 0:r.styles)??[],cx,Bt`
2528
+ */const mg=(r,e,t)=>{const i=new Map;for(let n=e;n<=t;n++)i.set(r[n],n);return i},Eg=kr(class extends yn{constructor(r){if(super(r),r.type!==Lr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(r,e,t){let i;t===void 0?t=e:e!==void 0&&(i=e);const n=[],s=[];let o=0;for(const a of r)n[o]=i?i(a,o):o,s[o]=t(a,o),o++;return{values:s,keys:n}}render(r,e,t){return this.dt(r,e,t).values}update(r,[e,t,i]){const n=Ap(r),{values:s,keys:o}=this.dt(e,t,i);if(!Array.isArray(n))return this.ut=o,s;const a=this.ut??(this.ut=[]),l=[];let A,u,c=0,h=n.length-1,d=0,f=s.length-1;for(;c<=h&&d<=f;)if(n[c]===null)c++;else if(n[h]===null)h--;else if(a[c]===o[d])l[d]=ur(n[c],s[d]),c++,d++;else if(a[h]===o[f])l[f]=ur(n[h],s[f]),h--,f--;else if(a[c]===o[f])l[f]=ur(n[c],s[f]),vn(r,l[f+1],n[c]),c++,f--;else if(a[h]===o[d])l[d]=ur(n[h],s[d]),vn(r,n[c],n[h]),h--,d++;else if(A===void 0&&(A=mg(o,d,f),u=mg(a,c,h)),A.has(a[c]))if(A.has(a[h])){const g=u.get(o[d]),p=g!==void 0?n[g]:null;if(p===null){const v=vn(r,n[c]);ur(v,s[d]),l[d]=v}else l[d]=ur(p,s[d]),vn(r,n[c],p),n[g]=null;d++}else fa(n[h]),h--;else fa(n[c]),c++;for(;d<=f;){const g=vn(r,l[f+1]);ur(g,s[d]),l[d++]=g}for(;c<=h;){const g=n[c++];g!==null&&fa(g)}return this.ut=o,lp(r,l),Fi}});var Nt="top",Jt="bottom",jt="right",Ot="left",BA="auto",Jn=[Nt,Jt,jt,Ot],qr="start",jn="end",gS="clippingParents",Ig="viewport",Xn="popper",pS="reference",vg=Jn.reduce(function(r,e){return r.concat([e+"-"+qr,e+"-"+jn])},[]),yg=[].concat(Jn,[BA]).reduce(function(r,e){return r.concat([e,e+"-"+qr,e+"-"+jn])},[]),mS="beforeRead",ES="read",IS="afterRead",vS="beforeMain",yS="main",CS="afterMain",BS="beforeWrite",TS="write",SS="afterWrite",bS=[mS,ES,IS,vS,yS,CS,BS,TS,SS];function pi(r){return r?(r.nodeName||"").toLowerCase():null}function $t(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}function yr(r){var e=$t(r).Element;return r instanceof e||r instanceof Element}function Xt(r){var e=$t(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function TA(r){if(typeof ShadowRoot>"u")return!1;var e=$t(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}function xS(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];!Xt(s)||!pi(s)||(Object.assign(s.style,i),Object.keys(n).forEach(function(o){var a=n[o];a===!1?s.removeAttribute(o):s.setAttribute(o,a===!0?"":a)}))})}function QS(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(i){var n=e.elements[i],s=e.attributes[i]||{},o=Object.keys(e.styles.hasOwnProperty(i)?e.styles[i]:t[i]),a=o.reduce(function(l,A){return l[A]="",l},{});!Xt(n)||!pi(n)||(Object.assign(n.style,a),Object.keys(s).forEach(function(l){n.removeAttribute(l)}))})}}const Cg={name:"applyStyles",enabled:!0,phase:"write",fn:xS,effect:QS,requires:["computeStyles"]};function mi(r){return r.split("-")[0]}var Cr=Math.max,Po=Math.min,Jr=Math.round;function SA(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function Bg(){return!/^((?!chrome|android).)*safari/i.test(SA())}function jr(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var i=r.getBoundingClientRect(),n=1,s=1;e&&Xt(r)&&(n=r.offsetWidth>0&&Jr(i.width)/r.offsetWidth||1,s=r.offsetHeight>0&&Jr(i.height)/r.offsetHeight||1);var o=yr(r)?$t(r):window,a=o.visualViewport,l=!Bg()&&t,A=(i.left+(l&&a?a.offsetLeft:0))/n,u=(i.top+(l&&a?a.offsetTop:0))/s,c=i.width/n,h=i.height/s;return{width:c,height:h,top:u,right:A+c,bottom:u+h,left:A,x:A,y:u}}function bA(r){var e=jr(r),t=r.offsetWidth,i=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-i)<=1&&(i=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:i}}function Tg(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&TA(t)){var i=e;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function wi(r){return $t(r).getComputedStyle(r)}function _S(r){return["table","td","th"].indexOf(pi(r))>=0}function zi(r){return((yr(r)?r.ownerDocument:r.document)||window.document).documentElement}function No(r){return pi(r)==="html"?r:r.assignedSlot||r.parentNode||(TA(r)?r.host:null)||zi(r)}function Sg(r){return!Xt(r)||wi(r).position==="fixed"?null:r.offsetParent}function wS(r){var e=/firefox/i.test(SA()),t=/Trident/i.test(SA());if(t&&Xt(r)){var i=wi(r);if(i.position==="fixed")return null}var n=No(r);for(TA(n)&&(n=n.host);Xt(n)&&["html","body"].indexOf(pi(n))<0;){var s=wi(n);if(s.transform!=="none"||s.perspective!=="none"||s.contain==="paint"||["transform","perspective"].indexOf(s.willChange)!==-1||e&&s.willChange==="filter"||e&&s.filter&&s.filter!=="none")return n;n=n.parentNode}return null}function zn(r){for(var e=$t(r),t=Sg(r);t&&_S(t)&&wi(t).position==="static";)t=Sg(t);return t&&(pi(t)==="html"||pi(t)==="body"&&wi(t).position==="static")?e:t||wS(r)||e}function xA(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function Zn(r,e,t){return Cr(r,Po(e,t))}function RS(r,e,t){var i=Zn(r,e,t);return i>t?t:i}function bg(){return{top:0,right:0,bottom:0,left:0}}function xg(r){return Object.assign({},bg(),r)}function Qg(r,e){return e.reduce(function(t,i){return t[i]=r,t},{})}var DS=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,xg(typeof e!="number"?e:Qg(e,Jn))};function LS(r){var e,t=r.state,i=r.name,n=r.options,s=t.elements.arrow,o=t.modifiersData.popperOffsets,a=mi(t.placement),l=xA(a),A=[Ot,jt].indexOf(a)>=0,u=A?"height":"width";if(!(!s||!o)){var c=DS(n.padding,t),h=bA(s),d=l==="y"?Nt:Ot,f=l==="y"?Jt:jt,g=t.rects.reference[u]+t.rects.reference[l]-o[l]-t.rects.popper[u],p=o[l]-t.rects.reference[l],v=zn(s),B=v?l==="y"?v.clientHeight||0:v.clientWidth||0:0,C=g/2-p/2,y=c[d],x=B-h[u]-c[f],w=B/2-h[u]/2+C,D=Zn(y,w,x),F=l;t.modifiersData[i]=(e={},e[F]=D,e.centerOffset=D-w,e)}}function kS(r){var e=r.state,t=r.options,i=t.element,n=i===void 0?"[data-popper-arrow]":i;n!=null&&(typeof n=="string"&&(n=e.elements.popper.querySelector(n),!n)||Tg(e.elements.popper,n)&&(e.elements.arrow=n))}const MS={name:"arrow",enabled:!0,phase:"main",fn:LS,effect:kS,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Xr(r){return r.split("-")[1]}var FS={top:"auto",right:"auto",bottom:"auto",left:"auto"};function PS(r,e){var t=r.x,i=r.y,n=e.devicePixelRatio||1;return{x:Jr(t*n)/n||0,y:Jr(i*n)/n||0}}function _g(r){var e,t=r.popper,i=r.popperRect,n=r.placement,s=r.variation,o=r.offsets,a=r.position,l=r.gpuAcceleration,A=r.adaptive,u=r.roundOffsets,c=r.isFixed,h=o.x,d=h===void 0?0:h,f=o.y,g=f===void 0?0:f,p=typeof u=="function"?u({x:d,y:g}):{x:d,y:g};d=p.x,g=p.y;var v=o.hasOwnProperty("x"),B=o.hasOwnProperty("y"),C=Ot,y=Nt,x=window;if(A){var w=zn(t),D="clientHeight",F="clientWidth";if(w===$t(t)&&(w=zi(t),wi(w).position!=="static"&&a==="absolute"&&(D="scrollHeight",F="scrollWidth")),w=w,n===Nt||(n===Ot||n===jt)&&s===jn){y=Jt;var O=c&&w===x&&x.visualViewport?x.visualViewport.height:w[D];g-=O-i.height,g*=l?1:-1}if(n===Ot||(n===Nt||n===Jt)&&s===jn){C=jt;var M=c&&w===x&&x.visualViewport?x.visualViewport.width:w[F];d-=M-i.width,d*=l?1:-1}}var j=Object.assign({position:a},A&&FS),X=u===!0?PS({x:d,y:g},$t(t)):{x:d,y:g};if(d=X.x,g=X.y,l){var le;return Object.assign({},j,(le={},le[y]=B?"0":"",le[C]=v?"0":"",le.transform=(x.devicePixelRatio||1)<=1?"translate("+d+"px, "+g+"px)":"translate3d("+d+"px, "+g+"px, 0)",le))}return Object.assign({},j,(e={},e[y]=B?g+"px":"",e[C]=v?d+"px":"",e.transform="",e))}function NS(r){var e=r.state,t=r.options,i=t.gpuAcceleration,n=i===void 0?!0:i,s=t.adaptive,o=s===void 0?!0:s,a=t.roundOffsets,l=a===void 0?!0:a,A={placement:mi(e.placement),variation:Xr(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:n,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,_g(Object.assign({},A,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,_g(Object.assign({},A,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const OS={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:NS,data:{}};var Oo={passive:!0};function US(r){var e=r.state,t=r.instance,i=r.options,n=i.scroll,s=n===void 0?!0:n,o=i.resize,a=o===void 0?!0:o,l=$t(e.elements.popper),A=[].concat(e.scrollParents.reference,e.scrollParents.popper);return s&&A.forEach(function(u){u.addEventListener("scroll",t.update,Oo)}),a&&l.addEventListener("resize",t.update,Oo),function(){s&&A.forEach(function(u){u.removeEventListener("scroll",t.update,Oo)}),a&&l.removeEventListener("resize",t.update,Oo)}}const GS={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:US,data:{}};var $S={left:"right",right:"left",bottom:"top",top:"bottom"};function Uo(r){return r.replace(/left|right|bottom|top/g,function(e){return $S[e]})}var HS={start:"end",end:"start"};function wg(r){return r.replace(/start|end/g,function(e){return HS[e]})}function QA(r){var e=$t(r),t=e.pageXOffset,i=e.pageYOffset;return{scrollLeft:t,scrollTop:i}}function _A(r){return jr(zi(r)).left+QA(r).scrollLeft}function YS(r,e){var t=$t(r),i=zi(r),n=t.visualViewport,s=i.clientWidth,o=i.clientHeight,a=0,l=0;if(n){s=n.width,o=n.height;var A=Bg();(A||!A&&e==="fixed")&&(a=n.offsetLeft,l=n.offsetTop)}return{width:s,height:o,x:a+_A(r),y:l}}function VS(r){var e,t=zi(r),i=QA(r),n=(e=r.ownerDocument)==null?void 0:e.body,s=Cr(t.scrollWidth,t.clientWidth,n?n.scrollWidth:0,n?n.clientWidth:0),o=Cr(t.scrollHeight,t.clientHeight,n?n.scrollHeight:0,n?n.clientHeight:0),a=-i.scrollLeft+_A(r),l=-i.scrollTop;return wi(n||t).direction==="rtl"&&(a+=Cr(t.clientWidth,n?n.clientWidth:0)-s),{width:s,height:o,x:a,y:l}}function wA(r){var e=wi(r),t=e.overflow,i=e.overflowX,n=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+n+i)}function Rg(r){return["html","body","#document"].indexOf(pi(r))>=0?r.ownerDocument.body:Xt(r)&&wA(r)?r:Rg(No(r))}function es(r,e){var t;e===void 0&&(e=[]);var i=Rg(r),n=i===((t=r.ownerDocument)==null?void 0:t.body),s=$t(i),o=n?[s].concat(s.visualViewport||[],wA(i)?i:[]):i,a=e.concat(o);return n?a:a.concat(es(No(o)))}function RA(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function KS(r,e){var t=jr(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function Dg(r,e,t){return e===Ig?RA(YS(r,t)):yr(e)?KS(e,t):RA(VS(zi(r)))}function WS(r){var e=es(No(r)),t=["absolute","fixed"].indexOf(wi(r).position)>=0,i=t&&Xt(r)?zn(r):r;return yr(i)?e.filter(function(n){return yr(n)&&Tg(n,i)&&pi(n)!=="body"}):[]}function qS(r,e,t,i){var n=e==="clippingParents"?WS(r):[].concat(e),s=[].concat(n,[t]),o=s[0],a=s.reduce(function(l,A){var u=Dg(r,A,i);return l.top=Cr(u.top,l.top),l.right=Po(u.right,l.right),l.bottom=Po(u.bottom,l.bottom),l.left=Cr(u.left,l.left),l},Dg(r,o,i));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function Lg(r){var e=r.reference,t=r.element,i=r.placement,n=i?mi(i):null,s=i?Xr(i):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(n){case Nt:l={x:o,y:e.y-t.height};break;case Jt:l={x:o,y:e.y+e.height};break;case jt:l={x:e.x+e.width,y:a};break;case Ot:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var A=n?xA(n):null;if(A!=null){var u=A==="y"?"height":"width";switch(s){case qr:l[A]=l[A]-(e[u]/2-t[u]/2);break;case jn:l[A]=l[A]+(e[u]/2-t[u]/2);break}}return l}function ts(r,e){e===void 0&&(e={});var t=e,i=t.placement,n=i===void 0?r.placement:i,s=t.strategy,o=s===void 0?r.strategy:s,a=t.boundary,l=a===void 0?gS:a,A=t.rootBoundary,u=A===void 0?Ig:A,c=t.elementContext,h=c===void 0?Xn:c,d=t.altBoundary,f=d===void 0?!1:d,g=t.padding,p=g===void 0?0:g,v=xg(typeof p!="number"?p:Qg(p,Jn)),B=h===Xn?pS:Xn,C=r.rects.popper,y=r.elements[f?B:h],x=qS(yr(y)?y:y.contextElement||zi(r.elements.popper),l,u,o),w=jr(r.elements.reference),D=Lg({reference:w,element:C,placement:n}),F=RA(Object.assign({},C,D)),O=h===Xn?F:w,M={top:x.top-O.top+v.top,bottom:O.bottom-x.bottom+v.bottom,left:x.left-O.left+v.left,right:O.right-x.right+v.right},j=r.modifiersData.offset;if(h===Xn&&j){var X=j[n];Object.keys(M).forEach(function(le){var oe=[jt,Jt].indexOf(le)>=0?1:-1,L=[Nt,Jt].indexOf(le)>=0?"y":"x";M[le]+=X[L]*oe})}return M}function JS(r,e){e===void 0&&(e={});var t=e,i=t.placement,n=t.boundary,s=t.rootBoundary,o=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,A=l===void 0?yg:l,u=Xr(i),c=u?a?vg:vg.filter(function(f){return Xr(f)===u}):Jn,h=c.filter(function(f){return A.indexOf(f)>=0});h.length===0&&(h=c);var d=h.reduce(function(f,g){return f[g]=ts(r,{placement:g,boundary:n,rootBoundary:s,padding:o})[mi(g)],f},{});return Object.keys(d).sort(function(f,g){return d[f]-d[g]})}function jS(r){if(mi(r)===BA)return[];var e=Uo(r);return[wg(r),e,wg(e)]}function XS(r){var e=r.state,t=r.options,i=r.name;if(!e.modifiersData[i]._skip){for(var n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!0:o,l=t.fallbackPlacements,A=t.padding,u=t.boundary,c=t.rootBoundary,h=t.altBoundary,d=t.flipVariations,f=d===void 0?!0:d,g=t.allowedAutoPlacements,p=e.options.placement,v=mi(p),B=v===p,C=l||(B||!f?[Uo(p)]:jS(p)),y=[p].concat(C).reduce(function(ie,he){return ie.concat(mi(he)===BA?JS(e,{placement:he,boundary:u,rootBoundary:c,padding:A,flipVariations:f,allowedAutoPlacements:g}):he)},[]),x=e.rects.reference,w=e.rects.popper,D=new Map,F=!0,O=y[0],M=0;M<y.length;M++){var j=y[M],X=mi(j),le=Xr(j)===qr,oe=[Nt,Jt].indexOf(X)>=0,L=oe?"width":"height",U=ts(e,{placement:j,boundary:u,rootBoundary:c,altBoundary:h,padding:A}),q=oe?le?jt:Ot:le?Jt:Nt;x[L]>w[L]&&(q=Uo(q));var R=Uo(q),_=[];if(s&&_.push(U[X]<=0),a&&_.push(U[q]<=0,U[R]<=0),_.every(function(ie){return ie})){O=j,F=!1;break}D.set(j,_)}if(F)for(var k=f?3:1,K=function(he){var fe=y.find(function(_e){var Te=D.get(_e);if(Te)return Te.slice(0,he).every(function(Fe){return Fe})});if(fe)return O=fe,"break"},Y=k;Y>0;Y--){var te=K(Y);if(te==="break")break}e.placement!==O&&(e.modifiersData[i]._skip=!0,e.placement=O,e.reset=!0)}}const zS={name:"flip",enabled:!0,phase:"main",fn:XS,requiresIfExists:["offset"],data:{_skip:!1}};function kg(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function Mg(r){return[Nt,jt,Jt,Ot].some(function(e){return r[e]>=0})}function ZS(r){var e=r.state,t=r.name,i=e.rects.reference,n=e.rects.popper,s=e.modifiersData.preventOverflow,o=ts(e,{elementContext:"reference"}),a=ts(e,{altBoundary:!0}),l=kg(o,i),A=kg(a,n,s),u=Mg(l),c=Mg(A);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:A,isReferenceHidden:u,hasPopperEscaped:c},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":c})}const eb={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:ZS};function tb(r,e,t){var i=mi(r),n=[Ot,Nt].indexOf(i)>=0?-1:1,s=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,o=s[0],a=s[1];return o=o||0,a=(a||0)*n,[Ot,jt].indexOf(i)>=0?{x:a,y:o}:{x:o,y:a}}function ib(r){var e=r.state,t=r.options,i=r.name,n=t.offset,s=n===void 0?[0,0]:n,o=yg.reduce(function(u,c){return u[c]=tb(c,e.rects,s),u},{}),a=o[e.placement],l=a.x,A=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=A),e.modifiersData[i]=o}const rb={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:ib};function nb(r){var e=r.state,t=r.name;e.modifiersData[t]=Lg({reference:e.rects.reference,element:e.rects.popper,placement:e.placement})}const sb={name:"popperOffsets",enabled:!0,phase:"read",fn:nb,data:{}};function ob(r){return r==="x"?"y":"x"}function ab(r){var e=r.state,t=r.options,i=r.name,n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!1:o,l=t.boundary,A=t.rootBoundary,u=t.altBoundary,c=t.padding,h=t.tether,d=h===void 0?!0:h,f=t.tetherOffset,g=f===void 0?0:f,p=ts(e,{boundary:l,rootBoundary:A,padding:c,altBoundary:u}),v=mi(e.placement),B=Xr(e.placement),C=!B,y=xA(v),x=ob(y),w=e.modifiersData.popperOffsets,D=e.rects.reference,F=e.rects.popper,O=typeof g=="function"?g(Object.assign({},e.rects,{placement:e.placement})):g,M=typeof O=="number"?{mainAxis:O,altAxis:O}:Object.assign({mainAxis:0,altAxis:0},O),j=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,X={x:0,y:0};if(w){if(s){var le,oe=y==="y"?Nt:Ot,L=y==="y"?Jt:jt,U=y==="y"?"height":"width",q=w[y],R=q+p[oe],_=q-p[L],k=d?-F[U]/2:0,K=B===qr?D[U]:F[U],Y=B===qr?-F[U]:-D[U],te=e.elements.arrow,ie=d&&te?bA(te):{width:0,height:0},he=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:bg(),fe=he[oe],_e=he[L],Te=Zn(0,D[U],ie[U]),Fe=C?D[U]/2-k-Te-fe-M.mainAxis:K-Te-fe-M.mainAxis,pe=C?-D[U]/2+k+Te+_e+M.mainAxis:Y+Te+_e+M.mainAxis,Qe=e.elements.arrow&&zn(e.elements.arrow),Ne=Qe?y==="y"?Qe.clientTop||0:Qe.clientLeft||0:0,Re=(le=j==null?void 0:j[y])!=null?le:0,Ke=q+Fe-Re-Ne,Se=q+pe-Re,ye=Zn(d?Po(R,Ke):R,q,d?Cr(_,Se):_);w[y]=ye,X[y]=ye-q}if(a){var ke,Ue=y==="x"?Nt:Ot,Xe=y==="x"?Jt:jt,Ge=w[x],$e=x==="y"?"height":"width",Ce=Ge+p[Ue],et=Ge-p[Xe],ot=[Nt,Ot].indexOf(v)!==-1,Ze=(ke=j==null?void 0:j[x])!=null?ke:0,ze=ot?Ce:Ge-D[$e]-F[$e]-Ze+M.altAxis,T=ot?Ge+D[$e]+F[$e]-Ze-M.altAxis:et,m=d&&ot?RS(ze,Ge,T):Zn(d?ze:Ce,Ge,d?T:et);w[x]=m,X[x]=m-Ge}e.modifiersData[i]=X}}const lb={name:"preventOverflow",enabled:!0,phase:"main",fn:ab,requiresIfExists:["offset"]};function Ab(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function cb(r){return r===$t(r)||!Xt(r)?QA(r):Ab(r)}function ub(r){var e=r.getBoundingClientRect(),t=Jr(e.width)/r.offsetWidth||1,i=Jr(e.height)/r.offsetHeight||1;return t!==1||i!==1}function hb(r,e,t){t===void 0&&(t=!1);var i=Xt(e),n=Xt(e)&&ub(e),s=zi(e),o=jr(r,n,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!t)&&((pi(e)!=="body"||wA(s))&&(a=cb(e)),Xt(e)?(l=jr(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):s&&(l.x=_A(s))),{x:o.left+a.scrollLeft-l.x,y:o.top+a.scrollTop-l.y,width:o.width,height:o.height}}function db(r){var e=new Map,t=new Set,i=[];r.forEach(function(s){e.set(s.name,s)});function n(s){t.add(s.name);var o=[].concat(s.requires||[],s.requiresIfExists||[]);o.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&n(l)}}),i.push(s)}return r.forEach(function(s){t.has(s.name)||n(s)}),i}function fb(r){var e=db(r);return bS.reduce(function(t,i){return t.concat(e.filter(function(n){return n.phase===i}))},[])}function gb(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}function pb(r){var e=r.reduce(function(t,i){var n=t[i.name];return t[i.name]=n?Object.assign({},n,i,{options:Object.assign({},n.options,i.options),data:Object.assign({},n.data,i.data)}):i,t},{});return Object.keys(e).map(function(t){return e[t]})}var Fg={placement:"bottom",modifiers:[],strategy:"absolute"};function Pg(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function mb(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,i=t===void 0?[]:t,n=e.defaultOptions,s=n===void 0?Fg:n;return function(a,l,A){A===void 0&&(A=s);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},Fg,s),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},c=[],h=!1,d={state:u,setOptions:function(v){var B=typeof v=="function"?v(u.options):v;g(),u.options=Object.assign({},s,u.options,B),u.scrollParents={reference:yr(a)?es(a):a.contextElement?es(a.contextElement):[],popper:es(l)};var C=fb(pb([].concat(i,u.options.modifiers)));return u.orderedModifiers=C.filter(function(y){return y.enabled}),f(),d.update()},forceUpdate:function(){if(!h){var v=u.elements,B=v.reference,C=v.popper;if(Pg(B,C)){u.rects={reference:hb(B,zn(C),u.options.strategy==="fixed"),popper:bA(C)},u.reset=!1,u.placement=u.options.placement,u.orderedModifiers.forEach(function(M){return u.modifiersData[M.name]=Object.assign({},M.data)});for(var y=0;y<u.orderedModifiers.length;y++){if(u.reset===!0){u.reset=!1,y=-1;continue}var x=u.orderedModifiers[y],w=x.fn,D=x.options,F=D===void 0?{}:D,O=x.name;typeof w=="function"&&(u=w({state:u,options:F,name:O,instance:d})||u)}}}},update:gb(function(){return new Promise(function(p){d.forceUpdate(),p(u)})}),destroy:function(){g(),h=!0}};if(!Pg(a,l))return d;d.setOptions(A).then(function(p){!h&&A.onFirstUpdate&&A.onFirstUpdate(p)});function f(){u.orderedModifiers.forEach(function(p){var v=p.name,B=p.options,C=B===void 0?{}:B,y=p.effect;if(typeof y=="function"){var x=y({state:u,name:v,instance:d,options:C}),w=function(){};c.push(x||w)}})}function g(){c.forEach(function(p){return p()}),c=[]}return d}}var Eb=[GS,sb,OS,Cg,rb,zS,lb,MS,eb],Ib=mb({defaultModifiers:Eb}),vb="tippy-box",Ng="tippy-content",yb="tippy-backdrop",Og="tippy-arrow",Ug="tippy-svg-arrow",Br={passive:!0,capture:!0},Gg=function(){return document.body};function DA(r,e,t){if(Array.isArray(r)){var i=r[e];return i??(Array.isArray(t)?t[e]:t)}return r}function LA(r,e){var t={}.toString.call(r);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function $g(r,e){return typeof r=="function"?r.apply(void 0,e):r}function Hg(r,e){if(e===0)return r;var t;return function(i){clearTimeout(t),t=setTimeout(function(){r(i)},e)}}function Cb(r){return r.split(/\s+/).filter(Boolean)}function zr(r){return[].concat(r)}function Yg(r,e){r.indexOf(e)===-1&&r.push(e)}function Bb(r){return r.filter(function(e,t){return r.indexOf(e)===t})}function Tb(r){return r.split("-")[0]}function Go(r){return[].slice.call(r)}function Vg(r){return Object.keys(r).reduce(function(e,t){return r[t]!==void 0&&(e[t]=r[t]),e},{})}function is(){return document.createElement("div")}function $o(r){return["Element","Fragment"].some(function(e){return LA(r,e)})}function Sb(r){return LA(r,"NodeList")}function bb(r){return LA(r,"MouseEvent")}function xb(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function Qb(r){return $o(r)?[r]:Sb(r)?Go(r):Array.isArray(r)?r:Go(document.querySelectorAll(r))}function kA(r,e){r.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function Kg(r,e){r.forEach(function(t){t&&t.setAttribute("data-state",e)})}function _b(r){var e,t=zr(r),i=t[0];return i!=null&&(e=i.ownerDocument)!=null&&e.body?i.ownerDocument:document}function wb(r,e){var t=e.clientX,i=e.clientY;return r.every(function(n){var s=n.popperRect,o=n.popperState,a=n.props,l=a.interactiveBorder,A=Tb(o.placement),u=o.modifiersData.offset;if(!u)return!0;var c=A==="bottom"?u.top.y:0,h=A==="top"?u.bottom.y:0,d=A==="right"?u.left.x:0,f=A==="left"?u.right.x:0,g=s.top-i+c>l,p=i-s.bottom-h>l,v=s.left-t+d>l,B=t-s.right-f>l;return g||p||v||B})}function MA(r,e,t){var i=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(n){r[i](n,t)})}function Wg(r,e){for(var t=e;t;){var i;if(r.contains(t))return!0;t=t.getRootNode==null||(i=t.getRootNode())==null?void 0:i.host}return!1}var Ei={isTouch:!1},qg=0;function Rb(){Ei.isTouch||(Ei.isTouch=!0,window.performance&&document.addEventListener("mousemove",Jg))}function Jg(){var r=performance.now();r-qg<20&&(Ei.isTouch=!1,document.removeEventListener("mousemove",Jg)),qg=r}function Db(){var r=document.activeElement;if(xb(r)){var e=r._tippy;r.blur&&!e.state.isVisible&&r.blur()}}function Lb(){document.addEventListener("touchstart",Rb,Br),window.addEventListener("blur",Db)}var kb=typeof window<"u"&&typeof document<"u",Mb=kb?!!window.msCrypto:!1,Fb={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Pb={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ii=Object.assign({appendTo:Gg,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},Fb,Pb),Nb=Object.keys(ii),Ob=function(e){var t=Object.keys(e);t.forEach(function(i){ii[i]=e[i]})};function jg(r){var e=r.plugins||[],t=e.reduce(function(i,n){var s=n.name,o=n.defaultValue;if(s){var a;i[s]=r[s]!==void 0?r[s]:(a=ii[s])!=null?a:o}return i},{});return Object.assign({},r,t)}function Ub(r,e){var t=e?Object.keys(jg(Object.assign({},ii,{plugins:e}))):Nb,i=t.reduce(function(n,s){var o=(r.getAttribute("data-tippy-"+s)||"").trim();if(!o)return n;if(s==="content")n[s]=o;else try{n[s]=JSON.parse(o)}catch{n[s]=o}return n},{});return i}function Xg(r,e){var t=Object.assign({},e,{content:$g(e.content,[r])},e.ignoreAttributes?{}:Ub(r,e.plugins));return t.aria=Object.assign({},ii.aria,t.aria),t.aria={expanded:t.aria.expanded==="auto"?e.interactive:t.aria.expanded,content:t.aria.content==="auto"?e.interactive?null:"describedby":t.aria.content},t}var Gb=function(){return"innerHTML"};function FA(r,e){r[Gb()]=e}function zg(r){var e=is();return r===!0?e.className=Og:(e.className=Ug,$o(r)?e.appendChild(r):FA(e,r)),e}function Zg(r,e){$o(e.content)?(FA(r,""),r.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?FA(r,e.content):r.textContent=e.content)}function PA(r){var e=r.firstElementChild,t=Go(e.children);return{box:e,content:t.find(function(i){return i.classList.contains(Ng)}),arrow:t.find(function(i){return i.classList.contains(Og)||i.classList.contains(Ug)}),backdrop:t.find(function(i){return i.classList.contains(yb)})}}function e0(r){var e=is(),t=is();t.className=vb,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var i=is();i.className=Ng,i.setAttribute("data-state","hidden"),Zg(i,r.props),e.appendChild(t),t.appendChild(i),n(r.props,r.props);function n(s,o){var a=PA(e),l=a.box,A=a.content,u=a.arrow;o.theme?l.setAttribute("data-theme",o.theme):l.removeAttribute("data-theme"),typeof o.animation=="string"?l.setAttribute("data-animation",o.animation):l.removeAttribute("data-animation"),o.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?l.setAttribute("role",o.role):l.removeAttribute("role"),(s.content!==o.content||s.allowHTML!==o.allowHTML)&&Zg(A,r.props),o.arrow?u?s.arrow!==o.arrow&&(l.removeChild(u),l.appendChild(zg(o.arrow))):l.appendChild(zg(o.arrow)):u&&l.removeChild(u)}return{popper:e,onUpdate:n}}e0.$$tippy=!0;var $b=1,Ho=[],NA=[];function Hb(r,e){var t=Xg(r,Object.assign({},ii,jg(Vg(e)))),i,n,s,o=!1,a=!1,l=!1,A=!1,u,c,h,d=[],f=Hg(Ke,t.interactiveDebounce),g,p=$b++,v=null,B=Bb(t.plugins),C={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:p,reference:r,popper:is(),popperInstance:v,props:t,state:C,plugins:B,clearDelayTimeouts:ze,setProps:T,setContent:m,show:E,hide:Q,hideWithInteractivity:N,enable:ot,disable:Ze,unmount:J,destroy:z};if(!t.render)return y;var x=t.render(y),w=x.popper,D=x.onUpdate;w.setAttribute("data-tippy-root",""),w.id="tippy-"+y.id,y.popper=w,r._tippy=y,w._tippy=y;var F=B.map(function($){return $.fn(y)}),O=r.hasAttribute("aria-expanded");return Qe(),k(),q(),R("onCreate",[y]),t.showOnCreate&&Ce(),w.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),w.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&oe().addEventListener("mousemove",f)}),y;function M(){var $=y.props.touch;return Array.isArray($)?$:[$,0]}function j(){return M()[0]==="hold"}function X(){var $;return!!(($=y.props.render)!=null&&$.$$tippy)}function le(){return g||r}function oe(){var $=le().parentNode;return $?_b($):document}function L(){return PA(w)}function U($){return y.state.isMounted&&!y.state.isVisible||Ei.isTouch||u&&u.type==="focus"?0:DA(y.props.delay,$?0:1,ii.delay)}function q($){$===void 0&&($=!1),w.style.pointerEvents=y.props.interactive&&!$?"":"none",w.style.zIndex=""+y.props.zIndex}function R($,ae,ue){if(ue===void 0&&(ue=!0),F.forEach(function(me){me[$]&&me[$].apply(me,ae)}),ue){var ve;(ve=y.props)[$].apply(ve,ae)}}function _(){var $=y.props.aria;if($.content){var ae="aria-"+$.content,ue=w.id,ve=zr(y.props.triggerTarget||r);ve.forEach(function(me){var nt=me.getAttribute(ae);if(y.state.isVisible)me.setAttribute(ae,nt?nt+" "+ue:ue);else{var Rt=nt&&nt.replace(ue,"").trim();Rt?me.setAttribute(ae,Rt):me.removeAttribute(ae)}})}}function k(){if(!(O||!y.props.aria.expanded)){var $=zr(y.props.triggerTarget||r);$.forEach(function(ae){y.props.interactive?ae.setAttribute("aria-expanded",y.state.isVisible&&ae===le()?"true":"false"):ae.removeAttribute("aria-expanded")})}}function K(){oe().removeEventListener("mousemove",f),Ho=Ho.filter(function($){return $!==f})}function Y($){if(!(Ei.isTouch&&(l||$.type==="mousedown"))){var ae=$.composedPath&&$.composedPath()[0]||$.target;if(!(y.props.interactive&&Wg(w,ae))){if(zr(y.props.triggerTarget||r).some(function(ue){return Wg(ue,ae)})){if(Ei.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else R("onClickOutside",[y,$]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),a=!0,setTimeout(function(){a=!1}),y.state.isMounted||fe())}}}function te(){l=!0}function ie(){l=!1}function he(){var $=oe();$.addEventListener("mousedown",Y,!0),$.addEventListener("touchend",Y,Br),$.addEventListener("touchstart",ie,Br),$.addEventListener("touchmove",te,Br)}function fe(){var $=oe();$.removeEventListener("mousedown",Y,!0),$.removeEventListener("touchend",Y,Br),$.removeEventListener("touchstart",ie,Br),$.removeEventListener("touchmove",te,Br)}function _e($,ae){Fe($,function(){!y.state.isVisible&&w.parentNode&&w.parentNode.contains(w)&&ae()})}function Te($,ae){Fe($,ae)}function Fe($,ae){var ue=L().box;function ve(me){me.target===ue&&(MA(ue,"remove",ve),ae())}if($===0)return ae();MA(ue,"remove",c),MA(ue,"add",ve),c=ve}function pe($,ae,ue){ue===void 0&&(ue=!1);var ve=zr(y.props.triggerTarget||r);ve.forEach(function(me){me.addEventListener($,ae,ue),d.push({node:me,eventType:$,handler:ae,options:ue})})}function Qe(){j()&&(pe("touchstart",Re,{passive:!0}),pe("touchend",Se,{passive:!0})),Cb(y.props.trigger).forEach(function($){if($!=="manual")switch(pe($,Re),$){case"mouseenter":pe("mouseleave",Se);break;case"focus":pe(Mb?"focusout":"blur",ye);break;case"focusin":pe("focusout",ye);break}})}function Ne(){d.forEach(function($){var ae=$.node,ue=$.eventType,ve=$.handler,me=$.options;ae.removeEventListener(ue,ve,me)}),d=[]}function Re($){var ae,ue=!1;if(!(!y.state.isEnabled||ke($)||a)){var ve=((ae=u)==null?void 0:ae.type)==="focus";u=$,g=$.currentTarget,k(),!y.state.isVisible&&bb($)&&Ho.forEach(function(me){return me($)}),$.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||o)&&y.props.hideOnClick!==!1&&y.state.isVisible?ue=!0:Ce($),$.type==="click"&&(o=!ue),ue&&!ve&&et($)}}function Ke($){var ae=$.target,ue=le().contains(ae)||w.contains(ae);if(!($.type==="mousemove"&&ue)){var ve=$e().concat(w).map(function(me){var nt,Rt=me._tippy,Dt=(nt=Rt.popperInstance)==null?void 0:nt.state;return Dt?{popperRect:me.getBoundingClientRect(),popperState:Dt,props:t}:null}).filter(Boolean);wb(ve,$)&&(K(),et($))}}function Se($){var ae=ke($)||y.props.trigger.indexOf("click")>=0&&o;if(!ae){if(y.props.interactive){y.hideWithInteractivity($);return}et($)}}function ye($){y.props.trigger.indexOf("focusin")<0&&$.target!==le()||y.props.interactive&&$.relatedTarget&&w.contains($.relatedTarget)||et($)}function ke($){return Ei.isTouch?j()!==$.type.indexOf("touch")>=0:!1}function Ue(){Xe();var $=y.props,ae=$.popperOptions,ue=$.placement,ve=$.offset,me=$.getReferenceClientRect,nt=$.moveTransition,Rt=X()?PA(w).arrow:null,Dt=me?{getBoundingClientRect:me,contextElement:me.contextElement||le()}:r,nn={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(sn){var ir=sn.state;if(X()){var ls=L(),As=ls.box;["placement","reference-hidden","escaped"].forEach(function(on){on==="placement"?As.setAttribute("data-placement",ir.placement):ir.attributes.popper["data-popper-"+on]?As.setAttribute("data-"+on,""):As.removeAttribute("data-"+on)}),ir.attributes.popper={}}}},Lt=[{name:"offset",options:{offset:ve}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!nt}},nn];X()&&Rt&&Lt.push({name:"arrow",options:{element:Rt,padding:3}}),Lt.push.apply(Lt,(ae==null?void 0:ae.modifiers)||[]),y.popperInstance=Ib(Dt,w,Object.assign({},ae,{placement:ue,onFirstUpdate:h,modifiers:Lt}))}function Xe(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Ge(){var $=y.props.appendTo,ae,ue=le();y.props.interactive&&$===Gg||$==="parent"?ae=ue.parentNode:ae=$g($,[ue]),ae.contains(w)||ae.appendChild(w),y.state.isMounted=!0,Ue()}function $e(){return Go(w.querySelectorAll("[data-tippy-root]"))}function Ce($){y.clearDelayTimeouts(),$&&R("onTrigger",[y,$]),he();var ae=U(!0),ue=M(),ve=ue[0],me=ue[1];Ei.isTouch&&ve==="hold"&&me&&(ae=me),ae?i=setTimeout(function(){y.show()},ae):y.show()}function et($){if(y.clearDelayTimeouts(),R("onUntrigger",[y,$]),!y.state.isVisible){fe();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf($.type)>=0&&o)){var ae=U(!1);ae?n=setTimeout(function(){y.state.isVisible&&y.hide()},ae):s=requestAnimationFrame(function(){y.hide()})}}function ot(){y.state.isEnabled=!0}function Ze(){y.hide(),y.state.isEnabled=!1}function ze(){clearTimeout(i),clearTimeout(n),cancelAnimationFrame(s)}function T($){if(!y.state.isDestroyed){R("onBeforeUpdate",[y,$]),Ne();var ae=y.props,ue=Xg(r,Object.assign({},ae,Vg($),{ignoreAttributes:!0}));y.props=ue,Qe(),ae.interactiveDebounce!==ue.interactiveDebounce&&(K(),f=Hg(Ke,ue.interactiveDebounce)),ae.triggerTarget&&!ue.triggerTarget?zr(ae.triggerTarget).forEach(function(ve){ve.removeAttribute("aria-expanded")}):ue.triggerTarget&&r.removeAttribute("aria-expanded"),k(),q(),D&&D(ae,ue),y.popperInstance&&(Ue(),$e().forEach(function(ve){requestAnimationFrame(ve._tippy.popperInstance.forceUpdate)})),R("onAfterUpdate",[y,$])}}function m($){y.setProps({content:$})}function E(){var $=y.state.isVisible,ae=y.state.isDestroyed,ue=!y.state.isEnabled,ve=Ei.isTouch&&!y.props.touch,me=DA(y.props.duration,0,ii.duration);if(!($||ae||ue||ve)&&!le().hasAttribute("disabled")&&(R("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,X()&&(w.style.visibility="visible"),q(),he(),y.state.isMounted||(w.style.transition="none"),X()){var nt=L(),Rt=nt.box,Dt=nt.content;kA([Rt,Dt],0)}h=function(){var Lt;if(!(!y.state.isVisible||A)){if(A=!0,w.offsetHeight,w.style.transition=y.props.moveTransition,X()&&y.props.animation){var Qr=L(),sn=Qr.box,ir=Qr.content;kA([sn,ir],me),Kg([sn,ir],"visible")}_(),k(),Yg(NA,y),(Lt=y.popperInstance)==null||Lt.forceUpdate(),R("onMount",[y]),y.props.animation&&X()&&Te(me,function(){y.state.isShown=!0,R("onShown",[y])})}},Ge()}}function Q(){var $=!y.state.isVisible,ae=y.state.isDestroyed,ue=!y.state.isEnabled,ve=DA(y.props.duration,1,ii.duration);if(!($||ae||ue)&&(R("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,A=!1,o=!1,X()&&(w.style.visibility="hidden"),K(),fe(),q(!0),X()){var me=L(),nt=me.box,Rt=me.content;y.props.animation&&(kA([nt,Rt],ve),Kg([nt,Rt],"hidden"))}_(),k(),y.props.animation?X()&&_e(ve,y.unmount):y.unmount()}}function N($){oe().addEventListener("mousemove",f),Yg(Ho,f),f($)}function J(){y.state.isVisible&&y.hide(),y.state.isMounted&&(Xe(),$e().forEach(function($){$._tippy.unmount()}),w.parentNode&&w.parentNode.removeChild(w),NA=NA.filter(function($){return $!==y}),y.state.isMounted=!1,R("onHidden",[y]))}function z(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Ne(),delete r._tippy,y.state.isDestroyed=!0,R("onDestroy",[y]))}}function Tr(r,e){e===void 0&&(e={});var t=ii.plugins.concat(e.plugins||[]);Lb();var i=Object.assign({},e,{plugins:t}),n=Qb(r),s=n.reduce(function(o,a){var l=a&&Hb(a,i);return l&&o.push(l),o},[]);return $o(r)?s[0]:s}Tr.defaultProps=ii,Tr.setDefaultProps=Ob,Tr.currentInput=Ei,Object.assign({},Cg,{effect:function(e){var t=e.state,i={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,i.popper),t.styles=i,t.elements.arrow&&Object.assign(t.elements.arrow.style,i.arrow)}}),Tr.setDefaultProps({render:e0});function zt(r,e){return`${r}-${e}`}function Ii(r){var e,t;const i=[];return(((e=r.renderer)==null?void 0:e.type)==="video"||((t=r.renderer)==null?void 0:t.type)==="audio")&&i.push({...r.config,...r.options}),i.push(...r.childNodes.flatMap(Ii).filter(Boolean)),i}class Yo extends Error{constructor(e,t=new Error,i=!1){super(),this.fatal=!1,this.fatal=i,this.stack=t.stack,this.message=[e,t.message].filter(Boolean).join(" - ")}}function Zi(r,e,t){return Math.min(Math.max(e,r),t)}const Yb=5;function Vb(r,e){return r.length!==e.length||r.some((t,i)=>t!==e[i])}class Kb{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._canvas=Qt(),this._controls=Qt(),this.host=e}set activeScenes(e){Vb(e,this._activeScenes)&&(this._activeScenes=e,this.host.dispatchEvent(new CustomEvent("scenechange",{detail:e})),this.host.requestUpdate())}get activeScenes(){return this._activeScenes}set currentTime(e){var t,i,n;const s=Zi(0,e,this.host.duration);this.activeScenes=((t=this.host.composition)==null?void 0:t.tracks.reduce((a,l)=>a.concat(l.scenes.filter(({start:A,duration:u})=>s>=A&&s<A+u)),[]))??[];const o=s!==this.currentTime;this._currentTime=s,this._upcomingScenes=((i=this.host.composition)==null?void 0:i.tracks.reduce((a,l)=>a.concat(l.scenes.filter(({start:A})=>s>=A-Yb&&s<A)),[]))??[],this.loadScenes(),this.syncMediaState(),(n=this._controls.value)==null||n.setAttribute("currentTime",s.toString()),o&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:s})),this.draw(s)}get currentTime(){return this._currentTime}set caption(e){e!==this._caption&&(this._caption=e,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return _t(this._canvas)}controls(){return _t(this._controls)}loadScenes(){[...this.activeScenes,...this._upcomingScenes].forEach(e=>{Ii(e.layout.node).forEach(({key:i})=>{var n,s,o;const{id:a,start:l,duration:A}=e,u=this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused,c=zt(a,i);if(this.host.media[c]){const h=this.host.media[c],{speed:d,volume:f,hls:g,node:p,start:v,duration:B}=h,C=this.host.mediaState[c];p&&C&&(p.currentTime>=v+B||p.ended||u&&(g?(n=g.startLoadOnce)==null||n.call(g,v):C.initialised||(s=p.startLoadOnce)==null||s.call(p),p.volume=Zi(0,this.host.volume*(f??1),1),p.playbackRate=Zi(.1,this.host.playbackRate*(d??1),4)))}else if(u){const h=`${l}-${A}`,d=this.host._sceneController.mediaState[h];this.host.duration&&!((o=d==null?void 0:d.buffered)!=null&&o.length)&&(this.host._sceneController.mediaState={...this.host._sceneController.mediaState,[h]:{...d,buffered:[{start:Math.max(0,l/this.host.duration*100),end:Math.min((l+A)/this.host.duration*100,100)}]}})}})})}syncMediaState(){var e;return Promise.all(((e=this.host.composition)==null?void 0:e.tracks.flatMap(t=>t.scenes.flatMap(i=>Ii(i.layout.node).map(async({key:s})=>{const o=zt(i.id,s);if(this.host.media[o]){const a=this.host.media[o],{node:l}=a,A=this.host.mediaState[o],u=this.activeScenes.includes(i);if(A)if(u&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(l.paused&&A.initialised)try{await l.play()}catch(c){throw new Yo("Video play error",c,!0)}}else l.paused||l.pause()}}))))??[])}draw(e=this.currentTime){this.host.composition&&this._canvas.value&&this.host.composition.draw({currentTime:e,canvas:this._canvas.value})}clear(){var e;const t=this._canvas.value;(e=t==null?void 0:t.getContext("2d"))==null||e.clearRect(0,0,t.width,t.height)}}const Wb=Hi(async function(e){const{weight:t,family:i}=e,{client:n,server:s}=i.weights.find(a=>a.weight===t)??{};return!n&&!s?null:new FontFace(e.family.name,`url(${n??s})`,{weight:t,style:"normal"}).load()},{cacheKey:([r])=>JSON.stringify(r)}),qb=Hi(async({options:r})=>{const e=await Wb(r.font);return e&&document.fonts.add(e),{font:r.font}}),Jb=Hi(async({config:r})=>r.src?new Promise((e,t)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>{e({image:i})},i.onerror=n=>{t(n)},i.src=r.src}):{image:null},{cacheKey:([{config:r}])=>JSON.stringify(r)});async function t0(r){return r.duration===1/0?new Promise(e=>{r.currentTime=Number.MAX_SAFE_INTEGER,r.ontimeupdate=()=>{r.ontimeupdate=null,e(r.duration),r.currentTime=0}}):r.duration}function jb(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Xb(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function zb(r){return new Promise(async e=>{let t=null;const{type:i,key:n,src:s,duration:o}=r;i==="video"?(t=document.createElement("video"),t.playsInline=!0):t=document.createElement("audio"),t.muted=!0,t.loop=!1,t.crossOrigin="anonymous",t.src=s;let a=!1;if(t.startLoadOnce=()=>{a||(t.preload="auto",t.load(),a=!0)},i==="video"&&o&&r.aspectRatio)t.preload="none",e({key:n,hls:null,node:t,aspectRatio:r.aspectRatio,totalDuration:o});else{t.preload="metadata";const l=async()=>{const A=await t0(t);e({key:n,hls:null,node:t,totalDuration:A,aspectRatio:t instanceof HTMLVideoElement?t.videoWidth/t.videoHeight:null}),t.removeEventListener("loadedmetadata",l)};t.addEventListener("loadedmetadata",l)}})}function Zb({key:r,playlist:e,duration:t}){return new Promise(i=>{const n=document.createElement("video");n instanceof HTMLVideoElement&&(n.playsInline=!0),n.muted=!0,n.loop=!1,n.crossOrigin="anonymous";let s=!1;const o=new gi({autoStartLoad:!0,xhrSetup:a=>{const{open:l}=a,A=e.split("?")[1];a.open=function(u,c,h){A&&!c.toString().includes("?")&&(c+="?"+A),!(!s&&c.toString().includes(".ts"))&&l.apply(this,[u,c,h])}}});o.on(gi.Events.LEVEL_LOADED,async()=>{s||o==null||o.stopLoad();const a=t??await t0(n);i({key:r,hls:o,node:n,aspectRatio:o.levels[0].width/o.levels[0].height,totalDuration:a})}),o.loadSource(e),o.attachMedia(n),o.startLoadOnce=(a=-1,l)=>{if(o&&!s){const A=o.levels.findIndex(u=>Math.min(u.height,u.width)===l);s=!0,o.startLevel=o.firstLevel,o.startLoad(a),o.currentLevel=A!==-1?A:o.firstLevel}}})}function ex(r){const{playlist:e}=r;return e&&!jb()&&gi.isSupported()?Zb({...r,playlist:e}):zb(r)}let tx=class{constructor(e){this._hasPlayed=!1,this._duration=0,this._composition=null,this._media={},this._mediaState={},this._compositionController=new AbortController,this._delayProcessing=(t=100)=>{const i=new AbortController,n=setTimeout(()=>{i.signal.aborted||(this.host._processing=!0)},t);return i.signal.addEventListener("abort",()=>{clearTimeout(n)}),i},this._mediaFactory=Hi(async(t,i)=>{const{key:n}=i,s=await ex(i),o={loadeddata:this._handleLoadedData,waiting:this._handleWaiting,canplay:this._handleCanPlay,progress:this._handleProgress,seeking:this._handleSeeking,seeked:this._handleSeeked,play:this._handlePlay,playing:this._handlePlaying,pause:this._handlePause,stalled:this._handleStalled,timeupdate:this._handleTimeUpdate,ended:this._handleEnded,error:this._handleError},a=Object.keys(o).reduce((l,A)=>{const u=A,c=o[u]({id:t,key:n,node:s.node});return l[u]=c,s.node.addEventListener(A,c),l},{});return{media:s,listeners:a,aspectRatio:s.aspectRatio,source:()=>s.node}},{cacheKey:([t,{key:i,src:n,playlist:s}])=>JSON.stringify({id:t,key:i,src:n==null?void 0:n.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._handleLoadedData=({id:t,key:i,node:n})=>()=>{const s=zt(t,i),o=this.mediaState[s];o!=null&&o.initialised||(this.mediaState={...this.mediaState,[s]:{...o,initialised:!0,waiting:!1,buffered:(o==null?void 0:o.buffered)??[]}},this.setMediaCurrentTime(this.host.currentTime),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{id:t,key:i,node:n}})))},this._handleWaiting=({id:t,key:i})=>()=>{const n=zt(t,i),s=this.mediaState[n];s!=null&&s.initialised&&!(s!=null&&s.waiting)&&(this.mediaState={...this.mediaState,[n]:{...s,waiting:!0}})},this._handleCanPlay=({id:t,key:i})=>()=>{const n=zt(t,i),s=this.mediaState[n];s!=null&&s.initialised&&(s!=null&&s.waiting)&&(this.mediaState={...this.mediaState,[n]:{...s,waiting:!1}}),this.host.paused&&this.host.draw()},this._handleProgress=()=>()=>{},this._handleSeeking=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:seeking",{detail:{id:t,key:i,node:n}}))},this._handleSeeked=({id:t,key:i,node:n})=>()=>{const s=zt(t,i),o=this.mediaState[s];o!=null&&o.initialised&&(this.host.draw(),this.host.activeScenes.flatMap(a=>Ii(a.layout.node).map(({id:A})=>A)).includes(t)&&this.host.dispatchEvent(new CustomEvent("seeked",{detail:this.host.currentTime})),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:t,key:i,node:n}})))},this._handlePlay=({id:t,key:i,node:n})=>()=>{this.hasPlayed=!0,this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:t,key:i,node:n}}))},this._handlePlaying=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:t,key:i,node:n}}))},this._handlePause=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:t,key:i,node:n}}))},this._handleStalled=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:t,key:i,node:n}}))},this._handleTimeUpdate=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:t,key:i,node:n}}))},this._handleEnded=({id:t,key:i,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:t,key:i,node:n}}))},this._handleError=({id:t,key:i,node:n})=>()=>{const s=new Yo(`Video error - answer ${t} failed to load`);this.host.dispatchEvent(new ErrorEvent("error",{bubbles:!0,composed:!0,error:s,message:s.message})),this.host.dispatchEvent(new CustomEvent("video:error",{detail:{id:t,key:i,node:n}}))},this._cleanupMedia=t=>{var i;const n=this.media[t];n&&(n.node.pause(),n.node.src="",(i=n.hls)==null||i.destroy(),Object.keys(n.listeners??{}).forEach(s=>{var o,a;if((o=this.media)!=null&&o[t]){const l=(a=n.listeners)==null?void 0:a[s];l&&n.node.removeEventListener(s,l)}}),delete this._media[t],delete this._mediaState[t])},this.host=e,this.host.addController(this)}set hasPlayed(e){e!==this._hasPlayed&&(this._hasPlayed=e,this.host.requestUpdate())}get hasPlayed(){return this._hasPlayed}set duration(e){!isNaN(e)&&e!==this._duration&&(this._duration=e,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set composition(e){e!==this._composition&&(this._composition=e,this.host.requestUpdate())}get composition(){return this._composition}set media(e){e!==this._media&&(this._media=e,this.host.requestUpdate())}get media(){return this._media}set mediaState(e){e!==this._mediaState&&(this._mediaState=e,this.host.requestUpdate())}get mediaState(){return this._mediaState}_setupTask(){new ys(this.host,async([e,t,i,n])=>{var s,o;this._compositionController.abort(),this._compositionController=new AbortController;const a=this._compositionController,l=this._delayProcessing();try{if(this.host._errors=[],(!t||!this.host._languages.find(({value:A})=>t===A))&&(this.host._language=(s=this.host._languages[0])==null?void 0:s.value),e){const{width:A,height:u}=ol({aspectRatio:i,resolution:1080});try{(o=this.composition)==null||o.cleanup();const f=await _h({debug:n,config:e,resolvers:{text:qb,image:Jb,video:async({id:g,config:p,options:v})=>{const{media:B,source:C}=await this._mediaFactory(g,{...p,...v});return{video:C,aspectRatio:B.aspectRatio}}},rootWidth:A,rootHeight:u});if(a.signal.aborted)return;this.composition=f}catch(f){throw new Yo("Fatal composition error",f,!0)}this.duration=this.composition.duration;const c={...this.media},h={...this.mediaState},d=[];for(const f of this.composition.tracks)for(const g of f.scenes){const p=Ii(g.layout.node);for(const v of p){const{media:B,listeners:C}=await this._mediaFactory(g.id,v),y=zt(g.id,B.key);d.push(y);const x=(v.startOffset??0)*B.totalDuration,w=(1-(v.endOffset??0))*B.totalDuration;c[y]={...B,listeners:C,start:x,duration:w-x,speed:v.speed??1,volume:v.volume??1},h[y]={initialised:!B,waiting:!!B,...this.mediaState[y]}}}this.media=c,this.mediaState=h,Object.keys(this.media).forEach(f=>{d.includes(f)||this.media[f].node.pause()}),this.host.currentTime>this.duration?this.host.reset(this.duration,!1):this.host.paused?this.host.reset(this.host.currentTime,!this.host.paused):this.setMediaCurrentTime(this.host.currentTime)}this.host.dispatchEvent(new CustomEvent("compositionupdate",{detail:this.composition,bubbles:!0,composed:!0}))}catch(A){this.composition=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",{composed:!0,bubbles:!0,error:A,message:A.message}))}finally{l.abort(),this.host._processing=!1}},()=>[this.host.config,this.host.language,this.host.aspectRatio,this.host.debug])}_setMediaCurrentTime({time:e,scene:t}){const{id:i,layout:n,start:s}=t;Ii(n.node).forEach(({key:a})=>{const l=zt(i,a);if(this.media[l]){const A=this.media[l],u=(e-s)*A.speed;A.node.currentTime=Zi(A.start,u+A.start,A.start+A.duration)}})}setMediaCurrentTime(e){var t;(t=this.composition)==null||t.tracks.forEach(i=>{i.scenes.forEach(n=>{this._setMediaCurrentTime({time:e,scene:n})})})}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.media).forEach(e=>{this._cleanupMedia(e)}),this.media={}}};function ix(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function rx(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const OA=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen","preview"],nx={id:"captions",event:"captions:click",label:"Closed Captions"},sx={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},i0={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},ox={id:"playbackRate",label:"Playback playbackRate",subItems:i0};class ax extends wc{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==Lr.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var e;(e=this.observer)==null||e.disconnect(),this.observer=void 0}reconnected(){var e;this.element&&((e=this.observer)==null||e.observe(this.element))}update(e,[t]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(t),this.element=e.element,this.observer.observe(this.element)),Oi}}const UA=kr(ax),lx=fS(()=>{const r=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),e=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-SemiBold.woff2)",{style:"normal",weight:"600"}),t=new FontFace("Roobert","url(https://vouch-clients.s3.ap-southeast-2.amazonaws.com/vouch/fonts/Roobert-Bold.woff2",{style:"normal",weight:"700"}),i=new FontFace("Roobert Captions","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),n=Ch.map(s=>({load:!1,font:new FontFace(s.family,`url(${s.url})`,{style:s.style})}));return[{load:!0,font:r},{load:!0,font:e},{load:!0,font:t},{load:!0,font:i},...n]}),vi={"red-120":"#feeded","red-130":"#fcd5d0","red-400":"#e84a4a","red-500":"#c51c3a","red-700":"#a21c39","red-800":"#850231","red-900":"#580A2D","teal-80":"#f3fafa","teal-100":"#d6f1f1","teal-200":"#ace3e3","teal-300":"#7acace","teal-400":"#4faab2","teal-500":"#358f97","teal-600":"#287179","teal-700":"#22555c","teal-800":"#21484e","teal-900":"#1f3d42","teal-950":"#0d2126","purple-100":"#d7cfff","purple-700":"#5f2fe9","green-200":"#a4d7aa","green-500":"#38b319","green-800":"#2b3c2f","grey-100":"#f0f0f0","light-50":"rgba(255, 255, 255, .05)","light-100":"rgba(255, 255, 255, .1)","light-200":"rgba(255, 255, 255, .2)","light-400":"rgba(255, 255, 255, .4)","light-500":"rgba(255, 255, 255, .5)","light-640":"rgba(255, 255, 255, .64)","light-800":"rgba(255, 255, 255, .8)","light-1000":"#fff","dark-50":"rgba(0, 0, 0, .05)","dark-80":"rgba(0, 0, 0, .08)","dark-100":"rgba(0, 0, 0, .1)","dark-200":"rgba(0, 0, 0, .2)","dark-250":"rgba(0, 0, 0, .25)","dark-400":"rgba(0, 0, 0, .4)","dark-500":"rgba(0, 0, 0, .5)","dark-640":"rgba(0, 0, 0, .64)","dark-800":"rgba(0, 0, 0, .8)","dark-900":"rgba(0, 0, 0, .9)","dark-1000":"#000"},Ax={colors:vi,space:{xxs:".25rem",xs:".5rem",small:".75rem",medium:"1rem",large:"1.5rem",xl:"2.5rem"},sizes:{xxs:"1rem",xs:"1.5rem",small:"2rem",medium:"2.5rem",large:"3rem"},fontWeights:{regular:400,semibold:600},lineHeights:{small:1.1,medium:1.25,large:1.4},letterSpacings:{xxs:"-.04rem",xs:"-.03rem",small:"-.02rem",medium:"-.01rem",large:0},fontSizes:{micro:".625rem",small:".75rem",medium:".875rem",large:"1rem",xl:"1.25rem",xxl:"1.5rem",xxxl:"2rem",huge:"2.75rem"},fontFamilies:{sans:'Roobert, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial,"Noto Sans", "Noto Color Emoji", sans-serif, "Segoe UI Emoji", "Segoe UI Symbol", "Apple Color Emoji"',mono:'"Maison Neue Mono", Menlo, Monaco, Consolas, Liberation Mono, "Courier New", monospace'},borderWidths:{thin:".0625rem"},radii:{small:".25rem",medium:".5rem",large:".75rem",xl:"1rem"},shadows:{small:`.25rem .25rem .25rem ${vi["dark-100"]}`,medium:`0 .125rem .625rem ${vi["dark-100"]}`,large:`0 .25rem 1rem ${vi["dark-50"]}`,xl:`.25rem .25rem 1rem ${vi["dark-250"]}`,xxl:`0 .25rem 2rem ${vi["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${vi["dark-250"]}`,toolbar:`0 -.625rem .625rem ${vi["dark-50"]}`,text:`0 0 .25rem ${vi["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:vi["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},r0=uS(Ax,{delimiter:"-"}),cx=Object.keys(r0).map(r=>hn(`:host { --${r}: ${r0[r]}; }`)),Je=(r=>{const e=class extends r{firstUpdated(){lx().forEach(({load:s,font:o})=>{document.fonts.add(o),s&&o.load()})}};return e.styles=[(r==null?void 0:r.styles)??[],cx,Bt`
2529
2529
  :host {
2530
2530
  font-family: var(--fontFamilies-sans);
2531
2531
  font-size: var(--fontSizes-medium);
@@ -2882,14 +2882,14 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2882
2882
  height: 32px;
2883
2883
  width: 32px;
2884
2884
  }
2885
- `],en([se({type:Boolean})],tr.prototype,"active",2),en([se({type:String})],tr.prototype,"size",2),en([se({type:String})],tr.prototype,"rounded",2),en([se({type:String})],tr.prototype,"weight",2),en([se({type:String})],tr.prototype,"icon",2),tr=en([kt("vmp-icon-button")],tr);var vx=Object.defineProperty,yx=Object.getOwnPropertyDescriptor,yi=(r,e,t,i)=>{for(var n=i>1?void 0:i?yx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&vx(e,t,n),n};let Sr=class extends Je{constructor(){super(...arguments),this.disabled=!1,this.aspectRatio=1,this.dataResolver=ul,this._currentTime=0,this._sceneController=new dx(this),this._canvasRef=xt(),this._previewRef=xt(),this._previewTimeRef=xt(),this._handleScrubberMouseEnter=({detail:{x:r,y:e,elementLeft:t,elementRight:i}})=>{var n,s;if((n=this._previewRef)!=null&&n.value){const o=this._previewRef.value.getBoundingClientRect(),a=(s=this._previewRef.value.getRootNode().host)==null?void 0:s.getBoundingClientRect();o&&a&&(this._previewRef.value.style.opacity="1",this._previewRef.value.style.transform=`translate3d(${Zi(t-a.left,r-a.left-o.width/2,i-a.left-o.width)}px, ${e-a.top-o.height-28}px, 0)`)}},this._handleScrubberMouseMove=({detail:{time:r,x:e,elementLeft:t,elementRight:i}})=>{var n,s,o,a,l,A,u,c,h,d;if(this._currentTime=r,(o=(s=(n=this._sceneController.composition)==null?void 0:n.tracks)==null?void 0:s[0])!=null&&o.scenes){const f=(u=(A=(l=(a=this._sceneController.composition)==null?void 0:a.tracks)==null?void 0:l[0])==null?void 0:A.scenes)==null?void 0:u.find(({start:g,duration:p})=>r>=g&&r<=g+p);if(f&&Ii(f.layout.node).forEach(({key:p})=>{var v,B;const C=zt(f.id,p);if(this._sceneController.videos[C]){const y=this._sceneController.videos[C];(B=(v=y.node).startLoadOnce)==null||B.call(v),y.node.currentTime=r-f.start}}),this._draw(),(c=this._previewRef)!=null&&c.value){const g=this._previewRef.value.getBoundingClientRect(),p=(h=this._previewRef.value.getRootNode().host)==null?void 0:h.getBoundingClientRect();if(g&&p){const v=this._previewRef.value.style.transform||"translate3d(0px, 0px, 0px)",[,B]=Array.from(v.matchAll(/([+-]?([0-9]*[.])?[0-9]+)(?=px)\w+/g));this._previewRef.value.style.transform=`translate3d(${Zi(t-p.left,e-p.left-g.width/2,i-p.left-g.width)}px, ${B[1]}px, 0)`}}this._previewTimeRef.value&&this._previewTimeRef.value.setAttribute("content",GA(Math.max(0,Math.min(this._currentTime,(d=this._sceneController.composition)==null?void 0:d.duration))))}},this._handleScrubberMouseLeave=()=>{var r;(r=this._previewRef)!=null&&r.value&&(this._previewRef.value.style.opacity="0")},this._handleScrubberResize=({detail:{y:r}})=>{var e,t;if((e=this._previewRef)!=null&&e.value){const i=this._previewRef.value.getBoundingClientRect(),n=(t=this._previewRef.value.getRootNode().host)==null?void 0:t.getBoundingClientRect();if(i&&n){const s=this._previewRef.value.style.transform||"translate3d(0px, 0px, 0px)",[o]=Array.from(s.matchAll(/([+-]?([0-9]*[.])?[0-9]+)(?=px)\w+/g));this._previewRef.value.style.transform=`translate3d(${o[1]}px, ${r-n.top-i.height-28}px, 0)`}}}}_draw(r=this._currentTime){this._sceneController.composition&&this._canvasRef.value&&this._sceneController.composition.draw({canvas:this._canvasRef.value,currentTime:Math.max(0,Math.min(r,this._sceneController.composition.duration))})}connectedCallback(){super.connectedCallback();const r=rs("vmp-media-player",this);r==null||r.addEventListener("scrubber:resize",this._handleScrubberResize),r==null||r.addEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),r==null||r.addEventListener("scrubber:mousemove",this._handleScrubberMouseMove),r==null||r.addEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}disconnectedCallback(){super.disconnectedCallback();const r=rs("vmp-media-player",this);r==null||r.removeEventListener("scrubber:resize",this._handleScrubberResize),r==null||r.removeEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),r==null||r.removeEventListener("scrubber:mousemove",this._handleScrubberMouseMove),r==null||r.removeEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}render(){var r,e,t;const{height:i,width:n}=ol({resolution:180,aspectRatio:this.aspectRatio}),s=((t=(e=(r=this._sceneController.composition)==null?void 0:r.tracks)==null?void 0:e[0])==null?void 0:t.scenes.length)??0;return!this.disabled&&s>1?xe`
2885
+ `],en([se({type:Boolean})],tr.prototype,"active",2),en([se({type:String})],tr.prototype,"size",2),en([se({type:String})],tr.prototype,"rounded",2),en([se({type:String})],tr.prototype,"weight",2),en([se({type:String})],tr.prototype,"icon",2),tr=en([kt("vmp-icon-button")],tr);var vx=Object.defineProperty,yx=Object.getOwnPropertyDescriptor,yi=(r,e,t,i)=>{for(var n=i>1?void 0:i?yx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&vx(e,t,n),n};let Sr=class extends Je{constructor(){super(...arguments),this.disabled=!1,this.aspectRatio=1,this.dataResolver=ul,this._currentTime=0,this._sceneController=new dx(this),this._canvasRef=Qt(),this._previewRef=Qt(),this._previewTimeRef=Qt(),this._handleScrubberMouseEnter=({detail:{x:r,y:e,elementLeft:t,elementRight:i}})=>{var n,s;if((n=this._previewRef)!=null&&n.value){const o=this._previewRef.value.getBoundingClientRect(),a=(s=this._previewRef.value.getRootNode().host)==null?void 0:s.getBoundingClientRect();o&&a&&(this._previewRef.value.style.opacity="1",this._previewRef.value.style.transform=`translate3d(${Zi(t-a.left,r-a.left-o.width/2,i-a.left-o.width)}px, ${e-a.top-o.height-28}px, 0)`)}},this._handleScrubberMouseMove=({detail:{time:r,x:e,elementLeft:t,elementRight:i}})=>{var n,s,o,a,l,A,u,c,h,d;if(this._currentTime=r,(o=(s=(n=this._sceneController.composition)==null?void 0:n.tracks)==null?void 0:s[0])!=null&&o.scenes){const f=(u=(A=(l=(a=this._sceneController.composition)==null?void 0:a.tracks)==null?void 0:l[0])==null?void 0:A.scenes)==null?void 0:u.find(({start:g,duration:p})=>r>=g&&r<=g+p);if(f&&Ii(f.layout.node).forEach(({key:p})=>{var v,B;const C=zt(f.id,p);if(this._sceneController.videos[C]){const y=this._sceneController.videos[C];(B=(v=y.node).startLoadOnce)==null||B.call(v),y.node.currentTime=r-f.start}}),this._draw(),(c=this._previewRef)!=null&&c.value){const g=this._previewRef.value.getBoundingClientRect(),p=(h=this._previewRef.value.getRootNode().host)==null?void 0:h.getBoundingClientRect();if(g&&p){const v=this._previewRef.value.style.transform||"translate3d(0px, 0px, 0px)",[,B]=Array.from(v.matchAll(/([+-]?([0-9]*[.])?[0-9]+)(?=px)\w+/g));this._previewRef.value.style.transform=`translate3d(${Zi(t-p.left,e-p.left-g.width/2,i-p.left-g.width)}px, ${B[1]}px, 0)`}}this._previewTimeRef.value&&this._previewTimeRef.value.setAttribute("content",GA(Math.max(0,Math.min(this._currentTime,(d=this._sceneController.composition)==null?void 0:d.duration))))}},this._handleScrubberMouseLeave=()=>{var r;(r=this._previewRef)!=null&&r.value&&(this._previewRef.value.style.opacity="0")},this._handleScrubberResize=({detail:{y:r}})=>{var e,t;if((e=this._previewRef)!=null&&e.value){const i=this._previewRef.value.getBoundingClientRect(),n=(t=this._previewRef.value.getRootNode().host)==null?void 0:t.getBoundingClientRect();if(i&&n){const s=this._previewRef.value.style.transform||"translate3d(0px, 0px, 0px)",[o]=Array.from(s.matchAll(/([+-]?([0-9]*[.])?[0-9]+)(?=px)\w+/g));this._previewRef.value.style.transform=`translate3d(${o[1]}px, ${r-n.top-i.height-28}px, 0)`}}}}_draw(r=this._currentTime){this._sceneController.composition&&this._canvasRef.value&&this._sceneController.composition.draw({canvas:this._canvasRef.value,currentTime:Math.max(0,Math.min(r,this._sceneController.composition.duration))})}connectedCallback(){super.connectedCallback();const r=rs("vmp-media-player",this);r==null||r.addEventListener("scrubber:resize",this._handleScrubberResize),r==null||r.addEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),r==null||r.addEventListener("scrubber:mousemove",this._handleScrubberMouseMove),r==null||r.addEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}disconnectedCallback(){super.disconnectedCallback();const r=rs("vmp-media-player",this);r==null||r.removeEventListener("scrubber:resize",this._handleScrubberResize),r==null||r.removeEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),r==null||r.removeEventListener("scrubber:mousemove",this._handleScrubberMouseMove),r==null||r.removeEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}render(){var r,e,t;const{height:i,width:n}=ol({resolution:180,aspectRatio:this.aspectRatio}),s=((t=(e=(r=this._sceneController.composition)==null?void 0:r.tracks)==null?void 0:e[0])==null?void 0:t.scenes.length)??0;return!this.disabled&&s>1?xe`
2886
2886
  <div
2887
- ${Qt(this._previewRef)}
2887
+ ${_t(this._previewRef)}
2888
2888
  class="preview"
2889
2889
  style=${hl({width:this.aspectRatio>1?"140px":void 0,height:this.aspectRatio<=1?"140px":void 0,aspectRatio:this.aspectRatio})}
2890
2890
  >
2891
- <canvas ${Qt(this._canvasRef)} class="preview-canvas" width=${n} height=${i}></canvas>
2892
- <vmp-text ${Qt(this._previewTimeRef)} class="preview-text" size="small"></vmp-text>
2891
+ <canvas ${_t(this._canvasRef)} class="preview-canvas" width=${n} height=${i}></canvas>
2892
+ <vmp-text ${_t(this._previewTimeRef)} class="preview-text" size="small"></vmp-text>
2893
2893
  </div>
2894
2894
  `:null}};Sr.styles=[Je.styles??[],Bt`
2895
2895
  .preview {
@@ -2929,7 +2929,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2929
2929
  .aspectRatio=${this.aspectRatio}
2930
2930
  .dataResolver=${this.dataResolver}
2931
2931
  ></vmp-video-preview-content>
2932
- `}};yi([se({type:Object})],tn.prototype,"config",2),yi([se({type:Boolean})],tn.prototype,"disabled",2),yi([se({type:Number})],tn.prototype,"aspectRatio",2),yi([se({attribute:!1})],tn.prototype,"dataResolver",2),tn=yi([kt("vmp-video-preview")],tn);class Cx extends yn{constructor(e){if(super(e),e.type!==Lr.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(e,[t]){return t==null||t(e.element),Oi}}const o0=kr(Cx);class Bx{constructor(e){this.hiddenControls=[],this._measureRef=xt(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=t=>{var i,n,s;const o=this._measureRef.value,a=(s=(n=(i=t==null?void 0:t[0])==null?void 0:i.borderBoxSize)==null?void 0:n[0])==null?void 0:s.inlineSize;if(o&&a&&a!==this._prevControlsWidth){Object.keys(this._hideables).forEach(A=>{this._hideables[A].element.style.display=""}),Object.keys(this._showables).forEach(A=>{this._showables[A].element.style.display="none"});const l=[];for(;o.scrollWidth>o.offsetWidth;){const A=Object.keys(this._hideables).find(c=>this._hideables[c].hideIndex===l.length);if(!A)break;const u=this._hideables[A].element;u&&(u.style.display="none"),l.push(A),Object.keys(this._showables).forEach(c=>{this._showables[c].showOn.some(h=>l.includes(h))&&(this._showables[c].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=a,this.host.requestUpdate()}},this.host=e}measure(){return Qt(this._measureRef)}contain(){return UA(this._onResize)}hide(e,t){return o0(i=>{this._hideables[e]={element:i,hideIndex:t}})}show(e,t){return o0(i=>{this._showables[e]={element:i,showOn:t}})}}const $A=".tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translateX(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translateX(-5px)}";var Tx=Object.defineProperty,Sx=Object.getOwnPropertyDescriptor,ns=(r,e,t,i)=>{for(var n=i>1?void 0:i?Sx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Tx(e,t,n),n};let br=class extends Je{constructor(){super(...arguments),this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return xe`
2932
+ `}};yi([se({type:Object})],tn.prototype,"config",2),yi([se({type:Boolean})],tn.prototype,"disabled",2),yi([se({type:Number})],tn.prototype,"aspectRatio",2),yi([se({attribute:!1})],tn.prototype,"dataResolver",2),tn=yi([kt("vmp-video-preview")],tn);class Cx extends yn{constructor(e){if(super(e),e.type!==Lr.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(e,[t]){return t==null||t(e.element),Oi}}const o0=kr(Cx);class Bx{constructor(e){this.hiddenControls=[],this._measureRef=Qt(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=t=>{var i,n,s;const o=this._measureRef.value,a=(s=(n=(i=t==null?void 0:t[0])==null?void 0:i.borderBoxSize)==null?void 0:n[0])==null?void 0:s.inlineSize;if(o&&a&&a!==this._prevControlsWidth){Object.keys(this._hideables).forEach(A=>{this._hideables[A].element.style.display=""}),Object.keys(this._showables).forEach(A=>{this._showables[A].element.style.display="none"});const l=[];for(;o.scrollWidth>o.offsetWidth;){const A=Object.keys(this._hideables).find(c=>this._hideables[c].hideIndex===l.length);if(!A)break;const u=this._hideables[A].element;u&&(u.style.display="none"),l.push(A),Object.keys(this._showables).forEach(c=>{this._showables[c].showOn.some(h=>l.includes(h))&&(this._showables[c].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=a,this.host.requestUpdate()}},this.host=e}measure(){return _t(this._measureRef)}contain(){return UA(this._onResize)}hide(e,t){return o0(i=>{this._hideables[e]={element:i,hideIndex:t}})}show(e,t){return o0(i=>{this._showables[e]={element:i,showOn:t}})}}const $A=".tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translateX(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translateX(-5px)}";var Tx=Object.defineProperty,Sx=Object.getOwnPropertyDescriptor,ns=(r,e,t,i)=>{for(var n=i>1?void 0:i?Sx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Tx(e,t,n),n};let br=class extends Je{constructor(){super(...arguments),this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return xe`
2933
2933
  <div
2934
2934
  part="content"
2935
2935
  class=${tt({semibold:this.semibold,truncate:this.truncate,[this.size]:!0})}
@@ -2974,9 +2974,9 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2974
2974
  text-overflow: ellipsis;
2975
2975
  overflow: hidden;
2976
2976
  }
2977
- `],ns([se({type:Boolean})],br.prototype,"semibold",2),ns([se({type:Boolean})],br.prototype,"truncate",2),ns([se({type:String})],br.prototype,"size",2),ns([se({type:String})],br.prototype,"content",2),br=ns([kt("vmp-text")],br);var bx=Object.defineProperty,xx=Object.getOwnPropertyDescriptor,ss=(r,e,t,i)=>{for(var n=i>1?void 0:i?xx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&bx(e,t,n),n};let xr=class extends Je{constructor(){super(...arguments),this.activeItems=[],this.visibleItems=null,this.subItemsActive=null,this.tippy=null,this._contentRef=xt()}_handleBackClick(){this.subItemsActive=null,this.visibleItems=this.items??null}willUpdate(){this.visibleItems=this.visibleItems??this.items??null}updated(){var r,e;const t=(e=(r=this.items)==null?void 0:r.items.find(({id:i})=>this.subItemsActive===i))==null?void 0:e.subItems;this.visibleItems=t??this.items??null,t||(this.subItemsActive=null)}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),t=e==null?void 0:e.assignedElements()[0];t&&this._contentRef.value&&(this.tippy=Tr(t,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",trigger:"click",onShow:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){var r,e;return xe`
2977
+ `],ns([se({type:Boolean})],br.prototype,"semibold",2),ns([se({type:Boolean})],br.prototype,"truncate",2),ns([se({type:String})],br.prototype,"size",2),ns([se({type:String})],br.prototype,"content",2),br=ns([kt("vmp-text")],br);var bx=Object.defineProperty,xx=Object.getOwnPropertyDescriptor,ss=(r,e,t,i)=>{for(var n=i>1?void 0:i?xx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&bx(e,t,n),n};let xr=class extends Je{constructor(){super(...arguments),this.activeItems=[],this.visibleItems=null,this.subItemsActive=null,this.tippy=null,this._contentRef=Qt()}_handleBackClick(){this.subItemsActive=null,this.visibleItems=this.items??null}willUpdate(){this.visibleItems=this.visibleItems??this.items??null}updated(){var r,e;const t=(e=(r=this.items)==null?void 0:r.items.find(({id:i})=>this.subItemsActive===i))==null?void 0:e.subItems;this.visibleItems=t??this.items??null,t||(this.subItemsActive=null)}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),t=e==null?void 0:e.assignedElements()[0];t&&this._contentRef.value&&(this.tippy=Tr(t,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",trigger:"click",onShow:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){var r,e;return xe`
2978
2978
  <slot></slot>
2979
- <div ${Qt(this._contentRef)} class="content">
2979
+ <div ${_t(this._contentRef)} class="content">
2980
2980
  <div class="title">
2981
2981
  ${this.subItemsActive?xe`
2982
2982
  <button class="back" @click=${this._handleBackClick}>
@@ -3062,9 +3062,9 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3062
3062
  height: 20px;
3063
3063
  width: 20px;
3064
3064
  }
3065
- `],ss([se({type:Object})],xr.prototype,"items",2),ss([se({type:Array})],xr.prototype,"activeItems",2),ss([dt()],xr.prototype,"visibleItems",2),ss([dt()],xr.prototype,"subItemsActive",2),xr=ss([kt("vmp-menu")],xr);var Qx=Object.defineProperty,_x=Object.getOwnPropertyDescriptor,HA=(r,e,t,i)=>{for(var n=i>1?void 0:i?_x(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Qx(e,t,n),n};let os=class extends Je{constructor(){super(...arguments),this.content="",this.disabled=!1,this.tippy=null,this._contentRef=xt()}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),t=e==null?void 0:e.assignedElements()[0];t&&this._contentRef.value&&(this.tippy=Tr(t,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!1,placement:"top",zIndex:1e4,appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}updated(){var r,e;this.disabled?(r=this.tippy)==null||r.disable():(e=this.tippy)==null||e.enable()}render(){return xe`
3065
+ `],ss([se({type:Object})],xr.prototype,"items",2),ss([se({type:Array})],xr.prototype,"activeItems",2),ss([dt()],xr.prototype,"visibleItems",2),ss([dt()],xr.prototype,"subItemsActive",2),xr=ss([kt("vmp-menu")],xr);var Qx=Object.defineProperty,_x=Object.getOwnPropertyDescriptor,HA=(r,e,t,i)=>{for(var n=i>1?void 0:i?_x(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Qx(e,t,n),n};let os=class extends Je{constructor(){super(...arguments),this.content="",this.disabled=!1,this.tippy=null,this._contentRef=Qt()}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const e=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),t=e==null?void 0:e.assignedElements()[0];t&&this._contentRef.value&&(this.tippy=Tr(t,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!1,placement:"top",zIndex:1e4,appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}updated(){var r,e;this.disabled?(r=this.tippy)==null||r.disable():(e=this.tippy)==null||e.enable()}render(){return xe`
3066
3066
  <slot></slot>
3067
- <div ${Qt(this._contentRef)} class="content">
3067
+ <div ${_t(this._contentRef)} class="content">
3068
3068
  <vmp-text content=${this.content}></vmp-text>
3069
3069
  </div>
3070
3070
  `}};os.styles=[Je.styles??[],hn($A),Bt`
@@ -3081,16 +3081,16 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3081
3081
  background: var(--colors-dark-800);
3082
3082
  border-radius: var(--radii-medium);
3083
3083
  }
3084
- `],HA([se({type:String})],os.prototype,"content",2),HA([se({type:Boolean})],os.prototype,"disabled",2),os=HA([kt("vmp-tooltip")],os);var wx=Object.defineProperty,Rx=Object.getOwnPropertyDescriptor,YA=(r,e,t,i)=>{for(var n=i>1?void 0:i?Rx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&wx(e,t,n),n};let as=class extends Je{constructor(){super(...arguments),this.volume=1,this.muted=!1,this.tippy=null,this._contentRef=xt(),this._anchorRef=xt(),this._menuOpen=!1}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{this._anchorRef.value&&this._contentRef.value&&(this.tippy=Tr(this._anchorRef.value,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",interactiveBorder:20,onShow:()=>{this._menuOpen=!0,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this._menuOpen=!1,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){return xe`
3084
+ `],HA([se({type:String})],os.prototype,"content",2),HA([se({type:Boolean})],os.prototype,"disabled",2),os=HA([kt("vmp-tooltip")],os);var wx=Object.defineProperty,Rx=Object.getOwnPropertyDescriptor,YA=(r,e,t,i)=>{for(var n=i>1?void 0:i?Rx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&wx(e,t,n),n};let as=class extends Je{constructor(){super(...arguments),this.volume=1,this.muted=!1,this.tippy=null,this._contentRef=Qt(),this._anchorRef=Qt(),this._menuOpen=!1}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{this._anchorRef.value&&this._contentRef.value&&(this.tippy=Tr(this._anchorRef.value,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",interactiveBorder:20,onShow:()=>{this._menuOpen=!0,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this._menuOpen=!1,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){return xe`
3085
3085
  <vmp-icon-button
3086
- ${Qt(this._anchorRef)}
3086
+ ${_t(this._anchorRef)}
3087
3087
  icon=${this.muted||this.volume===0?"muted":this.volume<1/3?"volume-low":this.volume<2/3?"volume-medium":"volume-high"}
3088
3088
  weight="heavy"
3089
3089
  rounded="full"
3090
3090
  @pointerdown=${r=>{this._menuOpen&&r.preventDefault()}}
3091
3091
  @click=${()=>{this._menuOpen&&this.dispatchEvent(new CustomEvent("volume:click",{bubbles:!0,composed:!0,detail:this.muted}))}}
3092
3092
  ></vmp-icon-button>
3093
- <div ${Qt(this._contentRef)} class="content">
3093
+ <div ${_t(this._contentRef)} class="content">
3094
3094
  <input
3095
3095
  key="volume"
3096
3096
  type="range"
@@ -3243,10 +3243,10 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3243
3243
  --volume-slider-height: 8px;
3244
3244
  color: var(--colors-light-800);
3245
3245
  }
3246
- `],YA([se({type:Number})],as.prototype,"volume",2),YA([se({type:Boolean})],as.prototype,"muted",2),as=YA([kt("vmp-volume-button")],as);var Dx=Object.defineProperty,Lx=Object.getOwnPropertyDescriptor,Ko=(r,e,t,i)=>{for(var n=i>1?void 0:i?Lx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Dx(e,t,n),n};let rn=class extends Je{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[],this._containerRef=xt(),this._handleContainerResize=()=>{var r;const e=(r=this._containerRef.value)==null?void 0:r.getBoundingClientRect();this.dispatchEvent(new CustomEvent("scrubber:resize",{detail:e,bubbles:!0,composed:!0}))},this._handleMouseEnter=r=>{var e;const t=(e=this._containerRef.value)==null?void 0:e.getBoundingClientRect();this.dispatchEvent(new CustomEvent("scrubber:mouseenter",{detail:{x:r.clientX,y:r.clientY,elementLeft:(t==null?void 0:t.left)??0,elementRight:(t==null?void 0:t.right)??document.body.offsetWidth},bubbles:!0,composed:!0}))},this._handleMouseMove=r=>{var e;const t=(e=this._containerRef.value)==null?void 0:e.getBoundingClientRect(),n=(r.clientX-((t==null?void 0:t.left)??0))/((t==null?void 0:t.width)??1);this.dispatchEvent(new CustomEvent("scrubber:mousemove",{detail:{x:r.clientX,y:r.clientY,time:n*this.duration,elementLeft:(t==null?void 0:t.left)??0,elementRight:(t==null?void 0:t.right)??document.body.offsetWidth},bubbles:!0,composed:!0}))},this._handleMouseLeave=r=>{this.dispatchEvent(new CustomEvent("scrubber:mouseleave",{detail:{x:r.clientX,y:r.clientY},bubbles:!0,composed:!0}))}}render(){var r;const e=((r=this.buffer)==null?void 0:r.sort((t,i)=>t.start<i.start?-1:i.start<t.start?1:0).reduce((t,{start:i,end:n},s)=>{const o=t[s-1],a=Math.floor(i),l=Math.ceil(n);return t.push({id:i,start:Math.max(0,a),end:Math.min(l,100)}),o&&o.end>=i-1&&(t[s].start=o.end),t},[]))??[];return xe`
3246
+ `],YA([se({type:Number})],as.prototype,"volume",2),YA([se({type:Boolean})],as.prototype,"muted",2),as=YA([kt("vmp-volume-button")],as);var Dx=Object.defineProperty,Lx=Object.getOwnPropertyDescriptor,Ko=(r,e,t,i)=>{for(var n=i>1?void 0:i?Lx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Dx(e,t,n),n};let rn=class extends Je{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[],this._containerRef=Qt(),this._handleContainerResize=()=>{var r;const e=(r=this._containerRef.value)==null?void 0:r.getBoundingClientRect();this.dispatchEvent(new CustomEvent("scrubber:resize",{detail:e,bubbles:!0,composed:!0}))},this._handleMouseEnter=r=>{var e;const t=(e=this._containerRef.value)==null?void 0:e.getBoundingClientRect();this.dispatchEvent(new CustomEvent("scrubber:mouseenter",{detail:{x:r.clientX,y:r.clientY,elementLeft:(t==null?void 0:t.left)??0,elementRight:(t==null?void 0:t.right)??document.body.offsetWidth},bubbles:!0,composed:!0}))},this._handleMouseMove=r=>{var e;const t=(e=this._containerRef.value)==null?void 0:e.getBoundingClientRect(),n=(r.clientX-((t==null?void 0:t.left)??0))/((t==null?void 0:t.width)??1);this.dispatchEvent(new CustomEvent("scrubber:mousemove",{detail:{x:r.clientX,y:r.clientY,time:n*this.duration,elementLeft:(t==null?void 0:t.left)??0,elementRight:(t==null?void 0:t.right)??document.body.offsetWidth},bubbles:!0,composed:!0}))},this._handleMouseLeave=r=>{this.dispatchEvent(new CustomEvent("scrubber:mouseleave",{detail:{x:r.clientX,y:r.clientY},bubbles:!0,composed:!0}))}}render(){var r;const e=((r=this.buffer)==null?void 0:r.sort((t,i)=>t.start<i.start?-1:i.start<t.start?1:0).reduce((t,{start:i,end:n},s)=>{const o=t[s-1],a=Math.floor(i),l=Math.ceil(n);return t.push({id:i,start:Math.max(0,a),end:Math.min(l,100)}),o&&o.end>=i-1&&(t[s].start=o.end),t},[]))??[];return xe`
3247
3247
  <div
3248
3248
  class="container"
3249
- ${Qt(this._containerRef)}
3249
+ ${_t(this._containerRef)}
3250
3250
  ${UA(this._handleContainerResize)}
3251
3251
  @mouseenter=${this._handleMouseEnter}
3252
3252
  @mousemove=${this._handleMouseMove}
@@ -3416,7 +3416,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3416
3416
  --player-scrubber-height: 16px;
3417
3417
  color: var(--colors-light-800);
3418
3418
  }
3419
- `],Ko([se({type:Number})],rn.prototype,"duration",2),Ko([se({type:Number})],rn.prototype,"currentTime",2),Ko([se({type:Array})],rn.prototype,"buffer",2),rn=Ko([kt("vmp-progress-scrubber")],rn);var kx=Object.defineProperty,Mx=Object.getOwnPropertyDescriptor,ft=(r,e,t,i)=>{for(var n=i>1?void 0:i?Mx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&kx(e,t,n),n};let lt=class extends Je{constructor(){super(...arguments),this.resizeHider=new Bx(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.languages=[],this.language="en",this.levels=[],this.level=-1,this.playbackRate=1,this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=OA,this.volumeMenuOpen=!1,this.languageMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLanguageMenuOpen({detail:r}){this.languageMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,e;(e=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-menu, vmp-tooltip, vmp-volume-button")))==null||e.forEach(t=>{var i;(i=t.tippy)==null||i.hide()})}render(){var r,e,t,i,n,s,o,a,l,A,u,c,h,d,f;const g=((r=this.languages)==null?void 0:r.map(Y=>({id:`language-${Y.value}`,event:"language:click",label:Y.label,value:Y.value})))??[],p={title:"Languages",items:g},v={id:"languages",label:"Languages",subItems:p},B=p.items.find(({value:Y})=>Y===this.language),C=((e=this.levels)==null?void 0:e.map((Y,te)=>{const ie=Math.min(Y.width,Y.height);return{id:`level-${te.toString()}`,event:"level:click",label:`${ie}p`,value:{resolution:ie,level:te}}}))??[],y={title:"Quality",items:[...C.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},x={id:"levels",label:"Quality",subItems:y},w=(t=y.items)==null?void 0:t.find(({value:Y})=>Y.level===this.level),D=[(g==null?void 0:g.length)&&"languages","levels","playback-rate","captions","fullscreen"].filter(Boolean).filter(Y=>{var te;return(te=this.controls)==null?void 0:te.includes(Y)}),F={title:"Settings",items:[(g==null?void 0:g.length)&&v,nx,sx,x,ox].filter(Boolean).filter(({id:Y})=>D.includes(Y)&&this.resizeHider.hiddenControls.includes(Y))},O=(i=this.controls)==null?void 0:i.includes("progress"),M=(n=this.controls)==null?void 0:n.includes("navigation"),j=(s=this.controls)==null?void 0:s.includes("play"),X=(o=this.controls)==null?void 0:o.includes("volume"),le=(a=this.controls)==null?void 0:a.includes("current-time"),oe=(l=this.controls)==null?void 0:l.includes("duration"),L=(A=this.controls)==null?void 0:A.includes("languages"),U=(u=this.controls)==null?void 0:u.includes("levels"),q=(c=this.controls)==null?void 0:c.includes("speed"),R=(h=this.controls)==null?void 0:h.includes("captions"),_=(d=this.controls)==null?void 0:d.includes("fullscreen"),k=j||X||le||oe||L||U||q||R||_,K=[this.captions&&"captions",this.fullscreen&&"fullscreen",`language-${this.language}`,`level-${(f=this.level)==null?void 0:f.toString()}`,`playback-rate-${this.playbackRate.toString()}`].filter(Boolean);return xe`
3419
+ `],Ko([se({type:Number})],rn.prototype,"duration",2),Ko([se({type:Number})],rn.prototype,"currentTime",2),Ko([se({type:Array})],rn.prototype,"buffer",2),rn=Ko([kt("vmp-progress-scrubber")],rn);var kx=Object.defineProperty,Mx=Object.getOwnPropertyDescriptor,ft=(r,e,t,i)=>{for(var n=i>1?void 0:i?Mx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&kx(e,t,n),n};let At=class extends Je{constructor(){super(...arguments),this.resizeHider=new Bx(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.languages=[],this.language="en",this.levels=[],this.level=-1,this.playbackRate=1,this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=OA,this.volumeMenuOpen=!1,this.languageMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLanguageMenuOpen({detail:r}){this.languageMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,e;(e=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-menu, vmp-tooltip, vmp-volume-button")))==null||e.forEach(t=>{var i;(i=t.tippy)==null||i.hide()})}render(){var r,e,t,i,n,s,o,a,l,A,u,c,h,d,f;const g=((r=this.languages)==null?void 0:r.map(Y=>({id:`language-${Y.value}`,event:"language:click",label:Y.label,value:Y.value})))??[],p={title:"Languages",items:g},v={id:"languages",label:"Languages",subItems:p},B=p.items.find(({value:Y})=>Y===this.language),C=((e=this.levels)==null?void 0:e.map((Y,te)=>{const ie=Math.min(Y.width,Y.height);return{id:`level-${te.toString()}`,event:"level:click",label:`${ie}p`,value:{resolution:ie,level:te}}}))??[],y={title:"Quality",items:[...C.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},x={id:"levels",label:"Quality",subItems:y},w=(t=y.items)==null?void 0:t.find(({value:Y})=>Y.level===this.level),D=[(g==null?void 0:g.length)&&"languages","levels","playback-rate","captions","fullscreen"].filter(Boolean).filter(Y=>{var te;return(te=this.controls)==null?void 0:te.includes(Y)}),F={title:"Settings",items:[(g==null?void 0:g.length)&&v,nx,sx,x,ox].filter(Boolean).filter(({id:Y})=>D.includes(Y)&&this.resizeHider.hiddenControls.includes(Y))},O=(i=this.controls)==null?void 0:i.includes("progress"),M=(n=this.controls)==null?void 0:n.includes("navigation"),j=(s=this.controls)==null?void 0:s.includes("play"),X=(o=this.controls)==null?void 0:o.includes("volume"),le=(a=this.controls)==null?void 0:a.includes("current-time"),oe=(l=this.controls)==null?void 0:l.includes("duration"),L=(A=this.controls)==null?void 0:A.includes("languages"),U=(u=this.controls)==null?void 0:u.includes("levels"),q=(c=this.controls)==null?void 0:c.includes("speed"),R=(h=this.controls)==null?void 0:h.includes("captions"),_=(d=this.controls)==null?void 0:d.includes("fullscreen"),k=j||X||le||oe||L||U||q||R||_,K=[this.captions&&"captions",this.fullscreen&&"fullscreen",`language-${this.language}`,`level-${(f=this.level)==null?void 0:f.toString()}`,`playback-rate-${this.playbackRate.toString()}`].filter(Boolean);return xe`
3420
3420
  <div
3421
3421
  ${this.resizeHider.measure()}
3422
3422
  ${this.resizeHider.contain()}
@@ -3557,7 +3557,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3557
3557
  </div>
3558
3558
  </div>
3559
3559
  </div>
3560
- `}};lt.styles=[Je.styles??[],Bt`
3560
+ `}};At.styles=[Je.styles??[],Bt`
3561
3561
  :host {
3562
3562
  --controls-border-radius: var(--player-border-radius, 0px);
3563
3563
 
@@ -3628,7 +3628,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3628
3628
  .hidden {
3629
3629
  display: none;
3630
3630
  }
3631
- `],ft([se({type:Boolean})],lt.prototype,"playing",2),ft([se({type:Number})],lt.prototype,"volume",2),ft([se({type:Boolean})],lt.prototype,"muted",2),ft([se({type:Number})],lt.prototype,"currentTime",2),ft([se({type:Number})],lt.prototype,"duration",2),ft([se({type:Array})],lt.prototype,"languages",2),ft([se({type:String})],lt.prototype,"language",2),ft([se({type:Array,attribute:!1})],lt.prototype,"levels",2),ft([se({type:Number})],lt.prototype,"level",2),ft([se({type:Number})],lt.prototype,"playbackRate",2),ft([se({type:Array})],lt.prototype,"buffer",2),ft([se({type:Boolean})],lt.prototype,"captions",2),ft([se({type:Boolean})],lt.prototype,"fullscreen",2),ft([se({type:Array})],lt.prototype,"controls",2),ft([dt()],lt.prototype,"volumeMenuOpen",2),ft([dt()],lt.prototype,"languageMenuOpen",2),ft([dt()],lt.prototype,"levelsMenuOpen",2),ft([dt()],lt.prototype,"playbackRateMenuOpen",2),ft([dt()],lt.prototype,"settingsMenuOpen",2),lt=ft([kt("vmp-player-controls")],lt);var Fx=Object.getOwnPropertyDescriptor,Px=(r,e,t,i)=>{for(var n=i>1?void 0:i?Fx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=o(n)||n);return n};let VA=class extends Je{render(){return xe`<vmp-icon icon="loading"></vmp-icon>`}};VA.styles=[Je.styles??[],Bt`
3631
+ `],ft([se({type:Boolean})],At.prototype,"playing",2),ft([se({type:Number})],At.prototype,"volume",2),ft([se({type:Boolean})],At.prototype,"muted",2),ft([se({type:Number})],At.prototype,"currentTime",2),ft([se({type:Number})],At.prototype,"duration",2),ft([se({type:Array})],At.prototype,"languages",2),ft([se({type:String})],At.prototype,"language",2),ft([se({type:Array,attribute:!1})],At.prototype,"levels",2),ft([se({type:Number})],At.prototype,"level",2),ft([se({type:Number})],At.prototype,"playbackRate",2),ft([se({type:Array})],At.prototype,"buffer",2),ft([se({type:Boolean})],At.prototype,"captions",2),ft([se({type:Boolean})],At.prototype,"fullscreen",2),ft([se({type:Array})],At.prototype,"controls",2),ft([dt()],At.prototype,"volumeMenuOpen",2),ft([dt()],At.prototype,"languageMenuOpen",2),ft([dt()],At.prototype,"levelsMenuOpen",2),ft([dt()],At.prototype,"playbackRateMenuOpen",2),ft([dt()],At.prototype,"settingsMenuOpen",2),At=ft([kt("vmp-player-controls")],At);var Fx=Object.getOwnPropertyDescriptor,Px=(r,e,t,i)=>{for(var n=i>1?void 0:i?Fx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=o(n)||n);return n};let VA=class extends Je{render(){return xe`<vmp-icon icon="loading"></vmp-icon>`}};VA.styles=[Je.styles??[],Bt`
3632
3632
  :host {
3633
3633
  display: flex;
3634
3634
  align-items: center;
@@ -3657,7 +3657,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3657
3657
  /* Line height controls the spacing between the cloned boxes so has to override the default */
3658
3658
  line-height: 2.2;
3659
3659
  }
3660
- `],a0([se({type:String})],Wo.prototype,"caption",2),Wo=a0([kt("vmp-captions")],Wo);var Ux=Object.defineProperty,Gx=Object.getOwnPropertyDescriptor,Ct=(r,e,t,i)=>{for(var n=i>1?void 0:i?Gx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Ux(e,t,n),n};const $x=3e3;let gt=class extends Je{constructor(){super(...arguments),this.loading=!1,this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.languages=[],this.language="en",this.levels=[],this.level=-1,this.playbackRate=1,this.caption="",this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=OA,this.showControls=!0,this._hasTouched=!1,this._playerControlsRef=xt()}_startHideControls(){clearTimeout(this._controlHideTimeout),this._controlHideTimeout=setTimeout(()=>{this.showControls=!1,this._hasTouched=!1},$x)}_immediateShowControls(){this.showControls=!0,clearTimeout(this._controlHideTimeout)}_immediateHideControls(){this.showControls=!1,this._hasTouched=!1,clearTimeout(this._controlHideTimeout)}willUpdate(r){var e;r.has("playing")&&this.playing&&this._startHideControls(),r.has("showControls")&&this.playing&&!this.showControls&&((e=this._playerControlsRef.value)==null||e.hideMenus())}render(){var r;const e=(r=this.controls)==null?void 0:r.includes("play-large"),t=this.playing&&!this.showControls,i=!!(e&&!this.playing);return xe`
3660
+ `],a0([se({type:String})],Wo.prototype,"caption",2),Wo=a0([kt("vmp-captions")],Wo);var Ux=Object.defineProperty,Gx=Object.getOwnPropertyDescriptor,Ct=(r,e,t,i)=>{for(var n=i>1?void 0:i?Gx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Ux(e,t,n),n};const $x=3e3;let gt=class extends Je{constructor(){super(...arguments),this.loading=!1,this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.languages=[],this.language="en",this.levels=[],this.level=-1,this.playbackRate=1,this.caption="",this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=OA,this.showControls=!0,this._hasTouched=!1,this._playerControlsRef=Qt()}_startHideControls(){clearTimeout(this._controlHideTimeout),this._controlHideTimeout=setTimeout(()=>{this.showControls=!1,this._hasTouched=!1},$x)}_immediateShowControls(){this.showControls=!0,clearTimeout(this._controlHideTimeout)}_immediateHideControls(){this.showControls=!1,this._hasTouched=!1,clearTimeout(this._controlHideTimeout)}willUpdate(r){var e;r.has("playing")&&this.playing&&this._startHideControls(),r.has("showControls")&&this.playing&&!this.showControls&&((e=this._playerControlsRef.value)==null||e.hideMenus())}render(){var r;const e=(r=this.controls)==null?void 0:r.includes("play-large"),t=this.playing&&!this.showControls,i=!!(e&&!this.playing);return xe`
3661
3661
  <div
3662
3662
  class=${tt({container:!0,hide:t})}
3663
3663
  @mousemove=${()=>{this._immediateShowControls(),this._startHideControls()}}
@@ -3687,7 +3687,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3687
3687
  caption=${this.caption}
3688
3688
  ></vmp-captions>`:null}
3689
3689
  <vmp-player-controls
3690
- ${Qt(this._playerControlsRef)}
3690
+ ${_t(this._playerControlsRef)}
3691
3691
  ?playing=${this.playing}
3692
3692
  ?muted=${this.muted}
3693
3693
  volume=${this.volume}
@@ -3777,7 +3777,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3777
3777
  vmp-captions.hiddenControls {
3778
3778
  transform: translateY(calc(var(--space-small) * -1));
3779
3779
  }
3780
- `],Ct([se({type:Boolean})],gt.prototype,"loading",2),Ct([se({type:Boolean})],gt.prototype,"playing",2),Ct([se({type:Number})],gt.prototype,"volume",2),Ct([se({type:Boolean})],gt.prototype,"muted",2),Ct([se({type:Number})],gt.prototype,"currentTime",2),Ct([se({type:Number})],gt.prototype,"duration",2),Ct([se({type:Array})],gt.prototype,"languages",2),Ct([se({type:String})],gt.prototype,"language",2),Ct([se({type:Array,attribute:!1})],gt.prototype,"levels",2),Ct([se({type:Number})],gt.prototype,"level",2),Ct([se({type:Number})],gt.prototype,"playbackRate",2),Ct([se({type:String})],gt.prototype,"caption",2),Ct([se({type:Array})],gt.prototype,"buffer",2),Ct([se({type:Boolean})],gt.prototype,"captions",2),Ct([se({type:Boolean})],gt.prototype,"fullscreen",2),Ct([se({type:Array})],gt.prototype,"controls",2),Ct([dt()],gt.prototype,"showControls",2),gt=Ct([kt("vmp-player-overlay")],gt);var Hx=Object.defineProperty,Yx=Object.getOwnPropertyDescriptor,At=(r,e,t,i)=>{for(var n=i>1?void 0:i?Yx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Hx(e,t,n),n};const Vx=1e3/60,Kx=30;let rt=class extends Je{constructor(){super(...arguments),this.debug=!1,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.disabled=!1,this.dataResolver=ul,this.languageResolver=By,this._sceneController=new tx(this),this._drawController=new Kb(this),this._observer=null,this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._seekerTimeout=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastCurrentTime=null,this._playerRef=xt(),this._canvasRef=xt(),this._pageHidden=document.visibilityState==="hidden",this._aspectRatio=this.propAspectRatio,this._processing=!1,this._waiting=!1,this._errors=[],this._seeking=!1,this._language=this.propLanguage,this._languages=[],this._captions=!1,this._fullscreen=!1,this._initialised=null,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{var r;(r=this.shadowRoot)!=null&&r.host&&!this.propAspectRatio&&(this._aspectRatio=this.shadowRoot.host.clientWidth/this.shadowRoot.host.clientHeight)},this._handleCanvasResize=()=>{this.draw()},this._loop=()=>{this._endLoop(),this._pageHidden?this._seekerTimeout=setTimeout(this._seeker,Vx):this._seekerRAF=requestAnimationFrame(this._seeker)},this._endLoop=()=>{this._seekerRAF&&cancelAnimationFrame(this._seekerRAF),this._seekerTimeout&&clearTimeout(this._seekerTimeout),this._seekerRAF=null,this._seekerTimeout=null},this._seeker=(r=performance.now())=>{if(this.composition){if(this._waiting=this._drawController.activeScenes.some(({id:e,layout:t})=>Ii(t.node).some(({key:n})=>{const s=zt(e,n);if(this.media[s]&&this.mediaState[s]){const o=this.media[s],a=this.mediaState[s];return!a||!a.initialised||a.waiting||o.node.readyState<3}})),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),r-(this._lastTimestamp??0)>1e3/Kx){let e=this._drawController.currentTime;const t=(r-(this._lastTimestamp??r))/1e3*this.playbackRate;this.activeScenes.every(({id:n,layout:s},o)=>Ii(s.node).every(({key:l},A)=>{var u,c;const h=zt(n,l),d=this.media[h];return((c=(u=this._lastCurrentTime)==null?void 0:u[o])==null?void 0:c[A])!==d.node.currentTime}))&&(e+=t),this._lastCurrentTime=this.activeScenes.map(({id:n,layout:s})=>Ii(s.node).map(({key:a})=>{const l=zt(n,a);return this.media[l].node.currentTime})),this._drawController.currentTime=e,this._lastTimestamp=r}this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))}this.paused||this._loop()},this._handleError=r=>{this._errors=[...this.errors,r.error],r.error.fatal&&this.pause()},this._handleFullscreenChange=()=>{this===document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1},this._handleVisibilityChange=()=>{this._pageHidden=document.visibilityState==="hidden",this.paused||this._loop()}}get aspectRatio(){return this._aspectRatio}get processing(){return this._processing}get waiting(){return!this.paused&&this._waiting}get errors(){return this._errors}get seeking(){return this._seeking}get language(){return this._language}get languages(){return this._languages}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get initialised(){return this._initialised=this._initialised??new Promise(r=>{const e=setInterval(()=>{!!this.errors.find(i=>i.fatal)&&r(!1),!this.loading&&!this.processing&&this.composition&&this.duration>0&&r(!0)},500);setTimeout(()=>{clearInterval(e),r(!1)},60*1e3)}),this._initialised}get duration(){return this._sceneController.duration}get media(){return this._sceneController.media??{}}get mediaState(){return this._sceneController.mediaState}get composition(){return this._sceneController.composition}get activeScenes(){return this._drawController.activeScenes}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,Object.values(this.media).forEach(({node:e,speed:t})=>{e.playbackRate=Zi(.1,r*t,4)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const e=Zi(0,r,1);e!==this._volume&&(Object.values(this.media).forEach(({node:t,volume:i})=>{t.volume=e*i}),localStorage.setItem("vmp-player-volume/v2",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume/v2")??"1"))}set muted(r){Object.values(this.media).forEach(({node:e,volume:t})=>{e.muted=t===0||r}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-player-muted/v2",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-player-muted/v2")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,Object.values(this.media).forEach(({hls:e})=>{if(e){const t=e.levels.findIndex(i=>Math.min(i.height,i.width)===r);e.currentLevel=t??-1}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._sceneController.setMediaCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,e=!1){this._lastTimestamp=null,this._lastCurrentTime=null,this._drawController.currentTime=r,this._sceneController.setMediaCurrentTime(r),e?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastCurrentTime=null,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._loop()}pause(){this._endLoop(),this.paused=!0,Object.values(this.media).forEach(({node:r})=>{r.pause()})}draw(r){return this._drawController.draw(r)}toggleFullscreen(r){r??this.fullscreen?rx():this._playerRef.value&&ix(this._playerRef.value)}connectedCallback(){var r;super.connectedCallback(),this.addEventListener("error",this._handleError),document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("visibilitychange",this._handleVisibilityChange),(r=this.shadowRoot)!=null&&r.host&&(this._observer=new ResizeObserver(this._handleContainerResize),this._observer.observe(this.shadowRoot.host))}willUpdate(r){r.has("propAspectRatio")&&(this._aspectRatio=this.propAspectRatio),r.has("propLanguage")&&(this._language=this.propLanguage)}updated(r){r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize(),this.autoplay&&!this._sceneController.hasPlayed&&!this.processing&&r.get("_processing")&&this.play(),r.has("_processing")&&this.processing&&this.dispatchEvent(new CustomEvent("processing"))}disconnectedCallback(){var r,e;super.disconnectedCallback(),(r=this._observer)==null||r.disconnect(),(e=this.composition)==null||e.cleanup(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("visibilitychange",this._handleVisibilityChange)}_renderStyles(){return this.propAspectRatio?typeof this.propAspectRatio=="number"?xe`
3780
+ `],Ct([se({type:Boolean})],gt.prototype,"loading",2),Ct([se({type:Boolean})],gt.prototype,"playing",2),Ct([se({type:Number})],gt.prototype,"volume",2),Ct([se({type:Boolean})],gt.prototype,"muted",2),Ct([se({type:Number})],gt.prototype,"currentTime",2),Ct([se({type:Number})],gt.prototype,"duration",2),Ct([se({type:Array})],gt.prototype,"languages",2),Ct([se({type:String})],gt.prototype,"language",2),Ct([se({type:Array,attribute:!1})],gt.prototype,"levels",2),Ct([se({type:Number})],gt.prototype,"level",2),Ct([se({type:Number})],gt.prototype,"playbackRate",2),Ct([se({type:String})],gt.prototype,"caption",2),Ct([se({type:Array})],gt.prototype,"buffer",2),Ct([se({type:Boolean})],gt.prototype,"captions",2),Ct([se({type:Boolean})],gt.prototype,"fullscreen",2),Ct([se({type:Array})],gt.prototype,"controls",2),Ct([dt()],gt.prototype,"showControls",2),gt=Ct([kt("vmp-player-overlay")],gt);var Hx=Object.defineProperty,Yx=Object.getOwnPropertyDescriptor,ct=(r,e,t,i)=>{for(var n=i>1?void 0:i?Yx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Hx(e,t,n),n};const Vx=1e3/60,Kx=30;let rt=class extends Je{constructor(){super(...arguments),this.debug=!1,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.disabled=!1,this.dataResolver=ul,this.languageResolver=By,this._sceneController=new tx(this),this._drawController=new Kb(this),this._observer=null,this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._seekerTimeout=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastCurrentTime=null,this._playerRef=Qt(),this._canvasRef=Qt(),this._pageHidden=document.visibilityState==="hidden",this._aspectRatio=this.propAspectRatio,this._processing=!1,this._waiting=!1,this._errors=[],this._seeking=!1,this._language=this.propLanguage,this._languages=[],this._captions=!1,this._fullscreen=!1,this._initialised=null,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{var r;(r=this.shadowRoot)!=null&&r.host&&!this.propAspectRatio&&(this._aspectRatio=this.shadowRoot.host.clientWidth/this.shadowRoot.host.clientHeight)},this._handleCanvasResize=()=>{this.draw()},this._loop=()=>{this._endLoop(),this._pageHidden?this._seekerTimeout=setTimeout(this._seeker,Vx):this._seekerRAF=requestAnimationFrame(this._seeker)},this._endLoop=()=>{this._seekerRAF&&cancelAnimationFrame(this._seekerRAF),this._seekerTimeout&&clearTimeout(this._seekerTimeout),this._seekerRAF=null,this._seekerTimeout=null},this._seeker=(r=performance.now())=>{if(this.composition){if(this._waiting=this._drawController.activeScenes.some(({id:e,layout:t})=>Ii(t.node).some(({key:n})=>{const s=zt(e,n);if(this.media[s]&&this.mediaState[s]){const o=this.media[s],a=this.mediaState[s];return!a||!a.initialised||a.waiting||o.node.readyState<3}})),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),r-(this._lastTimestamp??0)>1e3/Kx){let e=this._drawController.currentTime;const t=(r-(this._lastTimestamp??r))/1e3*this.playbackRate;this.activeScenes.every(({id:n,layout:s},o)=>Ii(s.node).every(({key:l},A)=>{var u,c;const h=zt(n,l),d=this.media[h];return((c=(u=this._lastCurrentTime)==null?void 0:u[o])==null?void 0:c[A])!==d.node.currentTime}))&&(e+=t),this._lastCurrentTime=this.activeScenes.map(({id:n,layout:s})=>Ii(s.node).map(({key:a})=>{const l=zt(n,a);return this.media[l].node.currentTime})),this._drawController.currentTime=e,this._lastTimestamp=r}this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))}this.paused||this._loop()},this._handleError=r=>{this._errors=[...this.errors,r.error],r.error.fatal&&this.pause()},this._handleFullscreenChange=()=>{this===document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1},this._handleVisibilityChange=()=>{this._pageHidden=document.visibilityState==="hidden",this.paused||this._loop()}}get aspectRatio(){return this._aspectRatio}get processing(){return this._processing}get waiting(){return!this.paused&&this._waiting}get errors(){return this._errors}get seeking(){return this._seeking}get language(){return this._language}get languages(){return this._languages}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get initialised(){return this._initialised=this._initialised??new Promise(r=>{const e=setInterval(()=>{!!this.errors.find(i=>i.fatal)&&r(!1),!this.loading&&!this.processing&&this.composition&&this.duration>0&&r(!0)},500);setTimeout(()=>{clearInterval(e),r(!1)},60*1e3)}),this._initialised}get duration(){return this._sceneController.duration}get media(){return this._sceneController.media??{}}get mediaState(){return this._sceneController.mediaState}get composition(){return this._sceneController.composition}get activeScenes(){return this._drawController.activeScenes}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,Object.values(this.media).forEach(({node:e,speed:t})=>{e.playbackRate=Zi(.1,r*t,4)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const e=Zi(0,r,1);e!==this._volume&&(Object.values(this.media).forEach(({node:t,volume:i})=>{t.volume=e*i}),localStorage.setItem("vmp-player-volume/v2",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume/v2")??"1"))}set muted(r){Object.values(this.media).forEach(({node:e,volume:t})=>{e.muted=t===0||r}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-player-muted/v2",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-player-muted/v2")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,Object.values(this.media).forEach(({hls:e})=>{if(e){const t=e.levels.findIndex(i=>Math.min(i.height,i.width)===r);e.currentLevel=t??-1}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._sceneController.setMediaCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,e=!1){this._lastTimestamp=null,this._lastCurrentTime=null,this._drawController.currentTime=r,this._sceneController.setMediaCurrentTime(r),e?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastCurrentTime=null,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._loop()}pause(){this._endLoop(),this.paused=!0,Object.values(this.media).forEach(({node:r})=>{r.pause()})}draw(r){return this._drawController.draw(r)}toggleFullscreen(r){r??this.fullscreen?rx():this._playerRef.value&&ix(this._playerRef.value)}connectedCallback(){var r;super.connectedCallback(),this.addEventListener("error",this._handleError),document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("visibilitychange",this._handleVisibilityChange),(r=this.shadowRoot)!=null&&r.host&&(this._observer=new ResizeObserver(this._handleContainerResize),this._observer.observe(this.shadowRoot.host))}willUpdate(r){r.has("propAspectRatio")&&(this._aspectRatio=this.propAspectRatio),r.has("propLanguage")&&(this._language=this.propLanguage)}updated(r){r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize(),this.autoplay&&!this._sceneController.hasPlayed&&!this.processing&&r.get("_processing")&&this.play(),r.has("_processing")&&this.processing&&this.dispatchEvent(new CustomEvent("processing"))}disconnectedCallback(){var r,e;super.disconnectedCallback(),(r=this._observer)==null||r.disconnect(),(e=this.composition)==null||e.cleanup(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("visibilitychange",this._handleVisibilityChange)}_renderStyles(){return this.propAspectRatio?typeof this.propAspectRatio=="number"?xe`
3781
3781
  <style>
3782
3782
  :host {
3783
3783
  aspect-ratio: ${this.propAspectRatio};
@@ -3801,12 +3801,12 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3801
3801
  </div>`}render(){var r;const e=this.disabled||this.loading||this.processing||!this.composition||this.duration<=0,{height:t,width:i}=ol({resolution:1080,aspectRatio:this.aspectRatio}),n=e?[]:(r=this.controls??OA)==null?void 0:r.filter(A=>!(A==="fullscreen"&&Xb())),s=!(n!=null&&n.includes("preview")),o=this.loading||this.waiting||this.processing,a=!this.config,l=!!this.errors.find(A=>A.fatal);return xe`
3802
3802
  ${this._renderStyles()}
3803
3803
  <div
3804
- ${Qt(this._playerRef)}
3804
+ ${_t(this._playerRef)}
3805
3805
  class=${tt({player:!0,responsive:!this.propAspectRatio})}
3806
3806
  style=${hl({aspectRatio:this.aspectRatio})}
3807
3807
  >
3808
3808
  ${!o&&(a||l)?this._renderError():xe`<canvas
3809
- ${Qt(this._canvasRef)}
3809
+ ${_t(this._canvasRef)}
3810
3810
  ${this._drawController.canvas()}
3811
3811
  ${UA(this._handleCanvasResize)}
3812
3812
  height=${t}
@@ -3907,7 +3907,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3907
3907
  top: 0;
3908
3908
  left: 0;
3909
3909
  }
3910
- `],At([se({type:Boolean})],rt.prototype,"debug",2),At([se({type:Object})],rt.prototype,"config",2),At([se({type:String,attribute:"language"})],rt.prototype,"propLanguage",2),At([se({type:Number,attribute:"aspectratio"})],rt.prototype,"propAspectRatio",2),At([se({type:String})],rt.prototype,"preload",2),At([se({type:Boolean})],rt.prototype,"autoplay",2),At([se({type:Boolean})],rt.prototype,"loading",2),At([se({type:Boolean})],rt.prototype,"disabled",2),At([se({type:Array})],rt.prototype,"controls",2),At([se({attribute:!1})],rt.prototype,"dataResolver",2),At([se({attribute:!1})],rt.prototype,"languageResolver",2),At([dt()],rt.prototype,"_pageHidden",2),At([dt()],rt.prototype,"_aspectRatio",2),At([dt()],rt.prototype,"_processing",2),At([dt()],rt.prototype,"_waiting",2),At([dt()],rt.prototype,"_errors",2),At([dt()],rt.prototype,"_seeking",2),At([dt()],rt.prototype,"_language",2),At([dt()],rt.prototype,"_languages",2),At([dt()],rt.prototype,"_captions",2),At([dt()],rt.prototype,"_fullscreen",2),rt=At([kt("vmp-media-player")],rt);var Wx=Object.defineProperty,qx=Object.getOwnPropertyDescriptor,wt=(r,e,t,i)=>{for(var n=i>1?void 0:i?qx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Wx(e,t,n),n};return ct.PlayerEmbed=class extends Dr{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new gp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","scenesupdate","seeking","seeked","timeupdate","volumechange","processing","waiting","video:loadeddata","video:seeking","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new Op(this),this._trackingController=new dy(this),this._mediaPlayerRef=xt()}get fetching(){return this._fetcherController.fetching}get waiting(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.waiting}get initialised(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.initialised}get seeking(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.seeking}get paused(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.paused}get captions(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.captions}get fullscreen(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.fullscreen}get duration(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.duration}set currentTime(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=e)}get currentTime(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.currentTime)??0}set playbackRate(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=e)}get playbackRate(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.playbackRate)??1}set volume(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=e)}get volume(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.volume)??1}set muted(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=e)}get muted(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.muted)??!1}get mediaState(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.mediaState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var e;(e=this._mediaPlayerRef.value)==null||e.play()}pause(){var e;(e=this._mediaPlayerRef.value)==null||e.pause()}reset(e=0,t=!1){var i;(i=this._mediaPlayerRef.value)==null||i.reset(e,t)}_renderStyles(){return this.aspectRatio?typeof this.aspectRatio=="number"?xe`
3910
+ `],ct([se({type:Boolean})],rt.prototype,"debug",2),ct([se({type:Object})],rt.prototype,"config",2),ct([se({type:String,attribute:"language"})],rt.prototype,"propLanguage",2),ct([se({type:Number,attribute:"aspectratio"})],rt.prototype,"propAspectRatio",2),ct([se({type:String})],rt.prototype,"preload",2),ct([se({type:Boolean})],rt.prototype,"autoplay",2),ct([se({type:Boolean})],rt.prototype,"loading",2),ct([se({type:Boolean})],rt.prototype,"disabled",2),ct([se({type:Array})],rt.prototype,"controls",2),ct([se({attribute:!1})],rt.prototype,"dataResolver",2),ct([se({attribute:!1})],rt.prototype,"languageResolver",2),ct([dt()],rt.prototype,"_pageHidden",2),ct([dt()],rt.prototype,"_aspectRatio",2),ct([dt()],rt.prototype,"_processing",2),ct([dt()],rt.prototype,"_waiting",2),ct([dt()],rt.prototype,"_errors",2),ct([dt()],rt.prototype,"_seeking",2),ct([dt()],rt.prototype,"_language",2),ct([dt()],rt.prototype,"_languages",2),ct([dt()],rt.prototype,"_captions",2),ct([dt()],rt.prototype,"_fullscreen",2),rt=ct([kt("vmp-media-player")],rt);var Wx=Object.defineProperty,qx=Object.getOwnPropertyDescriptor,xt=(r,e,t,i)=>{for(var n=i>1?void 0:i?qx(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Wx(e,t,n),n};return at.PlayerEmbed=class extends Dr{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new gp(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","scenesupdate","seeking","seeked","timeupdate","volumechange","processing","waiting","video:loadeddata","video:seeking","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new Op(this),this._trackingController=new dy(this),this._mediaPlayerRef=Qt()}get fetching(){return this._fetcherController.fetching}get waiting(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.waiting}get initialised(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.initialised}get seeking(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.seeking}get paused(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.paused}get captions(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.captions}get fullscreen(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.fullscreen}get duration(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.duration}set currentTime(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=e)}get currentTime(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.currentTime)??0}set playbackRate(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=e)}get playbackRate(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.playbackRate)??1}set volume(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=e)}get volume(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.volume)??1}set muted(e){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=e)}get muted(){var e;return((e=this._mediaPlayerRef.value)==null?void 0:e.muted)??!1}get mediaState(){var e;return(e=this._mediaPlayerRef.value)==null?void 0:e.mediaState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var e;(e=this._mediaPlayerRef.value)==null||e.play()}pause(){var e;(e=this._mediaPlayerRef.value)==null||e.pause()}reset(e=0,t=!1){var i;(i=this._mediaPlayerRef.value)==null||i.reset(e,t)}_renderStyles(){return this.aspectRatio?typeof this.aspectRatio=="number"?xe`
3911
3911
  <style>
3912
3912
  :host {
3913
3913
  aspect-ratio: ${this.aspectRatio};
@@ -3923,7 +3923,7 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3923
3923
  `}willUpdate(e){e.has("vouchId")&&this.vouchId!==e.get("vouchId")&&this.reset(0,!1)}render(){return xe`
3924
3924
  ${this._renderStyles()}
3925
3925
  <vmp-media-player
3926
- ${Qt(this._mediaPlayerRef)}
3926
+ ${_t(this._mediaPlayerRef)}
3927
3927
  ${this.eventController.register()}
3928
3928
  ?autoplay=${this.autoplay}
3929
3929
  ?loading=${this.fetching}
@@ -3932,9 +3932,9 @@ Schedule: ${l.map(d=>Xi(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3932
3932
  language=${cr(this.language)}
3933
3933
  .controls=${this.controls}
3934
3934
  ></vmp-media-player>
3935
- `}},ct.PlayerEmbed.styles=[Bt`
3935
+ `}},at.PlayerEmbed.styles=[Bt`
3936
3936
  :host {
3937
3937
  display: flex;
3938
3938
  }
3939
- `],wt([se({type:Object})],ct.PlayerEmbed.prototype,"data",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"vouchId",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"templateId",2),wt([se({type:Array})],ct.PlayerEmbed.prototype,"questions",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"env",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"apiKey",2),wt([se({type:Boolean})],ct.PlayerEmbed.prototype,"disableTracking",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"trackingSource",2),wt([se({type:Array})],ct.PlayerEmbed.prototype,"controls",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"preload",2),wt([se({type:Boolean})],ct.PlayerEmbed.prototype,"autoplay",2),wt([se({type:Number})],ct.PlayerEmbed.prototype,"aspectRatio",2),wt([se({type:String})],ct.PlayerEmbed.prototype,"language",2),wt([dt()],ct.PlayerEmbed.prototype,"vouch",2),wt([dt()],ct.PlayerEmbed.prototype,"template",2),ct.PlayerEmbed=wt([ip("vouch-embed-player")],ct.PlayerEmbed),Object.defineProperty(ct,Symbol.toStringTag,{value:"Module"}),ct}({});
3939
+ `],xt([se({type:Object})],at.PlayerEmbed.prototype,"data",2),xt([se({type:String})],at.PlayerEmbed.prototype,"vouchId",2),xt([se({type:String})],at.PlayerEmbed.prototype,"templateId",2),xt([se({type:Array})],at.PlayerEmbed.prototype,"questions",2),xt([se({type:String})],at.PlayerEmbed.prototype,"env",2),xt([se({type:String})],at.PlayerEmbed.prototype,"apiKey",2),xt([se({type:Boolean})],at.PlayerEmbed.prototype,"disableTracking",2),xt([se({type:String})],at.PlayerEmbed.prototype,"trackingSource",2),xt([se({type:Array})],at.PlayerEmbed.prototype,"controls",2),xt([se({type:String})],at.PlayerEmbed.prototype,"preload",2),xt([se({type:Boolean})],at.PlayerEmbed.prototype,"autoplay",2),xt([se({type:Number})],at.PlayerEmbed.prototype,"aspectRatio",2),xt([se({type:String})],at.PlayerEmbed.prototype,"language",2),xt([se({type:String})],at.PlayerEmbed.prototype,"senderId",2),xt([dt()],at.PlayerEmbed.prototype,"vouch",2),xt([dt()],at.PlayerEmbed.prototype,"template",2),at.PlayerEmbed=xt([ip("vouch-embed-player")],at.PlayerEmbed),Object.defineProperty(at,Symbol.toStringTag,{value:"Module"}),at}({});
3940
3940
  //# sourceMappingURL=embed.iife.js.map