@vouchfor/embeds 7.0.1 → 7.0.2

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.
@@ -111,10 +111,10 @@ ${e}`,hE=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),dE=Objec
111
111
  * @author Feross Aboukhadijeh <https://feross.org>
112
112
  * @license MIT
113
113
  */(function(i){const e=Xs,t=Za,r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;i.Buffer=a,i.SlowBuffer=B,i.INSPECT_MAX_BYTES=50;const n=2147483647;i.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 A(T)}return c(T,m,E)}a.poolSize=8192;function c(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 c(T,m,E)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(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 l(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 A(T){return l(T),o(T<0?0:v(T)|0)}a.allocUnsafe=function(T){return A(T)},a.allocUnsafeSlow=function(T){return A(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"||tt(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 w(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=i.INSPECT_MAX_BYTES;return m=this.toString("hex",0,E).replace(/(.{2})/g,"$1 ").trim(),this.length>E&&(m+=" ... "),"<Buffer "+m+">"},r&&(a.prototype[r]=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 _(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,tt(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 _(this,m,E,Q,!0)},a.prototype.lastIndexOf=function(m,E,Q){return _(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(tt($))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 w(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=et(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=et(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=et(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=et(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 ie(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 re(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=et(function(m,E=0){return ie(this,m,E,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=et(function(m,E=0){return re(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=et(function(m,E=0){return ie(this,m,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=et(function(m,E=0){return re(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 we(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 we(this,m,E,!0,Q)},a.prototype.writeDoubleBE=function(m,E,Q){return we(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 be={};function Fe(T,m,E){be[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 be.ERR_OUT_OF_RANGE("value",$,T)}Qe(Q,N,J)}function Re(T,m){if(typeof T!="number")throw new be.ERR_INVALID_ARG_TYPE(m,"number",T)}function Ke(T,m,E){throw Math.floor(T)!==T?(Re(T,E),new be.ERR_OUT_OF_RANGE("offset","an integer",T)):m<0?new be.ERR_BUFFER_OUT_OF_BOUNDS:new be.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 tt(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 et(T){return typeof BigInt>"u"?ze:T}function ze(){throw new Error("BigInt not supported")}})(Fu);var Xi=at,wt=ZE,Nu=Fu.Buffer;Ji.__TYPEDARRAY_POOL||(Ji.__TYPEDARRAY_POOL={UINT8:wt([32,0]),UINT16:wt([32,0]),UINT32:wt([32,0]),BIGUINT64:wt([32,0]),INT8:wt([32,0]),INT16:wt([32,0]),INT32:wt([32,0]),BIGINT64:wt([32,0]),FLOAT:wt([32,0]),DOUBLE:wt([32,0]),DATA:wt([32,0]),UINT8C:wt([32,0]),BUFFER:wt([32,0])});var lI=typeof Uint8ClampedArray<"u",cI=typeof BigUint64Array<"u",AI=typeof BigInt64Array<"u",ht=Ji.__TYPEDARRAY_POOL;ht.UINT8C||(ht.UINT8C=wt([32,0])),ht.BIGUINT64||(ht.BIGUINT64=wt([32,0])),ht.BIGINT64||(ht.BIGINT64=wt([32,0])),ht.BUFFER||(ht.BUFFER=wt([32,0]));var zs=ht.DATA,Zs=ht.BUFFER;Pe.free=function(e){if(Nu.isBuffer(e))Zs[Xi.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,r=Xi.log2(t)|0;zs[r].push(e)}};function Ou(i){if(i){var e=i.length||i.byteLength,t=Xi.log2(e);zs[t].push(i)}}function uI(i){Ou(i.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=uI,Pe.freeArrayBuffer=Ou,Pe.freeBuffer=function(e){Zs[Xi.log2(e.length)].push(e)},Pe.malloc=function(e,t){if(t===void 0||t==="arraybuffer")return Pt(e);switch(t){case"uint8":return el(e);case"uint16":return Uu(e);case"uint32":return Gu(e);case"int8":return $u(e);case"int16":return Hu(e);case"int32":return Yu(e);case"float":case"float32":return Vu(e);case"double":case"float64":return Ku(e);case"uint8_clamped":return Wu(e);case"bigint64":return Ju(e);case"biguint64":return qu(e);case"buffer":return Xu(e);case"data":case"dataview":return ju(e);default:return null}return null};function Pt(e){var e=Xi.nextPow2(e),t=Xi.log2(e),r=zs[t];return r.length>0?r.pop():new ArrayBuffer(e)}Pe.mallocArrayBuffer=Pt;function el(i){return new Uint8Array(Pt(i),0,i)}Pe.mallocUint8=el;function Uu(i){return new Uint16Array(Pt(2*i),0,i)}Pe.mallocUint16=Uu;function Gu(i){return new Uint32Array(Pt(4*i),0,i)}Pe.mallocUint32=Gu;function $u(i){return new Int8Array(Pt(i),0,i)}Pe.mallocInt8=$u;function Hu(i){return new Int16Array(Pt(2*i),0,i)}Pe.mallocInt16=Hu;function Yu(i){return new Int32Array(Pt(4*i),0,i)}Pe.mallocInt32=Yu;function Vu(i){return new Float32Array(Pt(4*i),0,i)}Pe.mallocFloat32=Pe.mallocFloat=Vu;function Ku(i){return new Float64Array(Pt(8*i),0,i)}Pe.mallocFloat64=Pe.mallocDouble=Ku;function Wu(i){return lI?new Uint8ClampedArray(Pt(i),0,i):el(i)}Pe.mallocUint8Clamped=Wu;function qu(i){return cI?new BigUint64Array(Pt(8*i),0,i):null}Pe.mallocBigUint64=qu;function Ju(i){return AI?new BigInt64Array(Pt(8*i),0,i):null}Pe.mallocBigInt64=Ju;function ju(i){return new DataView(Pt(i),0,i)}Pe.mallocDataView=ju;function Xu(i){i=Xi.nextPow2(i);var e=Xi.log2(i),t=Zs[e];return t.length>0?t.pop():new Nu(i)}Pe.mallocBuffer=Xu,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,zs[e].length=0,Zs[e].length=0};var eo=LE,tl=Du,Gr=Pe,hI=mI,to=null,il=null,io=null;function dI(i){to=[i.LINEAR,i.NEAREST_MIPMAP_LINEAR,i.LINEAR_MIPMAP_NEAREST,i.LINEAR_MIPMAP_NEAREST],il=[i.NEAREST,i.LINEAR,i.NEAREST_MIPMAP_NEAREST,i.NEAREST_MIPMAP_LINEAR,i.LINEAR_MIPMAP_NEAREST,i.LINEAR_MIPMAP_LINEAR],io=[i.REPEAT,i.CLAMP_TO_EDGE,i.MIRRORED_REPEAT]}function zu(i){return typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||typeof ImageData<"u"&&i instanceof ImageData}var Zu=function(i,e){tl.muls(i,e,255)};function rl(i,e,t){var r=i.gl,n=r.getParameter(r.MAX_TEXTURE_SIZE);if(e<0||e>n||t<0||t>n)throw new Error("gl-texture2d: Invalid texture size");return i._shape=[e,t],i.bind(),r.texImage2D(r.TEXTURE_2D,0,i.format,e,t,0,i.format,i.type,null),i._mipLevels=[0],i}function ro(i,e,t,r,n,s){this.gl=i,this.handle=e,this.format=n,this.type=s,this._shape=[t,r],this._mipLevels=[0],this._magFilter=i.NEAREST,this._minFilter=i.NEAREST,this._wrapS=i.CLAMP_TO_EDGE,this._wrapT=i.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,a=[this._wrapS,this._wrapT];Object.defineProperties(a,[{get:function(){return o._wrapS},set:function(l){return o.wrapS=l}},{get:function(){return o._wrapT},set:function(l){return o.wrapT=l}}]),this._wrapVector=a;var c=[this._shape[0],this._shape[1]];Object.defineProperties(c,[{get:function(){return o._shape[0]},set:function(l){return o.width=l}},{get:function(){return o._shape[1]},set:function(l){return o.height=l}}]),this._shapeVector=c}var Nn=ro.prototype;Object.defineProperties(Nn,{minFilter:{get:function(){return this._minFilter},set:function(i){this.bind();var e=this.gl;if(this.type===e.FLOAT&&to.indexOf(i)>=0&&(e.getExtension("OES_texture_float_linear")||(i=e.NEAREST)),il.indexOf(i)<0)throw new Error("gl-texture2d: Unknown filter mode "+i);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,i),this._minFilter=i}},magFilter:{get:function(){return this._magFilter},set:function(i){this.bind();var e=this.gl;if(this.type===e.FLOAT&&to.indexOf(i)>=0&&(e.getExtension("OES_texture_float_linear")||(i=e.NEAREST)),il.indexOf(i)<0)throw new Error("gl-texture2d: Unknown filter mode "+i);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,i),this._magFilter=i}},mipSamples:{get:function(){return this._anisoSamples},set:function(i){var e=this._anisoSamples;if(this._anisoSamples=Math.max(i,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(i){if(this.bind(),io.indexOf(i)<0)throw new Error("gl-texture2d: Unknown wrap mode "+i);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,i),this._wrapS=i}},wrapT:{get:function(){return this._wrapT},set:function(i){if(this.bind(),io.indexOf(i)<0)throw new Error("gl-texture2d: Unknown wrap mode "+i);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,i),this._wrapT=i}},wrap:{get:function(){return this._wrapVector},set:function(i){if(Array.isArray(i)||(i=[i,i]),i.length!==2)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(io.indexOf(i[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+i);this._wrapS=i[0],this._wrapT=i[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),i}},shape:{get:function(){return this._shapeVector},set:function(i){if(!Array.isArray(i))i=[i|0,i|0];else if(i.length!==2)throw new Error("gl-texture2d: Invalid texture shape");return rl(this,i[0]|0,i[1]|0),[i[0]|0,i[1]|0]}},width:{get:function(){return this._shape[0]},set:function(i){return i=i|0,rl(this,i,this._shape[1]),i}},height:{get:function(){return this._shape[1]},set:function(i){return i=i|0,rl(this,this._shape[0],i),i}}}),Nn.bind=function(i){var e=this.gl;return i!==void 0&&e.activeTexture(e.TEXTURE0+(i|0)),e.bindTexture(e.TEXTURE_2D,this.handle),i!==void 0?i|0:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},Nn.dispose=function(){this.gl.deleteTexture(this.handle)},Nn.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var i=Math.min(this._shape[0],this._shape[1]),e=0;i>0;++e,i>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},Nn.setPixels=function(i,e,t,r){var n=this.gl;this.bind(),Array.isArray(e)?(r=t,t=e[1]|0,e=e[0]|0):(e=e||0,t=t||0),r=r||0;var s=zu(i)?i:i.raw;if(s){var o=this._mipLevels.indexOf(r)<0;o?(n.texImage2D(n.TEXTURE_2D,0,this.format,this.format,this.type,s),this._mipLevels.push(r)):n.texSubImage2D(n.TEXTURE_2D,r,e,t,this.format,this.type,s)}else if(i.shape&&i.stride&&i.data){if(i.shape.length<2||e+i.shape[1]>this._shape[1]>>>r||t+i.shape[0]>this._shape[0]>>>r||e<0||t<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");fI(n,e,t,r,this.format,this.type,this._mipLevels,i)}else throw new Error("gl-texture2d: Unsupported data type")};function eh(i,e){return i.length===3?e[2]===1&&e[1]===i[0]*i[2]&&e[0]===i[2]:e[0]===1&&e[1]===i[0]}function fI(i,e,t,r,n,s,o,a){var c=a.dtype,l=a.shape.slice();if(l.length<2||l.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var u=0,A=0,h=eh(l,a.stride.slice());if(c==="float32"?u=i.FLOAT:c==="float64"?(u=i.FLOAT,h=!1,c="float32"):c==="uint8"?u=i.UNSIGNED_BYTE:(u=i.UNSIGNED_BYTE,h=!1,c="uint8"),l.length===2)A=i.LUMINANCE,l=[l[0],l[1],1],a=eo(a.data,l,[a.stride[0],a.stride[1],1],a.offset);else if(l.length===3){if(l[2]===1)A=i.ALPHA;else if(l[2]===2)A=i.LUMINANCE_ALPHA;else if(l[2]===3)A=i.RGB;else if(l[2]===4)A=i.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");l[2]}else throw new Error("gl-texture2d: Invalid shape for texture");if((A===i.LUMINANCE||A===i.ALPHA)&&(n===i.LUMINANCE||n===i.ALPHA)&&(A=n),A!==n)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=a.size,f=o.indexOf(r)<0;if(f&&o.push(r),u===s&&h)a.offset===0&&a.data.length===d?f?i.texImage2D(i.TEXTURE_2D,r,n,l[0],l[1],0,n,s,a.data):i.texSubImage2D(i.TEXTURE_2D,r,e,t,l[0],l[1],n,s,a.data):f?i.texImage2D(i.TEXTURE_2D,r,n,l[0],l[1],0,n,s,a.data.subarray(a.offset,a.offset+d)):i.texSubImage2D(i.TEXTURE_2D,r,e,t,l[0],l[1],n,s,a.data.subarray(a.offset,a.offset+d));else{var g;s===i.FLOAT?g=Gr.mallocFloat32(d):g=Gr.mallocUint8(d);var p=eo(g,l,[l[2],l[2]*l[0],1]);u===i.FLOAT&&s===i.UNSIGNED_BYTE?Zu(p,a):tl.assign(p,a),f?i.texImage2D(i.TEXTURE_2D,r,n,l[0],l[1],0,n,s,g.subarray(0,d)):i.texSubImage2D(i.TEXTURE_2D,r,e,t,l[0],l[1],n,s,g.subarray(0,d)),s===i.FLOAT?Gr.freeFloat32(g):Gr.freeUint8(g)}}function nl(i){var e=i.createTexture();return i.bindTexture(i.TEXTURE_2D,e),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e}function th(i,e,t,r,n){var s=i.getParameter(i.MAX_TEXTURE_SIZE);if(e<0||e>s||t<0||t>s)throw new Error("gl-texture2d: Invalid texture shape");if(n===i.FLOAT&&!i.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=nl(i);return i.texImage2D(i.TEXTURE_2D,0,r,e,t,0,r,n,null),new ro(i,o,e,t,r,n)}function gI(i,e,t,r,n,s){var o=nl(i);return i.texImage2D(i.TEXTURE_2D,0,n,n,s,e),new ro(i,o,t,r,n,s)}function pI(i,e){var t=e.dtype,r=e.shape.slice(),n=i.getParameter(i.MAX_TEXTURE_SIZE);if(r[0]<0||r[0]>n||r[1]<0||r[1]>n)throw new Error("gl-texture2d: Invalid texture size");var s=eh(r,e.stride.slice()),o=0;t==="float32"?o=i.FLOAT:t==="float64"?(o=i.FLOAT,s=!1,t="float32"):t==="uint8"?o=i.UNSIGNED_BYTE:(o=i.UNSIGNED_BYTE,s=!1,t="uint8");var a=0;if(r.length===2)a=i.LUMINANCE,r=[r[0],r[1],1],e=eo(e.data,r,[e.stride[0],e.stride[1],1],e.offset);else if(r.length===3)if(r[2]===1)a=i.ALPHA;else if(r[2]===2)a=i.LUMINANCE_ALPHA;else if(r[2]===3)a=i.RGB;else if(r[2]===4)a=i.RGBA;else throw new Error("gl-texture2d: Invalid shape for pixel coords");else throw new Error("gl-texture2d: Invalid shape for texture");o===i.FLOAT&&!i.getExtension("OES_texture_float")&&(o=i.UNSIGNED_BYTE,s=!1);var c,l,u=e.size;if(s)e.offset===0&&e.data.length===u?c=e.data:c=e.data.subarray(e.offset,e.offset+u);else{var A=[r[2],r[2]*r[0],1];l=Gr.malloc(u,t);var h=eo(l,r,A,0);(t==="float32"||t==="float64")&&o===i.UNSIGNED_BYTE?Zu(h,e):tl.assign(h,e),c=l.subarray(0,u)}var d=nl(i);return i.texImage2D(i.TEXTURE_2D,0,a,r[0],r[1],0,a,o,c),s||Gr.free(l),new ro(i,d,r[0],r[1],a,o)}function mI(i){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(to||dI(i),typeof arguments[1]=="number")return th(i,arguments[1],arguments[2],arguments[3]||i.RGBA,arguments[4]||i.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return th(i,arguments[1][0]|0,arguments[1][1]|0,arguments[2]||i.RGBA,arguments[3]||i.UNSIGNED_BYTE);if(typeof arguments[1]=="object"){var e=arguments[1],t=zu(e)?e:e.raw;if(t)return gI(i,t,e.width|0,e.height|0,arguments[2]||i.RGBA,arguments[3]||i.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return pI(i,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}const no=Ya(hI);var ih={},rh=EI;function EI(i,e){for(var t={},r=0;r<i.length;++r)for(var n=i[r].name,s=n.split("."),o=t,a=0;a<s.length;++a){var c=s[a].split("[");if(c.length>1){c[0]in o||(o[c[0]]=[]),o=o[c[0]];for(var l=1;l<c.length;++l){var u=parseInt(c[l]);l<c.length-1||a<s.length-1?(u in o||(l<c.length-1?o[u]=[]:o[u]={}),o=o[u]):e?o[u]=r:o[u]=i[r].type}}else a<s.length-1?(c[0]in o||(o[c[0]]={}),o=o[c[0]]):e?o[c[0]]=r:o[c[0]]=i[r].type}return t}function On(i,e,t){this.shortMessage=e||"",this.longMessage=t||"",this.rawError=i||"",this.message="gl-shader: "+(e||i||"")+(t?`
114
- `+t:""),this.stack=new Error().stack}On.prototype=new Error,On.prototype.name="GLError",On.prototype.constructor=On;var so=On,II=rh,Cr=so,vI=yI;function nh(i){return function(){return i}}function sl(i,e){for(var t=new Array(i),r=0;r<i;++r)t[r]=e;return t}function yI(i,e,t,r){function n(A){return function(h,d,f){return h.getUniform(d.program,f[A])}}function s(A){return function(d){for(var f=o("",A),g=0;g<f.length;++g){var p=f[g],v=p[0],B=p[1];if(r[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("["),_=y.slice(0,x),D=y.slice(x+1,y.length-1);C=_?d[_][D]:d[D]}else C=d[y]}var F=t[B].type,O;switch(F){case"bool":case"int":case"sampler2D":case"samplerCube":i.uniform1i(r[B],C);break;case"float":i.uniform1f(r[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 Cr("","Invalid data type");switch(F.charAt(0)){case"b":case"i":i["uniform"+O+"iv"](r[B],C);break;case"v":i["uniform"+O+"fv"](r[B],C);break;default:throw new Cr("","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 Cr("","Invalid uniform dimension type for matrix "+name+": "+F);i["uniformMatrix"+O+"fv"](r[B],!1,C);break}else throw new Cr("","Unknown uniform data type for "+name+": "+F)}}}}}function o(A,h){if(typeof h!="object")return[[A,h]];var d=[];for(var f in h){var g=h[f],p=A;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(A){switch(A){case"bool":return!1;case"int":case"sampler2D":case"samplerCube":return 0;case"float":return 0;default:var h=A.indexOf("vec");if(0<=h&&h<=1&&A.length===4+h){var d=A.charCodeAt(A.length-1)-48;if(d<2||d>4)throw new Cr("","Invalid data type");return A.charAt(0)==="b"?sl(d,!1):sl(d,0)}else if(A.indexOf("mat")===0&&A.length===4){var d=A.charCodeAt(A.length-1)-48;if(d<2||d>4)throw new Cr("","Invalid uniform dimension type for matrix "+name+": "+A);return sl(d*d,0)}else throw new Cr("","Unknown uniform data type for "+name+": "+A)}}function c(A,h,d){if(typeof d=="object"){var f=l(d);Object.defineProperty(A,h,{get:nh(f),set:s(d),enumerable:!0,configurable:!1})}else r[d]?Object.defineProperty(A,h,{get:n(d),set:s(d),enumerable:!0,configurable:!1}):A[h]=a(t[d].type)}function l(A){var h;if(Array.isArray(A)){h=new Array(A.length);for(var d=0;d<A.length;++d)c(h,d,A[d])}else{h={};for(var f in A)c(h,f,A[f])}return h}var u=II(t,!0);return{get:nh(l(u)),set:s(u),enumerable:!0,configurable:!0}}var CI=bI,ol=so;function sh(i,e,t,r,n,s){this._gl=i,this._wrapper=e,this._index=t,this._locations=r,this._dimension=n,this._constFunc=s}var al=sh.prototype;al.pointer=function(e,t,r,n){var s=this,o=s._gl,a=s._locations[s._index];o.vertexAttribPointer(a,s._dimension,e||o.FLOAT,!!t,r||0,n||0),o.enableVertexAttribArray(a)},al.set=function(i,e,t,r){return this._constFunc(this._locations[this._index],i,e,t,r)},Object.defineProperty(al,"location",{get:function(){return this._locations[this._index]},set:function(i){return i!==this._locations[this._index]&&(this._locations[this._index]=i|0,this._wrapper.program=null),i|0}});var BI=[function(i,e,t){return t.length===void 0?i.vertexAttrib1f(e,t):i.vertexAttrib1fv(e,t)},function(i,e,t,r){return t.length===void 0?i.vertexAttrib2f(e,t,r):i.vertexAttrib2fv(e,t)},function(i,e,t,r,n){return t.length===void 0?i.vertexAttrib3f(e,t,r,n):i.vertexAttrib3fv(e,t)},function(i,e,t,r,n,s){return t.length===void 0?i.vertexAttrib4f(e,t,r,n,s):i.vertexAttrib4fv(e,t)}];function ll(i,e,t,r,n,s,o){var a=BI[n],c=new sh(i,e,t,r,n,a);Object.defineProperty(s,o,{set:function(l){return i.disableVertexAttribArray(r[t]),a(i,r[t],l),l},get:function(){return c},enumerable:!0})}function TI(i,e,t,r,n,s,o){for(var a=new Array(n),c=new Array(n),l=0;l<n;++l)ll(i,e,t[l],r,n,a,l),c[l]=a[l];Object.defineProperty(a,"location",{set:function(h){if(Array.isArray(h))for(var d=0;d<n;++d)c[d].location=h[d];else for(var d=0;d<n;++d)c[d].location=h+d;return h},get:function(){for(var h=new Array(n),d=0;d<n;++d)h[d]=r[t[d]];return h},enumerable:!0}),a.pointer=function(h,d,f,g){h=h||i.FLOAT,d=!!d,f=f||n*n,g=g||0;for(var p=0;p<n;++p){var v=r[t[p]];i.vertexAttribPointer(v,n,h,d,f,g+p*n),i.enableVertexAttribArray(v)}};var u=new Array(n),A=i["vertexAttrib"+n+"fv"];Object.defineProperty(s,o,{set:function(h){for(var d=0;d<n;++d){var f=r[t[d]];if(i.disableVertexAttribArray(f),Array.isArray(h[0]))A.call(i,f,h[d]);else{for(var g=0;g<n;++g)u[g]=h[n*d+g];A.call(i,f,u)}}return h},get:function(){return a},enumerable:!0})}function bI(i,e,t,r){for(var n={},s=0,o=t.length;s<o;++s){var a=t[s],c=a.name,l=a.type,u=a.locations;switch(l){case"bool":case"int":case"float":ll(i,e,u[0],r,1,n,c);break;default:if(l.indexOf("vec")>=0){var A=l.charCodeAt(l.length-1)-48;if(A<2||A>4)throw new ol("","Invalid data type for attribute "+c+": "+l);ll(i,e,u[0],r,A,n,c)}else if(l.indexOf("mat")>=0){var A=l.charCodeAt(l.length-1)-48;if(A<2||A>4)throw new ol("","Invalid data type for attribute "+c+": "+l);TI(i,e,u,r,A,n,c)}else throw new ol("","Unknown data type for attribute "+c+": "+l);break}}return n}var cl={},oh={};(function(i){(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 r(a,c){return t.apply(null,[a].concat(c||[]))}function n(a,c){var l=1,u=a.length,A,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(A=c[l],f=0;f<g.keys.length;f++){if(A==null)throw new Error(t('[sprintf] Cannot access property "%s" of undefined value "%s"',g.keys[f],g.keys[f-1]));A=A[g.keys[f]]}else g.param_no?A=c[g.param_no]:A=c[l++];if(e.not_type.test(g.type)&&e.not_primitive.test(g.type)&&A instanceof Function&&(A=A()),e.numeric_arg.test(g.type)&&typeof A!="number"&&isNaN(A))throw new TypeError(t("[sprintf] expecting number but found %T",A));switch(e.number.test(g.type)&&(C=A>=0),g.type){case"b":A=parseInt(A,10).toString(2);break;case"c":A=String.fromCharCode(parseInt(A,10));break;case"d":case"i":A=parseInt(A,10);break;case"j":A=JSON.stringify(A,null,g.width?parseInt(g.width):0);break;case"e":A=g.precision?parseFloat(A).toExponential(g.precision):parseFloat(A).toExponential();break;case"f":A=g.precision?parseFloat(A).toFixed(g.precision):parseFloat(A);break;case"g":A=g.precision?String(Number(A.toPrecision(g.precision))):parseFloat(A);break;case"o":A=(parseInt(A,10)>>>0).toString(8);break;case"s":A=String(A),A=g.precision?A.substring(0,g.precision):A;break;case"t":A=String(!!A),A=g.precision?A.substring(0,g.precision):A;break;case"T":A=Object.prototype.toString.call(A).slice(8,-1).toLowerCase(),A=g.precision?A.substring(0,g.precision):A;break;case"u":A=parseInt(A,10)>>>0;break;case"v":A=A.valueOf(),A=g.precision?A.substring(0,g.precision):A;break;case"x":A=(parseInt(A,10)>>>0).toString(16);break;case"X":A=(parseInt(A,10)>>>0).toString(16).toUpperCase();break}e.json.test(g.type)?h+=A:(e.number.test(g.type)&&(!C||g.sign)?(y=C?"+":"-",A=A.toString().replace(e.sign,"")):y="",v=g.pad_char?g.pad_char==="0"?"0":g.pad_char.charAt(1):" ",B=g.width-(y+A).length,p=g.width&&B>0?v.repeat(B):"",h+=g.align?y+A+p:v==="0"?y+p+A:p+y+A)}return h}var s=Object.create(null);function o(a){if(s[a])return s[a];for(var c=a,l,u=[],A=0;c;){if((l=e.text.exec(c))!==null)u.push(l[0]);else if((l=e.modulo.exec(c))!==null)u.push("%");else if((l=e.placeholder.exec(c))!==null){if(l[2]){A|=1;var h=[],d=l[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");l[2]=h}else A|=2;if(A===3)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");u.push({placeholder:l[0],param_no:l[1],keys:l[2],sign:l[3],pad_char:l[4],align:l[5],width:l[6],precision:l[7],type:l[8]})}else throw new SyntaxError("[sprintf] unexpected placeholder");c=c.substring(l[0].length)}return s[a]=u}i.sprintf=t,i.vsprintf=r,typeof window<"u"&&(window.sprintf=t,window.vsprintf=r)})()})(oh);var SI={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"},xI=SI,QI=function(e){return xI[e]},ah=["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"],wI=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],lh=["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"],_I=ah,RI=_I.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"]),Al=lh;Al=Al.slice().filter(function(i){return!/^(gl\_|texture)/.test(i)});var DI=Al.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"]),LI=HI,kI=ah,ch=wI,MI=lh,FI=RI,PI=DI,ni=999,Ah=9999,ul=0,hl=1,uh=2,hh=3,dh=4,Un=5,NI=6,OI=7,UI=8,fh=9,GI=10,gh=11,$I=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];function HI(i){var e=0,t=0,r=ni,n,s,o=[],a=[],c=1,l=0,u=0,A=!1,h=!1,d="",f;i=i||{};var g=MI,p=kI;i.version==="300 es"&&(g=PI,p=FI);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:$I[r],data:q,position:u,line:c,column:l})}function y(q){e=0,q.toString&&(q=q.toString()),d+=q.replace(/\r\n/g,`
115
- `),f=d.length;for(var R;n=d[e],e<f;){switch(R=e,r){case ul:e=M();break;case hl:e=O();break;case uh:e=F();break;case hh:e=j();break;case dh:e=oe();break;case gh:e=le();break;case Un:e=L();break;case Ah:e=U();break;case fh:e=D();break;case ni:e=_();break}if(R!==e)switch(d[R]){case`
116
- `:l=0,++c;break;default:++l;break}}return t+=e,d=d.slice(e),a}function x(q){return o.length&&C(o.join("")),r=GI,C("(eof)"),a}function _(){return o=o.length?[]:o,s==="/"&&n==="*"?(u=t+e-1,r=ul,s=n,e+1):s==="/"&&n==="/"?(u=t+e-1,r=hl,s=n,e+1):n==="#"?(r=uh,u=t+e,e):/\s/.test(n)?(r=fh,u=t+e,e):(A=/\d/.test(n),h=/[^\w_]/.test(n),u=t+e,r=A?dh:h?hh:Ah,e)}function D(){return/[^\s]/g.test(n)?(C(o.join("")),r=ni,e):(o.push(n),s=n,e+1)}function F(){return(n==="\r"||n===`
117
- `)&&s!=="\\"?(C(o.join("")),r=ni,e):(o.push(n),s=n,e+1)}function O(){return F()}function M(){return n==="/"&&s==="*"?(o.push(n),C(o.join("")),r=ni,e+1):(o.push(n),s=n,e+1)}function j(){if(s==="."&&/\d/.test(n))return r=Un,e;if(s==="/"&&n==="*")return r=ul,e;if(s==="/"&&n==="/")return r=hl,e;if(n==="."&&o.length){for(;X(o););return r=Un,e}if(n===";"||n===")"||n==="("){if(o.length)for(;X(o););return C(n),r=ni,e+1}var q=o.length===2&&n!=="=";if(/[\w_\d\s]/.test(n)||q){for(;X(o););return r=ni,e}return o.push(n),s=n,e+1}function X(q){var R=0,w,k;do{if(w=ch.indexOf(q.slice(0,q.length+R).join("")),k=ch[w],w===-1){if(R--+q.length>0)continue;k=q.slice(0,1).join("")}return C(k),u+=k.length,o=o.slice(k.length),o.length}while(!0)}function le(){return/[^a-fA-F0-9]/.test(n)?(C(o.join("")),r=ni,e):(o.push(n),s=n,e+1)}function oe(){return n==="."||/[eE]/.test(n)?(o.push(n),r=Un,s=n,e+1):n==="x"&&o.length===1&&o[0]==="0"?(r=gh,o.push(n),s=n,e+1):/[^\d]/.test(n)?(C(o.join("")),r=ni,e):(o.push(n),s=n,e+1)}function L(){return n==="f"&&(o.push(n),s=n,e+=1),/[eE]/.test(n)||(n==="-"||n==="+")&&/[eE]/.test(s)?(o.push(n),s=n,e+1):/[^\d]/.test(n)?(C(o.join("")),r=ni,e):(o.push(n),s=n,e+1)}function U(){if(/[^\d\w_]/.test(n)){var q=o.join("");return B[q]?r=UI:v[q]?r=OI:r=NI,C(o.join("")),r=ni,e}return o.push(n),s=n,e+1}}var YI=LI,VI=KI;function KI(i,e){var t=YI(e),r=[];return r=r.concat(t(i)),r=r.concat(t(null)),r}var WI=function(e){return atob(e)},qI=VI,JI=WI,jI=XI;function XI(i){for(var e=Array.isArray(i)?i:qI(i),t=0;t<e.length;t++){var r=e[t];if(r.type==="preprocessor"){var n=r.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/);if(n&&n[2]){var s=n[1],o=n[2];return(s?JI(o):o).trim()}}}}/*!
114
+ `+t:""),this.stack=new Error().stack}On.prototype=new Error,On.prototype.name="GLError",On.prototype.constructor=On;var so=On,II=rh,Cr=so,vI=yI;function nh(i){return function(){return i}}function sl(i,e){for(var t=new Array(i),r=0;r<i;++r)t[r]=e;return t}function yI(i,e,t,r){function n(A){return function(h,d,f){return h.getUniform(d.program,f[A])}}function s(A){return function(d){for(var f=o("",A),g=0;g<f.length;++g){var p=f[g],v=p[0],B=p[1];if(r[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("["),_=y.slice(0,x),D=y.slice(x+1,y.length-1);C=_?d[_][D]:d[D]}else C=d[y]}var F=t[B].type,O;switch(F){case"bool":case"int":case"sampler2D":case"samplerCube":i.uniform1i(r[B],C);break;case"float":i.uniform1f(r[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 Cr("","Invalid data type");switch(F.charAt(0)){case"b":case"i":i["uniform"+O+"iv"](r[B],C);break;case"v":i["uniform"+O+"fv"](r[B],C);break;default:throw new Cr("","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 Cr("","Invalid uniform dimension type for matrix "+name+": "+F);i["uniformMatrix"+O+"fv"](r[B],!1,C);break}else throw new Cr("","Unknown uniform data type for "+name+": "+F)}}}}}function o(A,h){if(typeof h!="object")return[[A,h]];var d=[];for(var f in h){var g=h[f],p=A;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(A){switch(A){case"bool":return!1;case"int":case"sampler2D":case"samplerCube":return 0;case"float":return 0;default:var h=A.indexOf("vec");if(0<=h&&h<=1&&A.length===4+h){var d=A.charCodeAt(A.length-1)-48;if(d<2||d>4)throw new Cr("","Invalid data type");return A.charAt(0)==="b"?sl(d,!1):sl(d,0)}else if(A.indexOf("mat")===0&&A.length===4){var d=A.charCodeAt(A.length-1)-48;if(d<2||d>4)throw new Cr("","Invalid uniform dimension type for matrix "+name+": "+A);return sl(d*d,0)}else throw new Cr("","Unknown uniform data type for "+name+": "+A)}}function c(A,h,d){if(typeof d=="object"){var f=l(d);Object.defineProperty(A,h,{get:nh(f),set:s(d),enumerable:!0,configurable:!1})}else r[d]?Object.defineProperty(A,h,{get:n(d),set:s(d),enumerable:!0,configurable:!1}):A[h]=a(t[d].type)}function l(A){var h;if(Array.isArray(A)){h=new Array(A.length);for(var d=0;d<A.length;++d)c(h,d,A[d])}else{h={};for(var f in A)c(h,f,A[f])}return h}var u=II(t,!0);return{get:nh(l(u)),set:s(u),enumerable:!0,configurable:!0}}var CI=bI,ol=so;function sh(i,e,t,r,n,s){this._gl=i,this._wrapper=e,this._index=t,this._locations=r,this._dimension=n,this._constFunc=s}var al=sh.prototype;al.pointer=function(e,t,r,n){var s=this,o=s._gl,a=s._locations[s._index];o.vertexAttribPointer(a,s._dimension,e||o.FLOAT,!!t,r||0,n||0),o.enableVertexAttribArray(a)},al.set=function(i,e,t,r){return this._constFunc(this._locations[this._index],i,e,t,r)},Object.defineProperty(al,"location",{get:function(){return this._locations[this._index]},set:function(i){return i!==this._locations[this._index]&&(this._locations[this._index]=i|0,this._wrapper.program=null),i|0}});var BI=[function(i,e,t){return t.length===void 0?i.vertexAttrib1f(e,t):i.vertexAttrib1fv(e,t)},function(i,e,t,r){return t.length===void 0?i.vertexAttrib2f(e,t,r):i.vertexAttrib2fv(e,t)},function(i,e,t,r,n){return t.length===void 0?i.vertexAttrib3f(e,t,r,n):i.vertexAttrib3fv(e,t)},function(i,e,t,r,n,s){return t.length===void 0?i.vertexAttrib4f(e,t,r,n,s):i.vertexAttrib4fv(e,t)}];function ll(i,e,t,r,n,s,o){var a=BI[n],c=new sh(i,e,t,r,n,a);Object.defineProperty(s,o,{set:function(l){return i.disableVertexAttribArray(r[t]),a(i,r[t],l),l},get:function(){return c},enumerable:!0})}function TI(i,e,t,r,n,s,o){for(var a=new Array(n),c=new Array(n),l=0;l<n;++l)ll(i,e,t[l],r,n,a,l),c[l]=a[l];Object.defineProperty(a,"location",{set:function(h){if(Array.isArray(h))for(var d=0;d<n;++d)c[d].location=h[d];else for(var d=0;d<n;++d)c[d].location=h+d;return h},get:function(){for(var h=new Array(n),d=0;d<n;++d)h[d]=r[t[d]];return h},enumerable:!0}),a.pointer=function(h,d,f,g){h=h||i.FLOAT,d=!!d,f=f||n*n,g=g||0;for(var p=0;p<n;++p){var v=r[t[p]];i.vertexAttribPointer(v,n,h,d,f,g+p*n),i.enableVertexAttribArray(v)}};var u=new Array(n),A=i["vertexAttrib"+n+"fv"];Object.defineProperty(s,o,{set:function(h){for(var d=0;d<n;++d){var f=r[t[d]];if(i.disableVertexAttribArray(f),Array.isArray(h[0]))A.call(i,f,h[d]);else{for(var g=0;g<n;++g)u[g]=h[n*d+g];A.call(i,f,u)}}return h},get:function(){return a},enumerable:!0})}function bI(i,e,t,r){for(var n={},s=0,o=t.length;s<o;++s){var a=t[s],c=a.name,l=a.type,u=a.locations;switch(l){case"bool":case"int":case"float":ll(i,e,u[0],r,1,n,c);break;default:if(l.indexOf("vec")>=0){var A=l.charCodeAt(l.length-1)-48;if(A<2||A>4)throw new ol("","Invalid data type for attribute "+c+": "+l);ll(i,e,u[0],r,A,n,c)}else if(l.indexOf("mat")>=0){var A=l.charCodeAt(l.length-1)-48;if(A<2||A>4)throw new ol("","Invalid data type for attribute "+c+": "+l);TI(i,e,u,r,A,n,c)}else throw new ol("","Unknown data type for attribute "+c+": "+l);break}}return n}var cl={},oh={};(function(i){(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 r(a,c){return t.apply(null,[a].concat(c||[]))}function n(a,c){var l=1,u=a.length,A,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(A=c[l],f=0;f<g.keys.length;f++){if(A==null)throw new Error(t('[sprintf] Cannot access property "%s" of undefined value "%s"',g.keys[f],g.keys[f-1]));A=A[g.keys[f]]}else g.param_no?A=c[g.param_no]:A=c[l++];if(e.not_type.test(g.type)&&e.not_primitive.test(g.type)&&A instanceof Function&&(A=A()),e.numeric_arg.test(g.type)&&typeof A!="number"&&isNaN(A))throw new TypeError(t("[sprintf] expecting number but found %T",A));switch(e.number.test(g.type)&&(C=A>=0),g.type){case"b":A=parseInt(A,10).toString(2);break;case"c":A=String.fromCharCode(parseInt(A,10));break;case"d":case"i":A=parseInt(A,10);break;case"j":A=JSON.stringify(A,null,g.width?parseInt(g.width):0);break;case"e":A=g.precision?parseFloat(A).toExponential(g.precision):parseFloat(A).toExponential();break;case"f":A=g.precision?parseFloat(A).toFixed(g.precision):parseFloat(A);break;case"g":A=g.precision?String(Number(A.toPrecision(g.precision))):parseFloat(A);break;case"o":A=(parseInt(A,10)>>>0).toString(8);break;case"s":A=String(A),A=g.precision?A.substring(0,g.precision):A;break;case"t":A=String(!!A),A=g.precision?A.substring(0,g.precision):A;break;case"T":A=Object.prototype.toString.call(A).slice(8,-1).toLowerCase(),A=g.precision?A.substring(0,g.precision):A;break;case"u":A=parseInt(A,10)>>>0;break;case"v":A=A.valueOf(),A=g.precision?A.substring(0,g.precision):A;break;case"x":A=(parseInt(A,10)>>>0).toString(16);break;case"X":A=(parseInt(A,10)>>>0).toString(16).toUpperCase();break}e.json.test(g.type)?h+=A:(e.number.test(g.type)&&(!C||g.sign)?(y=C?"+":"-",A=A.toString().replace(e.sign,"")):y="",v=g.pad_char?g.pad_char==="0"?"0":g.pad_char.charAt(1):" ",B=g.width-(y+A).length,p=g.width&&B>0?v.repeat(B):"",h+=g.align?y+A+p:v==="0"?y+p+A:p+y+A)}return h}var s=Object.create(null);function o(a){if(s[a])return s[a];for(var c=a,l,u=[],A=0;c;){if((l=e.text.exec(c))!==null)u.push(l[0]);else if((l=e.modulo.exec(c))!==null)u.push("%");else if((l=e.placeholder.exec(c))!==null){if(l[2]){A|=1;var h=[],d=l[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");l[2]=h}else A|=2;if(A===3)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");u.push({placeholder:l[0],param_no:l[1],keys:l[2],sign:l[3],pad_char:l[4],align:l[5],width:l[6],precision:l[7],type:l[8]})}else throw new SyntaxError("[sprintf] unexpected placeholder");c=c.substring(l[0].length)}return s[a]=u}i.sprintf=t,i.vsprintf=r,typeof window<"u"&&(window.sprintf=t,window.vsprintf=r)})()})(oh);var SI={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"},xI=SI,QI=function(e){return xI[e]},ah=["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"],wI=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],lh=["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"],_I=ah,RI=_I.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"]),Al=lh;Al=Al.slice().filter(function(i){return!/^(gl\_|texture)/.test(i)});var DI=Al.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"]),LI=HI,kI=ah,ch=wI,MI=lh,FI=RI,PI=DI,si=999,Ah=9999,ul=0,hl=1,uh=2,hh=3,dh=4,Un=5,NI=6,OI=7,UI=8,fh=9,GI=10,gh=11,$I=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];function HI(i){var e=0,t=0,r=si,n,s,o=[],a=[],c=1,l=0,u=0,A=!1,h=!1,d="",f;i=i||{};var g=MI,p=kI;i.version==="300 es"&&(g=PI,p=FI);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:$I[r],data:q,position:u,line:c,column:l})}function y(q){e=0,q.toString&&(q=q.toString()),d+=q.replace(/\r\n/g,`
115
+ `),f=d.length;for(var R;n=d[e],e<f;){switch(R=e,r){case ul:e=M();break;case hl:e=O();break;case uh:e=F();break;case hh:e=j();break;case dh:e=oe();break;case gh:e=le();break;case Un:e=L();break;case Ah:e=U();break;case fh:e=D();break;case si:e=_();break}if(R!==e)switch(d[R]){case`
116
+ `:l=0,++c;break;default:++l;break}}return t+=e,d=d.slice(e),a}function x(q){return o.length&&C(o.join("")),r=GI,C("(eof)"),a}function _(){return o=o.length?[]:o,s==="/"&&n==="*"?(u=t+e-1,r=ul,s=n,e+1):s==="/"&&n==="/"?(u=t+e-1,r=hl,s=n,e+1):n==="#"?(r=uh,u=t+e,e):/\s/.test(n)?(r=fh,u=t+e,e):(A=/\d/.test(n),h=/[^\w_]/.test(n),u=t+e,r=A?dh:h?hh:Ah,e)}function D(){return/[^\s]/g.test(n)?(C(o.join("")),r=si,e):(o.push(n),s=n,e+1)}function F(){return(n==="\r"||n===`
117
+ `)&&s!=="\\"?(C(o.join("")),r=si,e):(o.push(n),s=n,e+1)}function O(){return F()}function M(){return n==="/"&&s==="*"?(o.push(n),C(o.join("")),r=si,e+1):(o.push(n),s=n,e+1)}function j(){if(s==="."&&/\d/.test(n))return r=Un,e;if(s==="/"&&n==="*")return r=ul,e;if(s==="/"&&n==="/")return r=hl,e;if(n==="."&&o.length){for(;X(o););return r=Un,e}if(n===";"||n===")"||n==="("){if(o.length)for(;X(o););return C(n),r=si,e+1}var q=o.length===2&&n!=="=";if(/[\w_\d\s]/.test(n)||q){for(;X(o););return r=si,e}return o.push(n),s=n,e+1}function X(q){var R=0,w,k;do{if(w=ch.indexOf(q.slice(0,q.length+R).join("")),k=ch[w],w===-1){if(R--+q.length>0)continue;k=q.slice(0,1).join("")}return C(k),u+=k.length,o=o.slice(k.length),o.length}while(!0)}function le(){return/[^a-fA-F0-9]/.test(n)?(C(o.join("")),r=si,e):(o.push(n),s=n,e+1)}function oe(){return n==="."||/[eE]/.test(n)?(o.push(n),r=Un,s=n,e+1):n==="x"&&o.length===1&&o[0]==="0"?(r=gh,o.push(n),s=n,e+1):/[^\d]/.test(n)?(C(o.join("")),r=si,e):(o.push(n),s=n,e+1)}function L(){return n==="f"&&(o.push(n),s=n,e+=1),/[eE]/.test(n)||(n==="-"||n==="+")&&/[eE]/.test(s)?(o.push(n),s=n,e+1):/[^\d]/.test(n)?(C(o.join("")),r=si,e):(o.push(n),s=n,e+1)}function U(){if(/[^\d\w_]/.test(n)){var q=o.join("");return B[q]?r=UI:v[q]?r=OI:r=NI,C(o.join("")),r=si,e}return o.push(n),s=n,e+1}}var YI=LI,VI=KI;function KI(i,e){var t=YI(e),r=[];return r=r.concat(t(i)),r=r.concat(t(null)),r}var WI=function(e){return atob(e)},qI=VI,JI=WI,jI=XI;function XI(i){for(var e=Array.isArray(i)?i:qI(i),t=0;t<e.length;t++){var r=e[t];if(r.type==="preprocessor"){var n=r.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/);if(n&&n[2]){var s=n[1],o=n[2];return(s?JI(o):o).trim()}}}}/*!
118
118
  * repeat-string <https://github.com/jonschlinkert/repeat-string>
119
119
  *
120
120
  * Copyright (c) 2014-2015, Jon Schlinkert.
@@ -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 _h=Ya(Mv);var Rh;function Fv(i){if(typeof i=="string"){const[e,t]=i.split(":");return Math.min(parseFloat(e),parseFloat(t))}return i}function Pv(i){if(typeof i=="string"){const[e,t]=i.split(":"),r=parseFloat(e),n=parseFloat(t);return r/n}return i}function yl({resolution:i,aspectRatio:e}){const t=Fv(i),r=Pv(e),n=r>=1,s=Math.min(n?t*r:t/r,t),o=Math.max(n?t*r:t/r,t);return{resolution:t,aspectRatio:r,height:Math.round(n?s:o),width:Math.round(n?o:s)}}const Dh={linear:Jm,easeIn:$a,easeInOut:Xm,easeOut:jm,circIn:Su,circInOut:zm,circOut:xu,backIn:Ha,backInOut:eE,backOut:Zm,anticipate:tE,bounceIn:sE,bounceInOut:oE,bounceOut:Gs},lo=Fs((i,e,{clamp:t=!0,ease:r="easeIn",...n}={})=>Hm(i,e,{...n,clamp:t,ease:Dh[r]}),{cacheKey:([i,e,t])=>JSON.stringify({from:i,to:e,options:t})}),Nv={type:"clip",processor:{getTargetState:i=>({clip:{x:i.coordinates.x,y:i.coordinates.y,width:i.dimensions.width,height:i.dimensions.height}}),interpolateState:({value:i,easing:e,progress:t,from:r})=>{const n=r.clip??{x:0,y:0,width:1,height:1},s={x:i.coordinates.x,y:i.coordinates.y,width:i.dimensions.width,height:i.dimensions.height};return{clip:lo([0,1],[n,s],{ease:e})(t)}}}},co={type:"fade",processor:{getTargetState:i=>({opacity:i}),interpolateState:({value:i,easing:e,progress:t,from:r})=>({opacity:lo([0,1],[r.opacity,i],{ease:e})(t)})}},Ov={type:"scale",processor:{getTargetState:i=>({scale:i}),interpolateState:({value:i,easing:e,progress:t,from:r})=>({scale:lo([0,1],[r.scale,i],{ease:e})(t)})}},Lh={type:"translate",processor:{getTargetState:i=>({translation:i}),interpolateState:({value:i,easing:e,progress:t,from:r})=>({translation:lo([0,1],[r.translation,i],{ease:e})(t)})}},Uv=[{label:"Both",value:"both"},{label:"At start",value:"enter"},{label:"At end",value:"exit"}],Gv=[{value:"left",icon:"arrow-left"},{value:"right",icon:"arrow-right"},{value:"up",icon:"arrow-up"},{value:"down",icon:"arrow-down"}],$v=[{value:"left",icon:"arrow-left"},{value:"right",icon:"arrow-right"}],Hv=[{value:"up",icon:"arrow-up"},{value:"down",icon:"arrow-down"}],Gn={timing:{type:"buttonRadio",name:"timing",label:"Animate",options:Uv},speed:{type:"slider",name:"speed",label:"Speed",min:0,max:100,step:1}},Cl={type:"switch",name:"reverseExit",label:"Reverse exit animation"},Yv=.2,Vv=1;function Kv(i,e){const t=i==="both"?e/2:e;return Math.min(Vv,t)}function $n({speed:i,timing:e,elementDuration:t}){const r=Kv(e,t),n=Math.min(Yv,r),s=Math.max(0,Math.min(100,i))/100;return r-s*(r-n)}const Wv="easeOut";function Hn(i){return{values:e=>{var t;return{timing:e.timing??"both",speed:[e.speed??50],...((t=i==null?void 0:i.values)==null?void 0:t.call(i,e))??{}}},options:e=>{var t;return{timing:e.timing,speed:e.speed[0],easing:Wv,...((t=i==null?void 0:i.options)==null?void 0:t.call(i,e))??{}}}}}function zi({timing:i,duration:e,elementDuration:t,easing:r,reverseExit:n=!1,enterFrom:s,exitTo:o,restValue:a}){const c=[],l=i==="both"||i==="enter",u=i==="both"||i==="exit",A=Math.max(0,t-e);if(l?(c.push({time:0,value:s,easing:r}),c.push({time:e,value:a,easing:"linear"})):c.push({time:0,value:a,easing:"linear"}),u){A>e&&c.push({time:A,value:a,easing:r});const h=n?s:o;c.push({time:t,value:h,easing:r})}return c}const kh="fade",qv={type:kh,name:"Fade",options:{...Gn},transform:Hn(),generate:(i,e)=>{const t=$n({speed:i.speed,timing:i.timing,elementDuration:e.elementDuration});return{fade:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,enterFrom:0,exitTo:0,restValue:1}),renderer:co}}}},Mh="pan",Fh=.25,Ph="left";function Nh(i,e,t){switch(i){case"left":return{x:e.width*t,y:0};case"right":return{x:-e.width*t,y:0};default:return Nh(Ph,e,t)}}function Jv(i){return{x:-i.x,y:-i.y}}const jv={type:Mh,name:"Pan",options:{...Gn,direction:{type:"buttonRadio",name:"direction",label:"Direction",options:$v},distance:{type:"slider",name:"distance",label:"Distance",min:.1,max:1,step:.05,transform:{format:i=>`${(i*100).toFixed(0)}%`}},reverseExit:Cl},transform:Hn({values:i=>({direction:i.direction??Ph,distance:[i.distance??Fh],reverseExit:i.reverseExit??!1}),options:i=>({direction:i.direction,distance:i.distance[0],reverseExit:i.reverseExit})}),generate:(i,e)=>{const t=$n({speed:i.speed,timing:i.timing,elementDuration:e.elementDuration}),r=i.distance??Fh,n=Nh(i.direction,e.elementDimensions,r),s=Jv(n);return{fade:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,reverseExit:i.reverseExit,enterFrom:0,exitTo:0,restValue:1}),renderer:co},translate:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,reverseExit:i.reverseExit,enterFrom:n,exitTo:s,restValue:{x:0,y:0}}),renderer:Lh}}}},Oh="pop",Uh=.5,Xv={type:Oh,name:"Pop",options:{...Gn},transform:Hn(),generate:(i,e)=>{const t=$n({speed:i.speed,timing:i.timing,elementDuration:e.elementDuration});return{fade:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,enterFrom:0,exitTo:0,restValue:1}),renderer:co},scale:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:"backOut",enterFrom:Uh,exitTo:Uh,restValue:1}),renderer:Ov}}}},Gh="rise",$h=50,zv="up";function Zv(i,e){switch(i){case"down":return{enterY:-e,exitY:e};case"up":default:return{enterY:e,exitY:-e}}}const ey={type:Gh,name:"Rise",options:{...Gn,direction:{type:"buttonRadio",name:"direction",label:"Direction",options:Hv},distance:{type:"slider",name:"distance",label:"Distance",min:5,max:100,step:5,transform:{format:i=>`${i}px`}},reverseExit:Cl},transform:Hn({values:i=>({direction:i.direction??zv,distance:[i.distance??$h],reverseExit:i.reverseExit??!1}),options:i=>({direction:i.direction,distance:i.distance[0],reverseExit:i.reverseExit})}),generate:(i,e)=>{const t=$n({speed:i.speed,timing:i.timing,elementDuration:e.elementDuration}),r=i.distance??$h,{enterY:n,exitY:s}=Zv(i.direction,r);return{fade:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,reverseExit:i.reverseExit,enterFrom:0,exitTo:0,restValue:1}),renderer:co},translate:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,reverseExit:i.reverseExit,enterFrom:{x:0,y:n},exitTo:{x:0,y:s},restValue:{x:0,y:0}}),renderer:Lh}}}},Hh="wipe",Bl="left";function $r(i){switch(i){case"left":return{coordinates:{x:1,y:0},dimensions:{width:0,height:1}};case"right":return{coordinates:{x:0,y:0},dimensions:{width:0,height:1}};case"up":return{coordinates:{x:0,y:1},dimensions:{width:1,height:0}};case"down":return{coordinates:{x:0,y:0},dimensions:{width:1,height:0}};default:return $r(Bl)}}function Yh(i){switch(i){case"left":return $r("right");case"right":return $r("left");case"up":return $r("down");case"down":return $r("up");default:return Yh(Bl)}}const ty={coordinates:{x:0,y:0},dimensions:{width:1,height:1}},iy={type:Hh,name:"Wipe",options:{...Gn,direction:{type:"buttonRadio",name:"direction",label:"Direction",options:Gv},reverseExit:Cl},transform:Hn({values:i=>({direction:i.direction??Bl,reverseExit:i.reverseExit??!1}),options:i=>({direction:i.direction,reverseExit:i.reverseExit})}),generate:(i,e)=>{const t=$n({speed:i.speed,timing:i.timing,elementDuration:e.elementDuration}),r=$r(i.direction),n=Yh(i.direction);return{clip:{keyframes:zi({timing:i.timing,duration:t,elementDuration:e.elementDuration,easing:i.easing,reverseExit:i.reverseExit,enterFrom:r,exitTo:n,restValue:ty}),renderer:Nv}}}},ry={[kh]:qv,[Gh]:ey,[Oh]:Xv,[Mh]:jv,[Hh]:iy};function ny(i,e){const{type:t,...r}=i,n=ry[t];if(!n)throw new Error(`Unknown preset type: ${t}`);return n.generate(r,e)}function sy({animation:i,sceneTime:e}){const t=i.keyframes;if(!t||t.length===0)return null;const r=[...t].sort((s,o)=>s.time-o.time);if(e<r[0].time)return null;const n=r[r.length-1];if(e>=n.time)return i.renderer.processor.getTargetState(n.value);for(let s=0;s<r.length-1;s++){const o=r[s],a=r[s+1];if(e>=o.time&&e<=a.time){const c=a.time-o.time,l=c===0?0:(e-o.time)/c,u=o.easing||"linear",A=i.renderer.processor.getTargetState(o.value);return i.renderer.processor.interpolateState({easing:u,progress:l,from:A,value:a.value})}}return null}function oy(i,e,t){const{preset:r,...n}=i;if(!r)return n;const s=ny(r,{elementDuration:e,elementDimensions:t});return{...n,...s}}function ay({layout:i,sceneTime:e,animations:t,elementDuration:r=5,elementDimensions:n={width:100,height:100}}){var s,o,a,c,l,u,A,h,d,f,g;let p={clip:null,opacity:((s=i==null?void 0:i.transform)==null?void 0:s.opacity)??1,translation:{x:((a=(o=i==null?void 0:i.transform)==null?void 0:o.translate)==null?void 0:a.x)??0,y:((l=(c=i==null?void 0:i.transform)==null?void 0:c.translate)==null?void 0:l.y)??0},scale:((u=i==null?void 0:i.transform)==null?void 0:u.scale)??1,rotation:((A=i==null?void 0:i.transform)==null?void 0:A.rotation)??0,dimensions:{widthRatio:((d=(h=i==null?void 0:i.transform)==null?void 0:h.dimension)==null?void 0:d.widthRatio)??1,heightRatio:((g=(f=i==null?void 0:i.transform)==null?void 0:f.dimension)==null?void 0:g.heightRatio)??1}};if(!t)return p;const v=oy(t,r,n);for(const B of Object.values(v)){if(!B)continue;const C=sy({animation:B,sceneTime:e});C&&(p={...p,...C})}return p}let Ao;const ly=new Uint8Array(16);function cy(){if(!Ao&&(Ao=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ao))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ao(ly)}const _t=[];for(let i=0;i<256;++i)_t.push((i+256).toString(16).slice(1));function Ay(i,e=0){return _t[i[e+0]]+_t[i[e+1]]+_t[i[e+2]]+_t[i[e+3]]+"-"+_t[i[e+4]]+_t[i[e+5]]+"-"+_t[i[e+6]]+_t[i[e+7]]+"-"+_t[i[e+8]]+_t[i[e+9]]+"-"+_t[i[e+10]]+_t[i[e+11]]+_t[i[e+12]]+_t[i[e+13]]+_t[i[e+14]]+_t[i[e+15]]}const Vh={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function uy(i,e,t){if(Vh.randomUUID&&!i)return Vh.randomUUID();i=i||{};const r=i.random||(i.rng||cy)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Ay(r)}function hy(i=.4,e=.4){const t=Math.max(.1,Math.min(.8,i)),r=Math.max(.2,Math.min(.6,e)),s=(1-t)/2,a=1-r;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 uo=64;function dy(){const i=[],e={x:.5,y:.5},t=.5;for(let r=0;r<uo;r++){const n=r/uo*2*Math.PI,s=e.x+t*Math.cos(n),o=e.y+t*Math.sin(n);i.push({x:s,y:o})}return i}function fy(i=1){const e=[],t={x:.5,y:.5};let r,n;i>=1?(r=.5,n=.5/i):(r=.5*i,n=.5);for(let s=0;s<uo;s++){const o=s/uo*2*Math.PI,a=t.x+r*Math.cos(o),c=t.y+n*Math.sin(o);e.push({x:a,y:c})}return e}function gy(){const i=[];for(let t=0;t<=100;t++){const r=t/100*2*Math.PI,n=16*Math.sin(r)**3,s=-(13*Math.cos(r)-5*Math.cos(2*r)-2*Math.cos(3*r)-Math.cos(4*r)),o=(n+16)/32,a=(s+13)/26;i.push({x:o,y:a})}return i}function Kh(i=0,e=1){if(i===0)return[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}];const t=i*Math.PI/180,r=Math.tan(t)/e;return[{x:Math.max(0,Math.min(1,0+r)),y:0},{x:Math.max(0,Math.min(1,1+r)),y:0},{x:Math.max(0,Math.min(1,1-r)),y:1},{x:Math.max(0,Math.min(1,0-r)),y:1}]}function ho(i){if(i<3)throw new Error("A polygon must have at least 3 sides");const e=[],t=[];for(let l=0;l<i;l++){const u=l*2*Math.PI/i-Math.PI/2,A=Math.cos(u),h=Math.sin(u);t.push({x:A,y:h})}const r=Math.min(...t.map(l=>l.x)),n=Math.max(...t.map(l=>l.x)),s=Math.min(...t.map(l=>l.y)),o=Math.max(...t.map(l=>l.y)),a=n-r,c=o-s;for(const l of t){const u=(l.x-r)/a,A=(l.y-s)/c;e.push({x:u,y:A})}return e}function Wh(i=90){const e=i*Math.PI/180,r=.5/Math.tan(e),s=1/(1+Math.abs(r)*2),o=r*s;return[{x:.5+o,y:0},{x:1,y:.5},{x:.5-o,y:1},{x:0,y:.5}]}function py(i=5,e=.4){const t=[];for(let n=0;n<i*2;n++){const s=n*Math.PI/i-Math.PI/2,o=n%2===0?.5:e,a=.5+o*Math.cos(s),c=.5+o*Math.sin(s);t.push({x:a,y:c})}return t}function my(i="isosceles",e={}){switch(i){case"equilateral":return Ey();case"isosceles":return qh(e.baseAngle??60);case"right":return Iy(e.rightAnglePosition??"bottom-left");case"scalene":return vy(e.angles??[60,60,60])}}function Ey(){return[{x:.5,y:0},{x:0,y:1},{x:1,y:1}]}function qh(i){const e=i*Math.PI/180,t=.5/Math.tan(e),r=Math.max(.1,Math.min(2,t));return[{x:.5,y:1-Math.min(1,r)},{x:0,y:1},{x:1,y:1}]}function Iy(i){switch(i){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 vy(i){return qh(i[0])}function yy(i={},e=1){const{type:t="rectangle",customPolygon:r,parallelogram:n,triangle:s,rhombus:o,arrow:a,star:c,regularPolygon:l}=i;switch(t){case"rectangle":return Kh(0,e);case"parallelogram":return Kh((n==null?void 0:n.angle)??30,e);case"triangle":return my((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 Wh((o==null?void 0:o.angle)??90);case"diamond":return Wh(90);case"pentagon":return ho(5);case"hexagon":return ho(6);case"octagon":return ho(8);case"star":return py((c==null?void 0:c.points)??5,(c==null?void 0:c.innerRadius)??.4);case"arrow":return hy((a==null?void 0:a.shaftRatio)??.4,(a==null?void 0:a.headRatio)??.4);case"heart":return gy();case"circle":return dy();case"ellipse":return fy(e);case"custom-polygon":if(!(r!=null&&r.points)||r.points.length<3)throw new Error("Custom polygon must have at least 3 points");return r.points;default:return ho((l==null?void 0:l.sides)??6)}}function Cy(i,e){let t=!1;const r=i.x,n=i.y;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s].x,c=e[s].y,l=e[o].x,u=e[o].y;c>n!=u>n&&r<(l-a)*(n-c)/(u-c)+a&&(t=!t)}return t}function By(i,e){let t=1,r=0;const n=200;for(let s=0;s<=n;s++){const o=s/n;Cy({x:o,y:i},e)&&(t=Math.min(t,o),r=Math.max(r,o))}return r>=t?{left:t,right:r}:null}function Ty(i){const e=Math.min(...i.map(c=>c.y)),t=Math.max(...i.map(c=>c.y));let r={x:0,y:0,width:0,height:0},n=0;const s=200,o=(t-e)/s,a=[];for(let c=0;c<=s;c++){const l=e+c*o;a.push({y:l,span:By(l,i)})}for(let c=0;c<a.length-1;c++){const l=a[c].y;for(let u=c+1;u<a.length;u++){const h=a[u].y-l;let d=0,f=1,g=!0;const p=Math.min(5,u-c+1);for(let v=0;v<p;v++){const B=c+Math.floor(v/(p-1)*(u-c)),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,r={x:d,y:l,width:v,height:h})}}}return r}function by(i,e=1){const t=yy(i,e);if(t.length<3)return{top:0,right:0,bottom:0,left:0};if(i.type==="rectangle")return{top:0,right:0,bottom:0,left:0};const r=Ty(t),n=r.y,s=r.x,o=1-(r.x+r.width),a=1-(r.y+r.height);return{top:Math.max(0,n),right:Math.max(0,o),bottom:Math.max(0,a),left:Math.max(0,s)}}function Sy(i){return typeof i=="number"?{topLeft:i,topRight:i,bottomRight:i,bottomLeft:i}:{topLeft:(i==null?void 0:i.topLeft)??0,topRight:(i==null?void 0:i.topRight)??0,bottomRight:(i==null?void 0:i.bottomRight)??0,bottomLeft:(i==null?void 0:i.bottomLeft)??0}}function xy(i,e){return typeof i=="number"?{top:i*e,right:i*e,bottom:i*e,left:i*e}:typeof i=="string"?{top:i,right:i,bottom:i,left:i}:{top:typeof i.top=="number"?i.top*e:i.top,right:typeof i.right=="number"?i.right*e:i.right,bottom:typeof i.bottom=="number"?i.bottom*e:i.bottom,left:typeof i.left=="number"?i.left*e:i.left}}function Qy(i,e){return typeof i=="number"?{top:i*e,right:i*e,bottom:i*e,left:i*e}:typeof i=="string"?{top:i,right:i,bottom:i,left:i}:{top:(typeof i.top=="number"?i.top*e:i.top)??0,right:(typeof i.right=="number"?i.right*e:i.right)??0,bottom:(typeof i.bottom=="number"?i.bottom*e:i.bottom)??0,left:(typeof i.left=="number"?i.left*e:i.left)??0}}function wy(i,e){return typeof i=="number"?{top:i*e,right:i*e,bottom:i*e,left:i*e}:typeof i=="string"?{top:i,right:i,bottom:i,left:i}:{top:(typeof i.top=="number"?i.top*e:i.top)??0,right:(typeof i.right=="number"?i.right*e:i.right)??0,bottom:(typeof i.bottom=="number"?i.bottom*e:i.bottom)??0,left:(typeof i.left=="number"?i.left*e:i.left)??0}}const _y=Ir(()=>Qu.loadYoga());function Jh(i,e,{layout:t,scale:r=1}){const{position:n="relative",inset:s,width:o,height:a,minWidth:c,minHeight:l,maxWidth:u,maxHeight:A,flex:h,flexGrow:d,flexShrink:f,gap:g,margin:p,padding:v,direction:B="column",align:C="start",alignSelf:y,justify:x="start"}=t??{},_={static:i.POSITION_TYPE_STATIC,relative:i.POSITION_TYPE_RELATIVE,absolute:i.POSITION_TYPE_ABSOLUTE};if(e.setPositionType(_[n]),typeof s<"u"){const{top:M,right:j,bottom:X,left:le}=xy(s,r);typeof M<"u"&&e.setPosition(i.EDGE_TOP,M),typeof j<"u"&&e.setPosition(i.EDGE_RIGHT,j),typeof X<"u"&&e.setPosition(i.EDGE_BOTTOM,X),typeof le<"u"&&e.setPosition(i.EDGE_LEFT,le)}const D={row:i.FLEX_DIRECTION_ROW,column:i.FLEX_DIRECTION_COLUMN,"row-reverse":i.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":i.FLEX_DIRECTION_COLUMN_REVERSE};e.setFlexDirection(D[B]);const F={start:i.ALIGN_FLEX_START,end:i.ALIGN_FLEX_END,center:i.ALIGN_CENTER,stretch:i.ALIGN_STRETCH};e.setAlignItems(F[C]),y&&e.setAlignSelf(F[y]);const O={start:i.JUSTIFY_FLEX_START,end:i.JUSTIFY_FLEX_END,center:i.JUSTIFY_CENTER,"space-between":i.JUSTIFY_SPACE_BETWEEN,"space-around":i.JUSTIFY_SPACE_AROUND,"space-evenly":i.JUSTIFY_SPACE_EVENLY};if(e.setJustifyContent(O[x]),typeof p<"u"){const{top:M,right:j,bottom:X,left:le}=Qy(p,r);e.setMargin(i.EDGE_TOP,M),e.setMargin(i.EDGE_RIGHT,j),e.setMargin(i.EDGE_BOTTOM,X),e.setMargin(i.EDGE_LEFT,le)}if(typeof v<"u"){const{top:M,right:j,bottom:X,left:le}=wy(v,r);e.setPadding(i.EDGE_TOP,M),e.setPadding(i.EDGE_RIGHT,j),e.setPadding(i.EDGE_BOTTOM,X),e.setPadding(i.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(i.GUTTER_ALL,(g??0)*r),typeof o<"u"&&e.setWidth(typeof o=="number"?o*r:o),typeof a<"u"&&e.setHeight(typeof a=="number"?a*r:a),typeof c<"u"&&e.setMinWidth(typeof c=="number"?c*r:c),typeof l<"u"&&e.setMinHeight(typeof l=="number"?l*r:l),typeof u<"u"&&e.setMaxWidth(typeof u=="number"?u*r:u),typeof A<"u"&&e.setMaxHeight(typeof A=="number"?A*r:A)}async function jh({id:i,yoga:e,index:t,parent:r,element:n,resolvers:s}){var o,a,c;const{layout:l={},config:u={},options:A={},renderer:h}=n,d=e.Node.create();Jh(e,d,{layout:l}),r.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:i,config:u,options:A}))??null:f=await((a=s[h.type])==null?void 0:a.call(s,{id:i,config:u,options:A}))??null);const g=[];for await(const[p,v]of((c=n.children)==null?void 0:c.entries())??[])g.push(await jh({id:i,yoga:e,index:p,parent:d,element:v,resolvers:s}));return{node:d,radius:Sy(l.radius),element:n,renderer:h,config:u,options:A,dependencies:f,childNodes:g}}function Xh(i,e,t=0,r=0){const{top:n,left:s}=i.getComputedLayout(),{top:o,left:a,width:c,height:l}=e.node.getComputedLayout(),u=t+a,A=r+o,h=e.childNodes.map(d=>Xh(i,d,u,A));return{...e,x:s+u,y:n+A,width:c,height:l,childNodes:h}}async function Tl({yoga:i,root:e,tree:t,measureCanvas:r}){for await(const{node:n,options:s,dependencies:o,renderer:a,childNodes:c}of t){if(a){const{width:l,height:u}=a;if(l&&r){e.calculateLayout();const A=await l({node:n,options:s,dependencies:o,measureCanvas:r});A&&n.setWidth(A)}if(u&&r){e.calculateLayout();const A=await u({node:n,options:s,dependencies:o,measureCanvas:r});A&&n.setHeight(A)}if(await Tl({yoga:i,root:e,tree:c,measureCanvas:r}),s!=null&&s.shape){const A=n.getComputedWidth(),h=n.getComputedHeight(),d=by(s.shape,A/h);n.setPadding(i.EDGE_TOP,d.top*h),n.setPadding(i.EDGE_RIGHT,d.right*A),n.setPadding(i.EDGE_BOTTOM,d.bottom*h),n.setPadding(i.EDGE_LEFT,d.left*A)}}e.calculateLayout(),await Tl({yoga:i,root:e,tree:c,measureCanvas:r})}}async function zh({id:i,root:e,resolvers:t,measureCanvas:r}){const n=await _y(),s=n.Node.create();Jh(n,s,{layout:e.layout});const o=await jh({id:i,yoga:n,index:0,parent:s,element:e.element,resolvers:t});await Tl({yoga:n,root:s,tree:[o],measureCanvas:r});const{top:a,left:c,width:l,height:u}=s.getComputedLayout(),A={root:{x:c,y:a,width:l,height:u},node:Xh(s,o)};return s.freeRecursive(),A}const Ry={type:"audio"},Yn=/(?<value>\d+\.?\d*)(?=px)/;function bl({words:i,spaceMetrics:e,strokeWidth:t=0}){return i.reduce((r,n,s)=>{const o=n.metrics.width+t,a=s<i.length-1?e.width:0;return r+o+a},0)}Fs(({context:i,font:e,fontSizes:t,words:r,maxW:n=1/0,strokeWidth:s=0,letterSpacing:o=0})=>{try{i.save(),i.letterSpacing=`${o}px`,i.font=e.replace(Yn,t[0].toString());const a=i.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");if(r.length<=0)return[];const c=i.measureText(r[0].text);return r.slice(1).reduce((l,u)=>{const A=l[l.length-1],h=i.measureText(u.text),d={...u,metrics:h},f=[...A.words,d],g=bl({strokeWidth:s,words:f,spaceMetrics:A.spaceMetrics});if(g>n){const p=t[l.length%t.length];i.font=e.replace(Yn,p.toString());const v=i.measureText(" "),B=i.measureText(u.text),C=[{...u,metrics:B}],y=i.measureText("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");l=[...l,{allMetrics:y,spaceMetrics:v,lineWidth:bl({strokeWidth:s,spaceMetrics:v,words:C}),font:i.font,words:C,lineHeight:y.actualBoundingBoxAscent+y.actualBoundingBoxDescent+s}]}else l[l.length-1]={...A,lineWidth:g,words:f};return l},[{allMetrics:a,lineWidth:bl({strokeWidth:s,words:[{...r[0],metrics:c}],spaceMetrics:i.measureText(" ")}),lineHeight:a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+s,font:i.font,words:[{...r[0],metrics:c}],spaceMetrics:i.measureText(" ")}])}finally{i.restore()}},{cacheKey:([{font:i,fontSizes:e,words:t,maxW:r,strokeWidth:n,letterSpacing:s}])=>`${i}_${JSON.stringify(e)}_${JSON.stringify(t)}_${r}_${n}_${s}`});function Dy(i){return i.slice(0,1).toUpperCase()+i.slice(1)}const Zh=[{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 Ly({text:i,font:e}){let t=e;return Zh.forEach(({family:r,regex:n})=>{n.exec(i)&&(t+=`, ${r}`)}),t}const ky="caption";Object.keys(Dh).map(i=>({label:Dy(i),value:i,data:i}));const My={type:ky},Fy={type:"image"};function ed({context:i,word:e,maxW:t=1/0}){const r=[],n=i.measureText(e);if(Math.floor(n.width)<=t)return[{text:e,metrics:n}];for(let s=0;s<e.length;s++){const o=r[r.length-1],a=((o==null?void 0:o.text)??"")+e[s],c=i.measureText(a);c.width<t?r[o?r.length-1:0]={text:a,metrics:c}:r.push({text:e[s],metrics:i.measureText(e[s])})}return r}const Py=Fs(({font:i,context:e,fontSizes:t,text:r,maxW:n=1/0,letterSpacing:s=0})=>{try{return e.save(),e.letterSpacing=`${s}px`,e.font=i.replace(Yn,t[0].toString()),r.split(`
2476
- `).flatMap(a=>{const c=a.split(" ").filter(Boolean);return c.length?c.slice(1).reduce((l,u,A)=>{const d=`${l[l.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)l=[...l,...ed({context:e,word:u,maxW:n})];else{const g=t[A%t.length];e.font=i.replace(Yn,g.toString()),l[l.length-1]={text:d,metrics:f}}return l},ed({context:e,word:c[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:i,fontSizes:e,text:t,maxW:r,letterSpacing:n}])=>`${i}_${JSON.stringify(e)}_${t}_${r}_${n}`});Fs(({font:i,text:e,scale:t,context:r,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:c=0})=>{var l,u;let A=0;if(a){A=(o??0)*t;let d=0;for(;a*t>A+1;){A+=1;const f=Py({font:i,context:r,fontSizes:[A],text:e,maxW:n,letterSpacing:c});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*A>s){A-=1;break}}}else A=parseFloat(((u=(l=i.match(Yn))==null?void 0:l.groups)==null?void 0:u.value)??"0")*t;return A},{cacheKey:([{font:i,text:e,scale:t,maxW:r,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${i}_${e}_${s}_${o}_${t}_${r}_${n}_${a}`});const Ny={type:"text"},Oy={type:"video"};function td(){return document.createElement("canvas")}function Uy(i,e){return Object.keys(i).reduce((t,r)=>(e.includes(r)||(t[r]=i[r]),t),{})}function Jt(i){let e=0;for(const t of i)Array.isArray(t)?e+=Jt(t):e+=t;return e}function fo(i){return i.map(({type:e,duration:t},r)=>{var n,s,o,a;if(e==="transition"){const c=((n=i[r-2])==null?void 0:n.type)==="transition"?i[r-2]:null,l=((s=i[r-1])==null?void 0:s.duration)??1/0,u=((o=i[r+1])==null?void 0:o.duration)??1/0,A=((a=i[r+2])==null?void 0:a.type)==="transition"?i[r+2]:null;return Math.min(c?l/2:l,t,A?u/2:u)*-1}return t})}function id(i){var e;return{...i,children:((e=i.children)==null?void 0:e.map(t=>{if(!t.renderer)return id(t)}).filter(Boolean))??[]}}function rd(i){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};i.renderer&&(e[i.renderer.type]+=1);for(const t of i.children??[]){const{box:r,shape:n,image:s,video:o,text:a,audio:c,gradient:l,caption:u}=rd(t);e.box+=r,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=c,e.gradient+=l,e.caption+=u}return e}function Gy(i){return i.video>0?Oy.type:i.image>0?Fy.type:i.audio>0?Ry.type:i.caption>0?My.type:Ny.type}function nd({node:i,duration:e,parentAnimations:t}){const r=[],n={...t,...i.element.animations};if(i.renderer){const s=id({...i.element,layout:{...i.element.layout?Uy(i.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=rd(s);r.push({type:Gy(o),id:uy(),x:i.x,y:i.y,width:i.width,height:i.height,duration:e,root:{element:s}})}for(const s of i.childNodes)r.push(...nd({node:s,duration:e,parentAnimations:n}));return r}function $y(i){if(i===null||typeof i!="object")return!1;if(Object.getPrototypeOf(i)===null)return!0;let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Hy(i){return i.replace(/\\/g,"\\\\").replace(/\//g,"\\/").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\f/g,"\\f").replace(/"/g,'\\"')}aE.filters.define("parse",i=>typeof i>"u"?null:typeof i=="string"?`"${Hy(i)}"`:$y(i)||Array.isArray(i)?JSON.stringify(i):i);const Yy="3";async function Vy({scene:i,start:e=0}){const{id:t,root:r,duration:n}=i,s=await zh({id:t,root:r});return{type:i.type,start:e,duration:n,layout:s,id:i.id,config:i}}async function Ky({track:i}){const e=fo(i),t=await Promise.all(i.reduce((s,o,a)=>{if(o.type!=="audio")return s;const c=Jt(e.slice(0,a));return s.push(Vy({scene:o,start:c})),s},[])),r=i.reduce((s,o,a)=>{if(o.type!=="gap")return s;const c=Jt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:c,config:o,duration:o.duration}),s},[]),n=i.map(({id:s})=>t.find(({id:o})=>o===s)??r.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:r,mergedScenes:n,config:i,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function sd({node:i,canvases:e,sceneTime:t,sceneDuration:r,parentOpacity:n=1,parentTransform:s,debug:o=!1}){var a,c;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(s);const u=ay({layout:i.element.layout,sceneTime:t,animations:i.element.animations,elementDuration:r,elementDimensions:{width:i.width,height:i.height}}),{opacity:A,translation:h,scale:d,clip:f,dimensions:g,rotation:p}=u,v=i.width*g.widthRatio,B=i.height*g.heightRatio;if(l.globalAlpha=A*n,(h.x||h.y)&&l.translate(h.x,h.y),(d!==1||p!==0)&&(l.translate(i.x+v/2,i.y+B/2),l.scale(d,d),l.rotate(p*Math.PI/180),l.translate(-(i.x+v/2),-(i.y+B/2))),f){l.beginPath();const C={x:i.x+f.x*v,y:i.y+f.y*B,width:f.width*v,height:f.height*B};l.rect(C.x,C.y,C.width,C.height),l.clip()}if(o){const C=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(i.x,i.y,v,B),l.globalAlpha=C}await((c=(a=i.renderer)==null?void 0:a.render)==null?void 0:c.call(a,{canvases:e,sceneTime:t,dx:i.x,dy:i.y,dw:v,dh:B,radius:i.radius,options:i.options,dependencies:i.dependencies}));for await(const C of i.childNodes)await sd({debug:o,node:C,canvases:e,sceneTime:t,sceneDuration:r,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function Wy({layout:i,canvases:e,sceneTime:t,sceneDuration:r,debug:n=!1}){const{node:s}=i;await sd({debug:n,node:s,canvases:e,sceneDuration:r,sceneTime:t})}async function go({debug:i=!1,scene:e,start:t=0,resolvers:r,rootWidth:n,rootHeight:s,canvasFactory:o=td}){var a,c;const{id:l,x:u,y:A,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await zh({id:l,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof A=="number"?{position:"absolute",inset:{top:A,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((c=f.element.layout)==null?void 0:c.height)}}},resolvers:r,measureCanvas:y}),_=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await Wy({debug:i,layout:x,sceneTime:F,sceneDuration:g,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:l,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:_,config:e,childScenes:x.node.childNodes.flatMap(D=>nd({node:D,duration:g}))}}async function qy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="caption"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}async function Jy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="video"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),h.type==="image"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(0,...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}async function jy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="text"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"text",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}function Xy(i){return i.some(({type:e})=>e==="text")}function zy(i){return i.some(({type:e})=>e==="caption")}function Zy(i){return i.some(({type:e})=>e==="audio")}function eC(i){return i.some(({type:e})=>e==="video"||e==="image")}function tC(i){return i.type==="audio"}const iC=(((Rh=_h)==null?void 0:Rh.default)??_h).reduce((i,e)=>(i[e.name]=e,i),{});function rC(i,e){return i.has(e)||i.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),i.get(e)}function nC({name:i,to:e,from:t,progress:r,width:n,height:s,glContext:o,contextResources:a,returnPixels:c=!0}){var l,u,A;const h=rC(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=(((l=no)==null?void 0:l.default)??no)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=no)==null?void 0:u.default)??no)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[i]||(h.transitions[i]=(((A=wh)==null?void 0:A.default)??wh)(o,iC[i])),h.transitions[i].draw(r,h.fromTexture,h.toTexture,n,s),!c)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 sC(i){for(const[e,t]of i.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(r=>{r.dispose()}),i.delete(e)}function oC({name:i,to:e,from:t,progress:r,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),nC({name:i,to:e,from:t,progress:r,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function od({debug:i=!1,config:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s=td,drawTransition:o=oC}){const a=new Map,c=await Promise.all(e.tracks.map(async A=>{if(eC(A))return{...await Jy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(Xy(A))return{...await jy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(zy(A))return{...await qy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(Zy(A))return{...await Ky({track:A}),config:A};throw new Error("Unknown track type")}));return{draw:async({canvas:A,currentTime:h})=>{const d=A.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,A.width,A.height),d.save(),d.fillStyle="black",d.fillRect(0,0,A.width,A.height),d.restore();for await(const f of c){if(tC(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=A.width,v.height=A.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:_})=>h>=x&&h<x+_);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:_})=>h>=x&&h<x+_);for await(const{sceneCanvas:x,draw:_}of C)await(_==null?void 0:_(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:_,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-_.start)/F));await o({name:x,progress:M,contextResources:a,to:_.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:()=>{sC(a)},tracks:c,aspectRatio:e.aspectRatio,transcriptions:e.transcriptions,duration:Math.max(...c.map(({duration:A})=>A))}}const aC={version:"7.0.1"};function lC(i){const{publicApiUrl:e}=Ms(i),t=Ki();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function cC(i){var s,o,a,c,l,u,A,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:Ki()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(c=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:c.call(a,"vouch-uid-client"),r=(u=(l=window.sessionStorage)==null?void 0:l.getItem)==null?void 0:u.call(l,"vouch-uid-tab");const n=Ki();return e||(e=lC(i),(h=(A=window.localStorage)==null?void 0:A.setItem)==null||h.call(A,"vouch-uid-visitor",e)),t||(t=Ki(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),r||(r=Ki(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",r)),{client:t,tab:r,request:n,visitor:e}}function AC(i,e){return i&&"vouchId"in i?i.vouchId:(e==null?void 0:e.id)??null}function uC(i="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,"/"))??[],r={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const c=o.toLowerCase().replace(/[-_][a-z0-9]/g,l=>l.slice(-1).toUpperCase());r[c]=a}}),{source:i,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:aC.version,templateVersion:Yy,...r}}const ad=1;class hC{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,r)=>{const n=AC(r,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...r,senderId:this.host.senderId,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=Ms(this.host.env),{client:r,tab:n,request:s,visitor:o}=cC(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":r,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":uC(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:r}=this._currentlyPlayingVideo;this._streamLatestTime[r]>this._streamStartTime[r]+ad&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[r],streamEnd:this._streamLatestTime[r]}),delete this._streamStartTime[r],delete this._streamLatestTime[r]}},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:r}})=>{this._answersViewed[r]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[r]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:r,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:r,node:n},this._streamLatestTime[r]=n.currentTime,this._streamStartTime[r]||(this._streamStartTime[r]=n.currentTime,this._streamLatestTime[r]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:r}})=>{this._streamLatestTime[r]>this._streamStartTime[r]+ad&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[r],streamEnd:this._streamLatestTime[r]}),delete this._streamStartTime[r],delete this._streamLatestTime[r]},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,r,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),(r=this.host.mediaPlayer)==null||r.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,r,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),(r=this.host.mediaPlayer)==null||r.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var Sl={exports:{}};(function(i,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ji<"u"&&Ji,r=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 Ji<"u"&&Ji||{},c={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 l(L){return L&&DataView.prototype.isPrototypeOf(L)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],A=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 c.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)},c.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),w=R?R[1]:"utf-8";return U.readAsText(L,w),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 _(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:c.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:c.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():c.arrayBuffer&&c.blob&&l(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||A(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):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.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(c.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)},c.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 w=/\?/;this.url+=(w.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("="),w=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(w),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 c=a.split(" ").filter(Boolean);return c.length?c.slice(1).reduce((l,u,A)=>{const d=`${l[l.length-1].text} ${u}`.trim(),f=e.measureText(d);if(f.width>n)l=[...l,...ed({context:e,word:u,maxW:n})];else{const g=t[A%t.length];e.font=i.replace(Yn,g.toString()),l[l.length-1]={text:d,metrics:f}}return l},ed({context:e,word:c[0],maxW:n})):{text:"",metrics:e.measureText("")}})}finally{e.restore()}},{cacheKey:([{font:i,fontSizes:e,text:t,maxW:r,letterSpacing:n}])=>`${i}_${JSON.stringify(e)}_${t}_${r}_${n}`});Fs(({font:i,text:e,scale:t,context:r,maxW:n,maxH:s,minSize:o,maxSize:a,letterSpacing:c=0})=>{var l,u;let A=0;if(a){A=(o??0)*t;let d=0;for(;a*t>A+1;){A+=1;const f=Py({font:i,context:r,fontSizes:[A],text:e,maxW:n,letterSpacing:c});if(d=f.reduce((g,p)=>(p.metrics.width>g&&(g=p.metrics.width),g),0),d>n||f.length*A>s){A-=1;break}}}else A=parseFloat(((u=(l=i.match(Yn))==null?void 0:l.groups)==null?void 0:u.value)??"0")*t;return A},{cacheKey:([{font:i,text:e,scale:t,maxW:r,maxH:n,minSize:s,maxSize:o,letterSpacing:a}])=>`${i}_${e}_${s}_${o}_${t}_${r}_${n}_${a}`});const Ny={type:"text"},Oy={type:"video"};function td(){return document.createElement("canvas")}function Uy(i,e){return Object.keys(i).reduce((t,r)=>(e.includes(r)||(t[r]=i[r]),t),{})}function Jt(i){let e=0;for(const t of i)Array.isArray(t)?e+=Jt(t):e+=t;return e}function fo(i){return i.map(({type:e,duration:t},r)=>{var n,s,o,a;if(e==="transition"){const c=((n=i[r-2])==null?void 0:n.type)==="transition"?i[r-2]:null,l=((s=i[r-1])==null?void 0:s.duration)??1/0,u=((o=i[r+1])==null?void 0:o.duration)??1/0,A=((a=i[r+2])==null?void 0:a.type)==="transition"?i[r+2]:null;return Math.min(c?l/2:l,t,A?u/2:u)*-1}return t})}function id(i){var e;return{...i,children:((e=i.children)==null?void 0:e.map(t=>{if(!t.renderer)return id(t)}).filter(Boolean))??[]}}function rd(i){const e={box:0,shape:0,image:0,video:0,text:0,audio:0,gradient:0,caption:0};i.renderer&&(e[i.renderer.type]+=1);for(const t of i.children??[]){const{box:r,shape:n,image:s,video:o,text:a,audio:c,gradient:l,caption:u}=rd(t);e.box+=r,e.shape+=n,e.image+=s,e.video+=o,e.text+=a,e.audio+=c,e.gradient+=l,e.caption+=u}return e}function Gy(i){return i.video>0?Oy.type:i.image>0?Fy.type:i.audio>0?Ry.type:i.caption>0?My.type:Ny.type}function nd({node:i,duration:e,parentAnimations:t}){const r=[],n={...t,...i.element.animations};if(i.renderer){const s=id({...i.element,layout:{...i.element.layout?Uy(i.element.layout,["maxWidth","maxHeight"]):{},width:"100%",height:"100%",margin:0}}),o=rd(s);r.push({type:Gy(o),id:uy(),x:i.x,y:i.y,width:i.width,height:i.height,duration:e,root:{element:s}})}for(const s of i.childNodes)r.push(...nd({node:s,duration:e,parentAnimations:n}));return r}function $y(i){if(i===null||typeof i!="object")return!1;if(Object.getPrototypeOf(i)===null)return!0;let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Hy(i){return i.replace(/\\/g,"\\\\").replace(/\//g,"\\/").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\f/g,"\\f").replace(/"/g,'\\"')}aE.filters.define("parse",i=>typeof i>"u"?null:typeof i=="string"?`"${Hy(i)}"`:$y(i)||Array.isArray(i)?JSON.stringify(i):i);const Yy="3";async function Vy({scene:i,start:e=0}){const{id:t,root:r,duration:n}=i,s=await zh({id:t,root:r});return{type:i.type,start:e,duration:n,layout:s,id:i.id,config:i}}async function Ky({track:i}){const e=fo(i),t=await Promise.all(i.reduce((s,o,a)=>{if(o.type!=="audio")return s;const c=Jt(e.slice(0,a));return s.push(Vy({scene:o,start:c})),s},[])),r=i.reduce((s,o,a)=>{if(o.type!=="gap")return s;const c=Jt(e.slice(0,a));return s.push({type:o.type,id:o.id,start:c,config:o,duration:o.duration}),s},[]),n=i.map(({id:s})=>t.find(({id:o})=>o===s)??r.find(({id:o})=>o===s)).filter(Boolean);return{type:"audio",scenes:t,gapScenes:r,mergedScenes:n,config:i,duration:Math.max(...n.map(({start:s,duration:o})=>s+o))}}async function sd({node:i,canvases:e,sceneTime:t,sceneDuration:r,parentOpacity:n=1,parentTransform:s,debug:o=!1}){var a,c;const l=e.sceneCanvas.getContext("2d");if(l){l.save(),l.setTransform(s);const u=ay({layout:i.element.layout,sceneTime:t,animations:i.element.animations,elementDuration:r,elementDimensions:{width:i.width,height:i.height}}),{opacity:A,translation:h,scale:d,clip:f,dimensions:g,rotation:p}=u,v=i.width*g.widthRatio,B=i.height*g.heightRatio;if(l.globalAlpha=A*n,(h.x||h.y)&&l.translate(h.x,h.y),(d!==1||p!==0)&&(l.translate(i.x+v/2,i.y+B/2),l.scale(d,d),l.rotate(p*Math.PI/180),l.translate(-(i.x+v/2),-(i.y+B/2))),f){l.beginPath();const C={x:i.x+f.x*v,y:i.y+f.y*B,width:f.width*v,height:f.height*B};l.rect(C.x,C.y,C.width,C.height),l.clip()}if(o){const C=l.globalAlpha;l.globalAlpha=1,l.strokeStyle="red",l.strokeRect(i.x,i.y,v,B),l.globalAlpha=C}await((c=(a=i.renderer)==null?void 0:a.render)==null?void 0:c.call(a,{canvases:e,sceneTime:t,dx:i.x,dy:i.y,dw:v,dh:B,radius:i.radius,options:i.options,dependencies:i.dependencies}));for await(const C of i.childNodes)await sd({debug:o,node:C,canvases:e,sceneTime:t,sceneDuration:r,parentOpacity:l.globalAlpha,parentTransform:l.getTransform()});l.restore()}}async function Wy({layout:i,canvases:e,sceneTime:t,sceneDuration:r,debug:n=!1}){const{node:s}=i;await sd({debug:n,node:s,canvases:e,sceneDuration:r,sceneTime:t})}async function go({debug:i=!1,scene:e,start:t=0,resolvers:r,rootWidth:n,rootHeight:s,canvasFactory:o=td}){var a,c;const{id:l,x:u,y:A,width:h,height:d,root:f,duration:g}=e,p=o(),v=o(),B=o(),C=o(),y=o(),x=await zh({id:l,root:{...f,layout:{...f.layout,width:n,height:s},element:{...f.element,layout:{...f.element.layout,...typeof u=="number"&&typeof A=="number"?{position:"absolute",inset:{top:A,left:u}}:{},width:h??((a=f.element.layout)==null?void 0:a.width),height:d??((c=f.element.layout)==null?void 0:c.height)}}},resolvers:r,measureCanvas:y}),_=async D=>{const F=Math.max(0,D-t);p.width=p.height=0,p.width=n,p.height=s,await Wy({debug:i,layout:x,sceneTime:F,sceneDuration:g,canvases:{sceneCanvas:p,cropCanvas:v,letterboxCanvas:B,posterCanvas:C}})};return{id:l,type:e.type,start:t,duration:g,layout:x,sceneCanvas:p,draw:_,config:e,childScenes:x.node.childNodes.flatMap(D=>nd({node:D,duration:g}))}}async function qy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="caption"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"caption",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}async function Jy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="video"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),h.type==="image"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"picture",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(0,...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}async function jy({debug:i=!1,track:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}){const o=fo(e),a=await Promise.all(e.reduce((A,h,d)=>{const f=Jt(o.slice(0,d));return h.type==="text"&&A.push(go({debug:i,scene:h,start:f,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s})),A},[])),c=e.reduce((A,h,d)=>{if(h.type!=="gap")return A;const f=Jt(o.slice(0,d));return A.push({type:h.type,id:h.id,start:f,config:h,duration:h.duration}),A},[]),l=e.reduce((A,h,d)=>{if(h.type!=="transition")return A;const f=h.duration,g=Jt(o.slice(0,d))-f;return A.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)})}),A},[]),u=e.map(({id:A})=>a.find(({id:h})=>h===A)??c.find(({id:h})=>h===A)??l.find(({id:h})=>h===A)).filter(Boolean);return{type:"text",scenes:a,gapScenes:c,transitions:l,mergedScenes:u,duration:Math.max(...u.map(({start:A,duration:h})=>A+h)),trackCanvas:s()}}function Xy(i){return i.some(({type:e})=>e==="text")}function zy(i){return i.some(({type:e})=>e==="caption")}function Zy(i){return i.some(({type:e})=>e==="audio")}function eC(i){return i.some(({type:e})=>e==="video"||e==="image")}function tC(i){return i.type==="audio"}const iC=(((Rh=_h)==null?void 0:Rh.default)??_h).reduce((i,e)=>(i[e.name]=e,i),{});function rC(i,e){return i.has(e)||i.set(e,{buffer:null,transitions:{},fromTexture:null,toTexture:null}),i.get(e)}function nC({name:i,to:e,from:t,progress:r,width:n,height:s,glContext:o,contextResources:a,returnPixels:c=!0}){var l,u,A;const h=rC(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=(((l=no)==null?void 0:l.default)??no)(o,t),h.fromTexture.minFilter=o.LINEAR,h.fromTexture.magFilter=o.LINEAR),h.toTexture?h.toTexture.setPixels(e):(h.toTexture=(((u=no)==null?void 0:u.default)??no)(o,e),h.toTexture.minFilter=o.LINEAR,h.toTexture.magFilter=o.LINEAR),h.transitions[i]||(h.transitions[i]=(((A=wh)==null?void 0:A.default)??wh)(o,iC[i])),h.transitions[i].draw(r,h.fromTexture,h.toTexture,n,s),!c)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 sC(i){for(const[e,t]of i.entries())t.buffer&&e.deleteBuffer(t.buffer),t.fromTexture&&t.fromTexture.dispose(),t.toTexture&&t.toTexture.dispose(),Object.values(t.transitions).forEach(r=>{r.dispose()}),i.delete(e)}function oC({name:i,to:e,from:t,progress:r,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),nC({name:i,to:e,from:t,progress:r,width:n.width,height:n.height,glContext:o,contextResources:s,returnPixels:!1}))}async function od({debug:i=!1,config:e,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s=td,drawTransition:o=oC}){const a=new Map,c=await Promise.all(e.tracks.map(async A=>{if(eC(A))return{...await Jy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(Xy(A))return{...await jy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(zy(A))return{...await qy({debug:i,track:A,resolvers:t,rootWidth:r,rootHeight:n,canvasFactory:s}),config:A};if(Zy(A))return{...await Ky({track:A}),config:A};throw new Error("Unknown track type")}));return{draw:async({canvas:A,currentTime:h})=>{const d=A.getContext("2d");if(d){d.globalAlpha=1,d.globalCompositeOperation="source-over",d.clearRect(0,0,A.width,A.height),d.save(),d.fillStyle="black",d.fillRect(0,0,A.width,A.height),d.restore();for await(const f of c){if(tC(f))continue;const{scenes:g,transitions:p,trackCanvas:v}=f;v.width=v.height=0,v.width=A.width,v.height=A.height;const B=v.getContext("2d"),C=g.filter(({start:x,duration:_})=>h>=x&&h<x+_);if(!B||C.length<=0)continue;const y=p.find(({start:x,duration:_})=>h>=x&&h<x+_);for await(const{sceneCanvas:x,draw:_}of C)await(_==null?void 0:_(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:_,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-_.start)/F));await o({name:x,progress:M,contextResources:a,to:_.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:()=>{sC(a)},tracks:c,aspectRatio:e.aspectRatio,transcriptions:e.transcriptions,duration:Math.max(...c.map(({duration:A})=>A))}}const aC={version:"7.0.2"};function lC(i){const{publicApiUrl:e}=Ms(i),t=Ki();return navigator.sendBeacon(`${e}/api/visitor`,JSON.stringify({visitorId:t})),t}function cC(i){var s,o,a,c,l,u,A,h,d,f,g,p;if(typeof window>"u")return{client:null,tab:null,request:Ki()};let e=(o=(s=window.localStorage)==null?void 0:s.getItem)==null?void 0:o.call(s,"vouch-uid-visitor"),t=(c=(a=window.localStorage)==null?void 0:a.getItem)==null?void 0:c.call(a,"vouch-uid-client"),r=(u=(l=window.sessionStorage)==null?void 0:l.getItem)==null?void 0:u.call(l,"vouch-uid-tab");const n=Ki();return e||(e=lC(i),(h=(A=window.localStorage)==null?void 0:A.setItem)==null||h.call(A,"vouch-uid-visitor",e)),t||(t=Ki(),(f=(d=window.localStorage)==null?void 0:d.setItem)==null||f.call(d,"vouch-uid-client",t)),r||(r=Ki(),(p=(g=window.sessionStorage)==null?void 0:g.setItem)==null||p.call(g,"vouch-uid-tab",r)),{client:t,tab:r,request:n,visitor:e}}function AC(i,e){return i&&"vouchId"in i?i.vouchId:(e==null?void 0:e.id)??null}function uC(i="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,"/"))??[],r={};return[...new URLSearchParams(location.search).entries()].forEach(([o,a])=>{if(/utm/.test(o)){const c=o.toLowerCase().replace(/[-_][a-z0-9]/g,l=>l.slice(-1).toUpperCase());r[c]=a}}),{source:i,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:aC.version,templateVersion:Yy,...r}}const ad=1;class hC{constructor(e){this._batchedEvents=[],this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamStartTime={},this._streamLatestTime={},this._currentlyPlayingVideo=null,this._createTrackingEvent=(t,r)=>{const n=AC(r,this.host.vouch);!n||this.host.disableTracking||this._batchedEvents.push({event:t,payload:{...r,senderId:this.host.senderId,vouchId:n,time:new Date().toISOString()}})},this._sendTrackingEvent=()=>{if(this._batchedEvents.length<=0)return;const{publicApiUrl:t}=Ms(this.host.env),{client:r,tab:n,request:s,visitor:o}=cC(this.host.env);navigator.sendBeacon(`${t}/api/batchevents`,JSON.stringify({payload:{events:this._batchedEvents},context:{"x-uid-client":r,"x-uid-tab":n,"x-uid-request":s,"x-uid-visitor":o,"x-reporting-metadata":uC(this.host.trackingSource)}})),this._batchedEvents=[]},this._streamEnded=()=>{if(this._currentlyPlayingVideo){const{id:t,key:r}=this._currentlyPlayingVideo;this._streamLatestTime[r]>this._streamStartTime[r]+ad&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[r],streamEnd:this._streamLatestTime[r]}),delete this._streamStartTime[r],delete this._streamLatestTime[r]}},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:r}})=>{this._answersViewed[r]||(this._createTrackingEvent("VOUCH_RESPONSE_VIEWED",{answerId:t}),this._answersViewed[r]=!0)},this._handleVideoTimeUpdate=({detail:{id:t,key:r,node:n}})=>{this.host.paused||(this._currentlyPlayingVideo={id:t,key:r,node:n},this._streamLatestTime[r]=n.currentTime,this._streamStartTime[r]||(this._streamStartTime[r]=n.currentTime,this._streamLatestTime[r]=n.currentTime))},this._handleVideoPause=({detail:{id:t,key:r}})=>{this._streamLatestTime[r]>this._streamStartTime[r]+ad&&this._createTrackingEvent("VIDEO_STREAMED",{answerId:t,streamStart:this._streamStartTime[r],streamEnd:this._streamLatestTime[r]}),delete this._streamStartTime[r],delete this._streamLatestTime[r]},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,r,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),(r=this.host.mediaPlayer)==null||r.addEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var e,t,r,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),(r=this.host.mediaPlayer)==null||r.removeEventListener("video:pause",this._handleVideoPause),(n=this.host.mediaPlayer)==null||n.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var Sl={exports:{}};(function(i,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ji<"u"&&Ji,r=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 Ji<"u"&&Ji||{},c={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 l(L){return L&&DataView.prototype.isPrototypeOf(L)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],A=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 c.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)},c.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),w=R?R[1]:"utf-8";return U.readAsText(L,w),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 _(){return this.bodyUsed=!1,this._initBody=function(L){this.bodyUsed=this.bodyUsed,this._bodyInit=L,L?typeof L=="string"?this._bodyText=L:c.blob&&Blob.prototype.isPrototypeOf(L)?this._bodyBlob=L:c.formData&&FormData.prototype.isPrototypeOf(L)?this._bodyFormData=L:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)?this._bodyText=L.toString():c.arrayBuffer&&c.blob&&l(L)?(this._bodyArrayBuffer=x(L.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(L)||A(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):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(L)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.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(c.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)},c.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 w=/\?/;this.url+=(w.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("="),w=R.shift().replace(/\+/g," "),k=R.join("=").replace(/\+/g," ");U.append(decodeURIComponent(w),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 w=R.split(":"),k=w.shift().trim();if(k){var K=w.join(":").trim();try{U.append(k,K)}catch(Y){console.warn("Response "+Y.message)}}}),U}_.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)}_.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 w=new O(L,U);if(w.signal&&w.signal.aborted)return R(new o.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function K(){k.abort()}k.onload=function(){var re={statusText:k.statusText,headers:j(k.getAllResponseHeaders()||"")};w.url.indexOf("file://")===0&&(k.status<200||k.status>599)?re.status=200:re.status=k.status,re.url="responseURL"in k?k.responseURL:re.headers.get("X-Request-URL");var he="response"in k?k.response:k.responseText;setTimeout(function(){q(new X(he,re))},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(re){try{return re===""&&a.location.href?a.location.href:re}catch{return re}}if(k.open(w.method,Y(w.url),!0),w.credentials==="include"?k.withCredentials=!0:w.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(c.blob?k.responseType="blob":c.arrayBuffer&&(k.responseType="arraybuffer")),U&&typeof U.headers=="object"&&!(U.headers instanceof g||a.Headers&&U.headers instanceof a.Headers)){var ie=[];Object.getOwnPropertyNames(U.headers).forEach(function(re){ie.push(h(re)),k.setRequestHeader(re,d(U.headers[re]))}),w.headers.forEach(function(re,he){ie.indexOf(he)===-1&&k.setRequestHeader(he,re)})}else w.headers.forEach(function(re,he){k.setRequestHeader(he,re)});w.signal&&(w.signal.addEventListener("abort",K),k.onreadystatechange=function(){k.readyState===4&&w.signal.removeEventListener("abort",K)}),k.send(typeof w._bodyInit>"u"?null:w._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})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var n=t.fetch?t:r;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,i.exports=e})(Sl,Sl.exports);var dC=Sl.exports;const ld=Ya(dC);async function fC(i){var e;try{if((e=await ld(i,{method:"HEAD"}))!=null&&e.ok)return i}catch{return}}async function xl({sources:i}){const e=i==null?void 0:i.filter(Boolean),t=e==null?void 0:e.find(s=>s.startsWith("blob:")),r=e==null?void 0:e.find(s=>!s.startsWith("http")&&!s.startsWith("blob:"));if(t||r)return t??r;let n=e[0];if(e.length>0){const s=e.map(a=>fC(a)),o=(await Promise.all(s)).find(Boolean);o&&(n=o)}return n}async function gC(i){try{return(await ld(i)).text()}catch{return null}}async function pC(i){return i=i.trim(),i.startsWith("http")||i.startsWith("blob:")?gC(i):i}const mC=Ir(async({original:i,translation:e,originalLanguage:t="",translationLanguage:r=""},{language:n})=>{var s,o;const a={[(s=r==null?void 0:r.split("-"))==null?void 0:s[0]]:e,[(o=t==null?void 0:t.split("-"))==null?void 0:o[0]]:i},c=(n&&a[n])??i;return c?pC(c):null},{cacheKey:([i,{language:e}])=>JSON.stringify({...i,language:e})});function EC(i){var e;return((e=i==null?void 0:i.items)==null?void 0:e.map(t=>{var r;return{text:(r=t.alternatives[0])==null?void 0:r.content,start:t.start_time,end:t.end_time}}))??[]}const IC=Ir(async i=>{var e,t,r,n,s,o,a,c,l,u,A;const[h,d,f]=await Promise.all([xl({sources:[(t=(e=i==null?void 0:i.answer)==null?void 0:e.media)==null?void 0:t.video,(n=(r=i==null?void 0:i.answer)==null?void 0:r.media)==null?void 0:n.input]}),xl({sources:[(o=(s=i==null?void 0:i.answer)==null?void 0:s.media)==null?void 0:o.playlist]}),xl({sources:[((c=(a=i==null?void 0:i.answer)==null?void 0:a.media)==null?void 0:c.reducedQuality)??((A=(u=(l=i==null?void 0:i.answer)==null?void 0:l.media)==null?void 0:u.videos)==null?void 0:A.xs)]})]);return{src:h,playlist:d,preview:f}},{cacheKey:([i])=>{var e,t,r,n,s,o,a,c,l,u,A;return JSON.stringify({video:(t=(e=i==null?void 0:i.answer)==null?void 0:e.media)==null?void 0:t.video,input:(n=(r=i==null?void 0:i.answer)==null?void 0:r.media)==null?void 0:n.input,playlist:(o=(s=i==null?void 0:i.answer)==null?void 0:s.media)==null?void 0:o.playlist,preview:((c=(a=i==null?void 0:i.answer)==null?void 0:a.media)==null?void 0:c.reducedQuality)??((A=(u=(l=i==null?void 0:i.answer)==null?void 0:l.media)==null?void 0:u.videos)==null?void 0:A.xs)})}});function cd(i){var e,t,r,n,s,o,a,c,l,u,A,h;const d=((t=(e=i==null?void 0:i.answer)==null?void 0:e.contact)==null?void 0:t.name)==="Anonymous"?"":((s=(n=(r=i==null?void 0:i.answer)==null?void 0:r.contact)==null?void 0:n.name)==null?void 0:s.trim())??"",f=((c=(a=(o=i==null?void 0:i.answer)==null?void 0:o.contact)==null?void 0:a.client)==null?void 0:c.name)==="Not Supplied"?"":((h=(A=(u=(l=i==null?void 0:i.answer)==null?void 0:l.contact)==null?void 0:u.client)==null?void 0:A.name)==null?void 0:h.trim())??"",[g,p]=d.split(" ");return{name:d,firstName:g,lastName:p,companyName:f}}function vC(i){var e,t;const r=(t=(e=i==null?void 0:i.answer)==null?void 0:e.contact)==null?void 0:t.roleTitle,n=r==null?void 0:r.split(" ");return{roleTitle:r,roleWords:n,firstRoleWord:n==null?void 0:n[0],remainingRoleWords:n==null?void 0:n.slice(1).join(" ")}}async function yC(i,e,t){var r,n,s;const o=(r=e==null?void 0:e.answer)==null?void 0:r.id;return((s=(n=i==null?void 0:i.questions)==null?void 0:n.items)==null?void 0:s.reduce((c,l)=>{var u;return((u=l==null?void 0:l.answer)==null?void 0:u.id)===o?(c??0)+1:c},0))<=1?o:`${o}-${t}`}async function Ql({data:i,rootData:e,index:t},r){var n,s,o,a,c,l,u,A,h,d,f,g,p,v,B,C,y,x,_,D,F,O,M,j;const[X,le,oe]=await Promise.all([yC(i,e,t),IC(e),mC({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:((l=(c=e==null?void 0:e.answer)==null?void 0:c.media)==null?void 0:l.translation)??((A=(u=e==null?void 0:e.answer)==null?void 0:u.captions)==null?void 0:A.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},r)]),L=cd(e),U=vC(e);return{...le,...L,...U,key:X,captions:oe,wordTimings:EC((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?((_=(x=(y=(C=i==null?void 0:i.questions)==null?void 0:C.items)==null?void 0:y[t-1])==null?void 0:x.answer)==null?void 0:_.label)??((O=(F=(D=i==null?void 0:i.questions)==null?void 0:D.items)==null?void 0:F[t-1])==null?void 0:O.title)??null:null,isFirstInstanceOfName:t?((j=(M=i==null?void 0:i.questions)==null?void 0:M.items)==null?void 0:j.findIndex(q=>cd(q).name===L.name))===t:!0}}const po={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 CC({data:i}){var e,t;return((t=(e=i==null?void 0:i.questions)==null?void 0:e.items)==null?void 0:t.reduce((r,n)=>{var s,o,a,c,l,u,A;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=(A=(u=(l=(c=n==null?void 0:n.answer)==null?void 0:c.transcription)==null?void 0:l.translation)==null?void 0:u.language)==null?void 0:A.split("-")[0];return h&&po[h]&&!r.find(f=>f.value===h)&&r.push({value:h,label:po[h]}),d&&po[d]&&!r.find(f=>f.value===d)&&r.push({value:d,label:po[d]}),r},[]))??[]}/**
2478
2478
  * @license
2479
2479
  * Copyright 2018 Google LLC
@@ -2492,12 +2492,12 @@ 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 ie=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===k&&k>0){const re=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: ${re.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,re,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>w*2?ie():this.timer=self.setInterval(ie,w*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 SC(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 r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var n;this.fragCurrent=r,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 r=t.frag,{fragCurrent:n,partCurrent:s}=this;if(r&&n&&r.sn===n.sn&&r.level===n.level){const o=performance.now(),a=s?s.stats:r.stats,c=o-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const A=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(A,l),a.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,r,n){const s=e+r/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.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=r?r.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:c},o.realBitrate=Math.round(8*a/c)}if(t.bitrateTest){const s={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:r.stats;if(s.aborted||this.ignoreFragment(r))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(),r.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,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,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,r=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=r&&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:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=r,a=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let u=s.abrBandWidthFactor,A=s.abrBandWidthUpFactor;if(l){const p=this.findBestLevel(c,o,n,l,0,u,A);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){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=A=1)}const d=this.findBestLevel(c,o,n,l,h,u,A);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=r.levels[o],g=r.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,s,o,a){var c;const l=n+s,u=this.lastLoadedFragLevel,A=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[A],C=!!((c=this.hls.latestLevelDetails)!=null&&c.live),y=p===-1||u===-1;let x,_="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=Nd(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=dB(f,M,t,r)),q=hB(U,_,e,F,O),{codecSet:R,videoRanges:w,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:ie}=q;j=Y,x=R,_=ie?w[w.length-1]:w[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${it(q)}`)}else x=B==null?void 0:B.codecSet,_=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=r;U>=t;U--){var L;const q=f[U],R=U>A;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(sB(q,M,_,D,e,F)||vo(q.videoCodec))?(q.supportedPromise=kd(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const we=this.hls.levels,be=we.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${be} ${it(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${be} ${it(fe)}`),be>-1&&we.length>1&&(this.log(`Removing unsupported level ${be}`),this.hls.removeLevel(be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=Rd}if((x&&q.codecSet!==x||_&&q.videoRange!==_||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 w=q.details,k=(d?w==null?void 0:w.partTarget:w==null?void 0:w.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,ie=this.getTimeToLoadFrag(le,K,Y*k,w===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(ie<=le||!de(ie)||C&&!this.bitrateTestDelay||ie<l)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${_}`),this.info(`switch candidate:${A}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${ie.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:r}=this.hls;return Math.min(Math.max(e,r),t)}}const Gl={search:function(i,e){let t=0,r=i.length-1,n=null,s=null;for(;t<=r;){n=(t+r)/2|0,s=i[n];const o=e(s);if(o>0)t=n+1;else if(o<0)r=n-1;else return s}return null}};function EB(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!de(e))return null;const r=i[0].programDateTime;if(e<(r||0))return null;const n=i[i.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<i.length;++s){const o=i[s];if(vB(e,t,o))return o}return null}function br(i,e,t=0,r=0,n=.005){let s=null;if(i){s=e[1+i.sn-e[0].sn]||null;const a=i.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&i.level!==s.level&&s.end<=i.end&&(s=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!i||i.level===s.level)&&Gd(t,r,s)===0||IB(s,i,Math.min(n,r))))return s;const o=Gl.search(e,Gd.bind(null,t,r));return o&&(o!==i||!s)?o:s}function IB(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return i.start<=r}return!1}function Gd(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-r<=i?1:t.start-r>i&&t.start?-1:0}function vB(i,e,t){const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-r>i}function $d(i,e){return Gl.search(i,t=>t.cc<e?1:t.cc>e?-1:0)}function yB(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){const r=t.start,n=t.end;let s=i.fragments;if(!t.relurl){const{fragmentHint:o}=i;o&&(s=s.concat(o))}return Gl.search(s,o=>o.cc<e||o.end<=r?1:o.cc>e||o.start>=n?-1:0)}return null}function xo(i){switch(i.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(i,e){const t=xo(e);return i.default[`${t?"timeout":"error"}Retry`]}function $l(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function Yd(i){return Ye(Ye({},i),{errorRetry:null,timeoutRetry:null})}function Qo(i,e,t,r){if(!i)return!1;const n=r==null?void 0:r.code,s=e<i.maxNumRetry&&(CB(n)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,r,s):s}function CB(i){return i===0&&navigator.onLine===!1||!!i&&(i<400||i>499)}var Dt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},si={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class BB extends _i{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 r;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((r=t.frag)!=null&&r.gap){t.errorAction=qn();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Dt.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const l=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,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}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 l=n.loadLevelObj;if(l&&(s.type===Me.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Dt.SendAlternateToPenaltyBox,t.errorAction.flags=si.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=n.loadLevelObj,u=l==null?void 0:l.attrs["HDCP-LEVEL"];u?t.errorAction={action:Dt.SendAlternateToPenaltyBox,flags:si.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 c;t.errorAction=this.getLevelSwitchAction(t,(c=t.level)!=null?c: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=qn();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 r=this.hls,n=Hd(r.config.playlistLoadPolicy,e),s=this.playlistError++;if(Qo(n,s,xo(e),e.response))return{action:Dt.RetryRequest,flags:si.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,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=Hd(e.details.startsWith("key")?o:s,e),c=t.levels.reduce((u,A)=>u+A.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,Qo(a,c,xo(e),e.response)))return{action:Dt.RetryRequest,flags:si.None,retryConfig:a,retryCount:c};const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=c),l}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const l=e.details;n.loadError++,l===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:A,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=r;r.autoLevelEnabled||(r.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&l===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===V.BUFFER_ADD_CODEC_ERROR||l===V.BUFFER_APPEND_ERROR))&&A.some(({audioCodec:_})=>n.audioCodec!==_),C=e.sourceBufferName==="video"&&(l===V.BUFFER_ADD_CODEC_ERROR||l===V.BUFFER_APPEND_ERROR)&&A.some(({codecSet:_,audioCodec:D})=>n.codecSet!==_&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let _=A.length;_--;){const D=(_+h)%A.length;if(D!==h&&D>=d&&D<=f&&A[D].loadError===0){var a,c;const F=A[D];if(l===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=A[D].details;if(O){const M=br(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&&(c=n.subtitleGroups)!=null&&c.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&&r.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Dt.SendAlternateToPenaltyBox,flags:si.None,nextAutoLevel:u}}return{action:Dt.SendAlternateToPenaltyBox,flags:si.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case Dt.DoNothing:break;case Dt.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,r=e.errorAction;if(!r)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=r;switch(n){case si.None:this.switchLevel(e,o);break;case si.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=Ul[Ul.indexOf(s)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}r.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 r=_d(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===r&&this.hls.removeLevel(s)}}}function qn(i){const e={action:Dt.DoNothing,flags:si.None};return i&&(e.resolved=!0),e}var It={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class TB{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 r=this.activePartLists[t];if(r)for(let n=r.length;n--;){const s=r[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,r){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&&(!r||a.buffered)){const c=a.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,r,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 c=this.fragments[a];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||s)){c.body.type===r&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(u=>{const A=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return A&&this.removeFragment(c.body),A})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,n=Vr(r),s=this.fragments[n];if(!s||s.buffered&&r.gap)return;const o=!r.relurl;Object.keys(t).forEach(a=>{const c=r.elementaryStreams[a];if(!c)return;const l=t[a],u=o||c.partial===!0;s.range[a]=this.getBufferedTimes(r,e.part,u,l)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=r.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),wo(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=Vd(r,n=>n.fragment.sn>=e))}fragBuffered(e,t){const r=Vr(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={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,r,n){const s={time:[],partial:r},o=e.start,a=e.end,c=e.minEndPTS||a,l=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const A=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(l>=A&&c<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>A){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<=A)break}return s}getPartialFragment(e){let t=null,r,n,s,o=0;const{bufferPadding:a,fragments:c}=this;return Object.keys(c).forEach(l=>{const u=c[l];u&&wo(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(r=Math.min(e-n,s-e),o<=r&&(t=u.body,o=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||wo(t))}getState(e){const t=Vr(e),r=this.fragments[t];return r?r.buffered?wo(r)?It.PARTIAL:It.OK:It.APPENDING:It.NOT_LOADED}isTimeBuffered(e,t,r){let n,s;for(let o=0;o<r.length;o++){if(n=r.start(o)-this.bufferPadding,s=r.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 r=t.frag,n=t.part?null:t,s=Vr(r);this.fragments[s]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s,type:o}=t;if(r.sn==="initSegment")return;const a=r.type;if(n){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(n)}this.timeRanges=s;const c=s[o];this.detectEvictedFragments(o,c,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Vr(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const s=t[r[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,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const c=a.body;c.type!==r||n&&!c.gap||c.start<t&&c.end>e&&(a.buffered||s)&&this.removeFragment(c)})}removeFragment(e){const t=Vr(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const n=e.sn;this.activePartLists[e.type]=Vd(r,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 r=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function wo(i){var e,t,r;return i.buffered&&(i.body.gap||((e=i.range.video)==null?void 0:e.partial)||((t=i.range.audio)==null?void 0:t.partial)||((r=i.range.audiovideo)==null?void 0:r.partial))}function Vr(i){return`${i.type}_${i.level}_${i.sn}`}function Vd(i,e){return i.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}var tr={cbc:0,ctr:1};class bB{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case tr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tr.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 SB(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class xB{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),r=new Uint32Array(4);for(let n=0;n<4;n++)r[n]=t.getUint32(n*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],o=r[2],a=r[3],c=this.invSubMix,l=c[0],u=c[1],A=c[2],h=c[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,l[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,A[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 r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)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,c;const l=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),A=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=l[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=A[C>>>24]<<24|A[C>>>16&255]<<16|A[C>>>8&255]<<8|A[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=A[C>>>24]<<24|A[C>>>16&255]<<16|A[C>>>8&255]<<8|A[C&255]),l[a]=B=(l[a-s]^C)>>>0}for(c=0;c<o;c++)a=o-c,c&3?C=l[a]:C=l[a-4],c<4||a<=4?u[c]=C:u[c]=f[A[C>>>24]]^g[A[C>>>16&255]]^p[A[C>>>8&255]]^v[A[C&255]],u[c]=u[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,c=a[0],l=a[1],u=a[2],A=a[3],h=this.uint8ArrayToUint32Array_(r);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,_,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=c[D>>>24]^l[F>>16&255]^u[O>>8&255]^A[M&255]^s[L],y=c[F>>>24]^l[O>>16&255]^u[M>>8&255]^A[D&255]^s[L+1],x=c[O>>>24]^l[M>>16&255]^u[D>>8&255]^A[F&255]^s[L+2],_=c[M>>>24]^l[D>>16&255]^u[F>>8&255]^A[O&255]^s[L+3],D=C,F=y,O=x,M=_,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],_=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(_^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 QB{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=wB(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function wB(i){switch(i){case tr.cbc:return"AES-CBC";case tr.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const _B=16;class Hl{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 r=self.crypto;r&&(this.subtle=r.subtle||r.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 r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?SB(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,n);const c=this.flush();c?s(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==tr.cbc||t.byteLength!==16)return Oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=jt(a,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xB),l.expandKey(t);const u=o;return this.currentResult=l.decrypt(c.buffer,0,r),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new QB(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bB(this.subtle,new Uint8Array(r),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,r,n)))}onWebCryptoError(e,t,r,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,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 r=e.length-e.length%_B;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Kd=Math.pow(2,17);class RB{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 r=e.url;if(!r)return Promise.reject(new Ri({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(qd(e));return}else e.gap=!1;const l=this.loader=s?new s(n):new o(n),u=Wd(e);e.loader=l;const A=Yd(n.fragLoadPolicy.default),h={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kd};e.stats=l.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,l);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,l),c(new Ri({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ye({url:r,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,l),c(new Ri({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,l),c(new Ri({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})),l.load(u,h,d)})}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(qd(e,t));return}const l=this.loader=s?new s(n):new o(n),u=Wd(e,t);e.loader=l;const A=Yd(n.fragLoadPolicy.default),h={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kd};t.stats=l.stats,l.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};r(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,l),c(new Ri({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,l),c(new Ri({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,l),c(new Ri({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 r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(r.loaded/s),c),A=(c-l)*Math.round(r.loaded/l);r.total=r.loaded+A}else r.total=Math.max(r.loaded,r.total);const o=r.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 Wd(i,e=null){const t=e||i,r={frag:i,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,c=s;if(i.sn==="initSegment"&&DB((o=i.decryptdata)==null?void 0:o.method)){const l=s-n;l%16&&(c=s+(16-l%16)),n!==0&&(r.resetIV=!0,a=n-16)}r.rangeStart=a,r.rangeEnd=c}return r}function qd(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),r={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(r.part=e),(e||i).stats.aborted=!0,new Ri(r)}function DB(i){return i==="AES-128"||i==="AES-256"}class Ri extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Jd extends _i{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 Yl{constructor(e,t,r,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=_o(),this.buffering={audio:_o(),video:_o(),audiovideo:_o()},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=o}}function _o(){return{start:0,executeStart:0,executeEnd:0,end:0}}const jd={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const r=Le.getBuffered(e);for(let n=r.length;n--;)if(t>=r.start(n)&&t<=r.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 r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((u,A)=>u.start-A.start||A.end-u.end);let n=-1,s=[];if(r)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const A=s.length;if(A){const h=s[A-1].end;e[u].start-h<r?e[u].end>h&&(s[A-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,c=t,l=t;for(let u=0;u<s.length;u++){const A=s[u].start,h=s[u].end;if(n===-1&&t>=A&&t<=h&&(n=u),t+r>=A&&t<h)c=A,l=h,o=l-t;else if(t+r<A){a=A;break}}return{len:o,start:c||0,end:l||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||jd}catch(t){return Oe.log("failed to get media.buffered",t),jd}}}const Xd=/\{\$([a-zA-Z0-9-_]+)\}/g;function zd(i){return Xd.test(i)}function Vl(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(Xd,r=>{const n=r.substring(2,r.length-1),s=t==null?void 0:t[n];return s===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),r):s})}return e}function Zd(i,e,t){let r=i.variableList;r||(i.variableList=r={});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){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in r?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):r[n]=s||""}function LB(i,e,t){const r=e.IMPORT;if(t&&r in t){let n=i.variableList;n||(i.variableList=n={}),n[r]=t[r]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const kB=/^(\d+)x(\d+)$/,ef=/(.+?)=(".*?"|.*?)(?:,|$)/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 r=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}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 r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=kB.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const n={},s='"';for(ef.lastIndex=0;(r=ef.exec(e))!==null;){const o=r[1].trim();let a=r[2];const c=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let l=!1;if(c)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))a=Vl(t,a);else if(!l&&!c)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 MB="com.apple.hls.interstitial";function FB(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function PB(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class tf{constructor(e,t,r=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:r,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===MB}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 NB=10;class OB{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,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>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||NB}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 r=e.length;r--;)if(e[r].index>t)return e[r].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 Kr(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Kl(i){switch(i){case"AES-128":case"AES-256":return tr.cbc;case"AES-256-CTR":return tr.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Wl(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function ql(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function UB(i){const e=ql(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function GB(i){const e=function(r,n,s){const o=r[n];r[n]=r[s],r[s]=o};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function $B(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),n=r[r.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(r.splice(-1,1),t=Wl(o)):t=UB(o)}}return t}const Ro=typeof self<"u"?self:void 0;var Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Nt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Jl(i){switch(i){case Nt.FAIRPLAY:return Ve.FAIRPLAY;case Nt.PLAYREADY:return Ve.PLAYREADY;case Nt.WIDEVINE:return Ve.WIDEVINE;case Nt.CLEARKEY:return Ve.CLEARKEY}}var Do={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function jl(i){if(i===Do.WIDEVINE)return Ve.WIDEVINE;if(i===Do.PLAYREADY)return Ve.PLAYREADY;if(i===Do.CENC||i===Do.CLEARKEY)return Ve.CLEARKEY}function Xl(i){switch(i){case Ve.FAIRPLAY:return Nt.FAIRPLAY;case Ve.PLAYREADY:return Nt.PLAYREADY;case Ve.WIDEVINE:return Nt.WIDEVINE;case Ve.CLEARKEY:return Nt.CLEARKEY}}function Lo(i){const{drmSystems:e,widevineLicenseUrl:t}=i,r=e?[Ve.FAIRPLAY,Ve.WIDEVINE,Ve.PLAYREADY,Ve.CLEARKEY].filter(n=>!!e[n]):[];return!r[Ve.WIDEVINE]&&t&&r.push(Ve.WIDEVINE),r}const rf=function(i){return Ro!=null&&(i=Ro.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function HB(i,e,t,r){let n;switch(i){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: ${i}`)}return YB(n,e,t,r)}function YB(i,e,t,r){return[{initDataTypes:i,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function VB(i){var e;return i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function nf(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),r=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const c=Wl(a).subarray(0,16);return GB(c),c}}return null}let ko={};class Jn{static clearKeyUriToKeyIdMap(){ko={}}constructor(e,t,r,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=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Kr(e)}isSupported(){if(this.method){if(Kr(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Nt.FAIRPLAY:case Nt.WIDEVINE:case Nt.PLAYREADY:case Nt.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(Kr(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 r=KB(e);return new Jn(this.method,this.uri,"identity",this.keyFormatVersions,r)}const t=$B(this.uri);if(t)switch(this.keyFormat){case Nt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Nt.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=XC(r,null,t),this.keyId=nf(t);break}default:{let r=t.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r=ko[this.uri];if(!r){const n=Object.keys(ko).length%Number.MAX_SAFE_INTEGER;r=new Uint8Array(16),new DataView(r.buffer,12,4).setUint32(0,n),ko[this.uri]=r}this.keyId=r}return this}}function KB(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const sf=/#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,of=/#EXT-X-MEDIA:(.*)/g,WB=/^#EXT(?:INF|-X-TARGETDURATION):/m,zl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),qB=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 mi{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static resolve(e,t){return Dl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return WB.test(e)}static parseMasterPlaylist(e,t){const r=zd(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},s=[];sf.lastIndex=0;let o;for(;(o=sf.exec(e))!=null;)if(o[1]){var a;const l=new st(o[1],n),u=Vl(n,o[2]),A={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:mi.resolve(u,t)},h=l.decimalResolution("RESOLUTION");h&&(A.width=h.width,A.height=h.height),Af(l.CODECS,A);const d=l["SUPPLEMENTAL-CODECS"];d&&(A.supplemental={},Af(d,A.supplemental)),(a=A.unknownCodecs)!=null&&a.length||s.push(A),n.levels.push(A)}else if(o[3]){const l=o[3],u=o[4];switch(l){case"SESSION-DATA":{const A=new st(u,n),h=A["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=A);break}case"SESSION-KEY":{const A=lf(u,t,n);A.encrypted&&A.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(A)):Oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const A=new st(u,n);Zd(n,A,t)}break}case"CONTENT-STEERING":{const A=new st(u,n);n.contentSteering={uri:mi.resolve(A["SERVER-URI"],t),pathwayId:A["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=cf(u);break}}}const c=s.length>0&&s.length<n.levels.length;return n.levels=c?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,r){let n;const s={},o=r.levels,a={AUDIO:o.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:o.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(of.lastIndex=0;(n=of.exec(e))!==null;){const l=new st(n[1],r),u=l.TYPE;if(u){const A=a[u],h=s[u]||[];s[u]=h;const d=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],g=l.CHANNELS,p=l.CHARACTERISTICS,v=l["INSTREAM-ID"],B={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||d||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:d,url:l.URI?mi.resolve(l.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),A!=null&&A.length){const C=mi.findGroup(A,B.groupId)||A[0];uf(B,C,"audioCodec"),uf(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,r,n,s,o){var a;const c={url:t},l=new OB(t),u=l.fragments,A=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new kl(n,c),y,x,_,D=-1,F=!1,O=null,M;if(zl.lastIndex=0,l.m3u8=e,l.hasVariableRefs=zd(e),((a=zl.exec(e))==null?void 0:a[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(y=zl.exec(e))!==null;){F&&(F=!1,C=new kl(n,c),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=r,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,_&&df(C,_,l),C.sn=d,C.level=r,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=Vl(l,L),Zl(C,B,A),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(qB),!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":l.type&&Di(l,L,y),l.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Di(l,L,y):u.length>0&&ff(l,L,y),d=l.startSN=parseInt(U);break;case"SKIP":{l.skippedSegments&&Di(l,L,y);const R=new st(U,l),w=R.decimalInteger("SKIPPED-SEGMENTS");if(de(w)){l.skippedSegments+=w;for(let K=w;K--;)u.push(null);d+=w}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Di(l,L,y),l.targetduration=Math.max(parseInt(U),1);break;case"VERSION":l.version!==null&&Di(l,L,y),l.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Di(l,L,y),l.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,l),w=new tf(R,l.dateRanges[R.ID],l.dateRangeTagCount);l.dateRangeTagCount++,w.isValid||l.skippedSegments?l.dateRanges[w.id]=w:Oe.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new st(U,l);"IMPORT"in R?LB(l,R,o):Zd(l,R,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Di(l,L,y):u.length>0&&ff(l,L,y),l.startCC=p=parseInt(U);break;case"KEY":{const R=lf(U,t,l);if(R.isSupported()){if(R.method==="NONE"){_=void 0;break}_||(_={}),_[R.keyFormat]&&(_=We({},_)),_[R.keyFormat]=R}else Oe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":l.startTimeOffset=cf(U);break;case"MAP":{const R=new st(U,l);if(C.duration){const w=new kl(n,c);hf(w,R,r,_),h=w,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const w=C.byteRangeEndOffset;if(w){const k=C.byteRangeStartOffset;O=`${w-k}@${k}`}else O=null;hf(C,R,r,_),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&Di(l,L,y),M=new st(U),l.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),l.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Di(l,L,y);const R=new st(U);l.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=l.partList;R||(R=l.partList=[]);const w=f>0?R[R.length-1]:void 0,k=f++,K=new st(U,l),Y=new FC(K,C,c,k,w);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new st(U,l);l.preloadHint=R;break}case"RENDITION-REPORT":{const R=new st(U,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(R);break}default:Oe.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,l.partList&&(l.fragmentHint=B)):l.partList&&(Zl(C,B,A),C.cc=p,l.fragmentHint=C,_&&df(C,_,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=l.skippedSegments*l.targetduration,g>0&&j&&le){l.averagetargetduration=g/j;const oe=le.sn;l.endSN=oe!=="initSegment"?oe:0,l.live||(le.endList=!0),X&&l.startCC===void 0&&(l.startCC=X.cc),D>0&&(jB(u,D),X&&A.unshift(X))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(g+=l.fragmentHint.duration),l.totalduration=g,A.length&&l.dateRangeTagCount&&X&&af(A,l),l.endCC=p,l}}function af(i,e){const t=i.length,r=i[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]],c=a.startDate.getTime();a.tagAnchor=r.ref;for(let l=t;l--;){const u=JB(e,c,i,l,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function JB(i,e,t,r,n){const s=t[r];if(s){const a=s.programDateTime;if(e>=a||r===0){var o;const c=(((o=t[r+1])==null?void 0:o.start)||n)-s.start;if(e<=a+c*1e3){const l=t[r].sn-i.startSN,u=i.fragments;if(u.length>t.length){const h=(t[r+1]||u[u.length-1]).sn-i.startSN;for(let d=h;d>l;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return l}}}return-1}function lf(i,e,t){var r,n;const s=new st(i,t),o=(r=s.METHOD)!=null?r:"",a=s.URI,c=s.hexadecimalInteger("IV"),l=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!c&&Oe.error(`Invalid IV: ${s.IV}`);const A=a?mi.resolve(a,e):"",h=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Jn(o,A,u,h,c)}function cf(i){const t=new st(i).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Af(i,e){let t=(i||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const n=t.filter(s=>Sd(s,r));n.length&&(e[`${r}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function uf(i,e,t){const r=e[t];r&&(i[t]=r)}function jB(i,e){let t=i[e];for(let r=e;r--;){const n=i[r];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Zl(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function hf(i,e,t,r){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",r&&(i.levelkeys=r),i.initSegment=null}function df(i,e,t){i.levelkeys=e;const{encryptedFragments:r}=t;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&r.push(i)}function Di(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ff(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function ec(i,e){const t=e.startPTS;if(de(t)){let r=0,n;e.sn>i.sn?(r=t-i.start,n=i):(r=i.start-t,n=e),n.duration!==r&&n.setDuration(r)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function gf(i,e,t,r,n,s){r-t<=0&&(Oe.warn("Fragment should have a positive duration",e),r=t+e.duration,s=n+e.duration);let a=t,c=r;const l=e.startPTS,u=e.endPTS;if(de(l)){const p=Math.abs(l-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,l),t=Math.min(t,l),n=Math.min(n,e.startDTS),c=Math.min(r,u),r=Math.max(r,u),s=Math.max(s,e.endDTS)}const A=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(r-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=r,e.minEndPTS=c,e.endDTS=s;const h=e.sn;if(!i||h<i.startSN||h>i.endSN)return 0;let d;const f=h-i.startSN,g=i.fragments;for(g[f]=e,d=f;d>0;d--)ec(g[d],g[d-1]);for(d=f;d<g.length-1;d++)ec(g[d],g[d+1]);return i.fragmentHint&&ec(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,A}function XB(i,e){if(i===e)return;let t=null;const r=i.fragments;for(let c=r.length-1;c>=0;c--){const l=r[c].initSegment;if(l){t=l;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;eT(i,e,(c,l,u,A)=>{if(!e.startCC&&l.cc!==c.cc){var h,d;const f=c.cc-l.cc;for(let g=u;g<A.length;g++)A[g].cc+=f;e.startCC=(h=(d=If(i,e.startSN-1))==null?void 0:d.cc)!=null?h:A[0].cc,e.endCC=A[A.length-1].cc}de(c.startPTS)&&de(c.endPTS)&&(l.setStart(l.startPTS=c.startPTS),l.startDTS=c.startDTS,l.maxStartPTS=c.maxStartPTS,l.endPTS=c.endPTS,l.endDTS=c.endDTS,l.minEndPTS=c.minEndPTS,l.setDuration(c.endPTS-c.startPTS),l.duration&&(n=l),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(l.elementaryStreams=c.elementaryStreams),l.loader=c.loader,c.hasStats&&(l.stats=c.stats),c.initSegment&&(l.initSegment=c.initSegment,t=c.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(c=>{var l;c&&(!c.initSegment||c.initSegment.relurl===((l=t)==null?void 0:l.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(c=>!c),e.deltaUpdateFailed){Oe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=zB(i.dateRanges,e));const c=i.fragments.filter(l=>l.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let l=1;l<o.length;l++)o[l].programDateTime===null&&Zl(o[l],o[l-1],c);af(c,e)}ZB(i.partList,e.partList,(c,l)=>{l.elementaryStreams=c.elementaryStreams,l.stats=c.stats}),n?gf(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):mf(i,e),s.length&&(e.totalduration=e.edge-s[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const c=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=c),e.driftEndTime=a,e.driftEnd=c}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function zB(i,e){const{dateRanges:t,recentlyRemovedDateranges:r}=e,n=We({},i);r&&r.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const c=n[a],l=new tf(t[a].attr,c);l.isValid?(n[a]=l,c||(l.tagOrder+=o)):Oe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${it(t[a].attr)}"`)}),n}function ZB(i,e,t){if(i&&e){let r=0;for(let n=0,s=i.length;n<=s;n++){const o=i[n],a=e[n+r];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):r--}}}function eT(i,e,t){const r=e.skippedSegments,n=Math.max(i.startSN,e.startSN)-e.startSN,s=(i.fragmentHint?1:0)+(r?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,o=e.startSN-i.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let l=n;l<=s;l++){const u=c[o+l];let A=a[l];if(r&&!A&&u&&(A=e.fragments[l]=u),u&&A){if(t(u,A,l,a),u.url&&u.url!==A.url){e.playlistParsingError=pf(`media sequence mismatch ${A.sn}:`,i,e,u,A);return}else if(u.cc!==A.cc){e.playlistParsingError=pf(`discontinuity sequence mismatch (${u.cc}!=${A.cc})`,i,e,u,A);return}}}}function pf(i,e,t,r,n){return new Error(`${i} ${n.url}
2495
+ Time to underbuffer: ${re.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,k>d){let he=this.findBestLevel(this.hls.levels[d].bitrate,d,k,0,re,1,1);he===-1&&(he=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};p||L>w*2?ie():this.timer=self.setInterval(ie,w*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 SC(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 r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var n;this.fragCurrent=r,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 r=t.frag,{fragCurrent:n,partCurrent:s}=this;if(r&&n&&r.sn===n.sn&&r.level===n.level){const o=performance.now(),a=s?s.stats:r.stats,c=o-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const A=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(A,l),a.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,r,n){const s=e+r/t,o=n?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;de(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.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=r?r.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:c},o.realBitrate=Math.round(8*a/c)}if(t.bitrateTest){const s={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(I.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:r.stats;if(s.aborted||this.ignoreFragment(r))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(),r.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,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,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,r=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=r&&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:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:o}=r,a=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let u=s.abrBandWidthFactor,A=s.abrBandWidthUpFactor;if(l){const p=this.findBestLevel(c,o,n,l,0,u,A);if(p>=0)return this.rebufferNotice=-1,p}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){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=A=1)}const d=this.findBestLevel(c,o,n,l,h,u,A);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=r.levels[o],g=r.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?o:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,s,o,a){var c;const l=n+s,u=this.lastLoadedFragLevel,A=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[A],C=!!((c=this.hls.latestLevelDetails)!=null&&c.live),y=p===-1||u===-1;let x,_="SDR",D=(B==null?void 0:B.frameRate)||0;const{audioPreference:F,videoPreference:O}=v,M=this.audioTracksByGroup||(this.audioTracksByGroup=Nd(g));let j=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const U=this.codecTiers||(this.codecTiers=dB(f,M,t,r)),q=hB(U,_,e,F,O),{codecSet:R,videoRanges:w,minFramerate:k,minBitrate:K,minIndex:Y,preferHDR:ie}=q;j=Y,x=R,_=ie?w[w.length-1]:w[0],D=k,e=Math.max(e,K),this.log(`picked start tier ${it(q)}`)}else x=B==null?void 0:B.codecSet,_=B==null?void 0:B.videoRange;const X=d?d.duration:h?h.duration:0,le=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let U=r;U>=t;U--){var L;const q=f[U],R=U>A;if(!q)continue;if(v.useMediaCapabilities&&!q.supportedResult&&!q.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&(sB(q,M,_,D,e,F)||vo(q.videoCodec))?(q.supportedPromise=kd(q,M,he),q.supportedPromise.then(fe=>{if(!this.hls)return;q.supportedResult=fe;const we=this.hls.levels,be=we.indexOf(q);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${be} ${it(fe)}`):fe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${be} ${it(fe)}`),be>-1&&we.length>1&&(this.log(`Removing unsupported level ${be}`),this.hls.removeLevel(be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):q.supportedResult=Rd}if((x&&q.codecSet!==x||_&&q.videoRange!==_||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 w=q.details,k=(d?w==null?void 0:w.partTarget:w==null?void 0:w.averagetargetduration)||X;let K;R?K=a*e:K=o*e;const Y=X&&n>=X*2&&s===0?q.averageBitrate:q.maxBitrate,ie=this.getTimeToLoadFrag(le,K,Y*k,w===void 0);if(K>=Y&&(U===u||q.loadError===0&&q.fragmentError===0)&&(ie<=le||!de(ie)||C&&!this.bitrateTestDelay||ie<l)){const he=this.forcedAutoLevel;return U!==p&&(he===-1||he!==p)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[oe[0]].codecs}" ${f[oe[0]].videoRange}; not compatible with "${x}" ${_}`),this.info(`switch candidate:${A}->${U} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-Y)} ttfb:${le.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${ie.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:r}=this.hls;return Math.min(Math.max(e,r),t)}}const Gl={search:function(i,e){let t=0,r=i.length-1,n=null,s=null;for(;t<=r;){n=(t+r)/2|0,s=i[n];const o=e(s);if(o>0)t=n+1;else if(o<0)r=n-1;else return s}return null}};function EB(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!de(e))return null;const r=i[0].programDateTime;if(e<(r||0))return null;const n=i[i.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let s=0;s<i.length;++s){const o=i[s];if(vB(e,t,o))return o}return null}function br(i,e,t=0,r=0,n=.005){let s=null;if(i){s=e[1+i.sn-e[0].sn]||null;const a=i.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&i.level!==s.level&&s.end<=i.end&&(s=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!i||i.level===s.level)&&Gd(t,r,s)===0||IB(s,i,Math.min(n,r))))return s;const o=Gl.search(e,Gd.bind(null,t,r));return o&&(o!==i||!s)?o:s}function IB(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((n,s)=>(s[0]==="INF"&&(n+=parseFloat(s[1])),n),t);return i.start<=r}return!1}function Gd(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-r<=i?1:t.start-r>i&&t.start?-1:0}function vB(i,e,t){const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-r>i}function $d(i,e){return Gl.search(i,t=>t.cc<e?1:t.cc>e?-1:0)}function yB(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){const r=t.start,n=t.end;let s=i.fragments;if(!t.relurl){const{fragmentHint:o}=i;o&&(s=s.concat(o))}return Gl.search(s,o=>o.cc<e||o.end<=r?1:o.cc>e||o.start>=n?-1:0)}return null}function xo(i){switch(i.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(i,e){const t=xo(e);return i.default[`${t?"timeout":"error"}Retry`]}function $l(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function Yd(i){return Ye(Ye({},i),{errorRetry:null,timeoutRetry:null})}function Qo(i,e,t,r){if(!i)return!1;const n=r==null?void 0:r.code,s=e<i.maxNumRetry&&(CB(n)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,r,s):s}function CB(i){return i===0&&navigator.onLine===!1||!!i&&(i<400||i>499)}var Dt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},oi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class BB extends _i{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 r;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((r=t.frag)!=null&&r.gap){t.errorAction=qn();return}case V.FRAG_GAP:case V.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Dt.SendAlternateToPenaltyBox;return}case V.LEVEL_EMPTY_ERROR:case V.LEVEL_PARSING_ERROR:{var o,a;const l=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,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}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 l=n.loadLevelObj;if(l&&(s.type===Me.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===Me.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Dt.SendAlternateToPenaltyBox,t.errorAction.flags=oi.MoveAllAlternatesMatchingHost;return}}return;case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=n.loadLevelObj,u=l==null?void 0:l.attrs["HDCP-LEVEL"];u?t.errorAction={action:Dt.SendAlternateToPenaltyBox,flags:oi.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 c;t.errorAction=this.getLevelSwitchAction(t,(c=t.level)!=null?c: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=qn();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 r=this.hls,n=Hd(r.config.playlistLoadPolicy,e),s=this.playlistError++;if(Qo(n,s,xo(e),e.response))return{action:Dt.RetryRequest,flags:oi.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,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=Hd(e.details.startsWith("key")?o:s,e),c=t.levels.reduce((u,A)=>u+A.fragmentError,0);if(n&&(e.details!==V.FRAG_GAP&&n.fragmentError++,Qo(a,c,xo(e),e.response)))return{action:Dt.RetryRequest,flags:oi.None,retryConfig:a,retryCount:c};const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=c),l}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var s,o;const l=e.details;n.loadError++,l===V.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:A,loadLevel:h,minAutoLevel:d,maxAutoLevel:f}=r;r.autoLevelEnabled||(r.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===Ee.AUDIO&&l===V.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===V.BUFFER_ADD_CODEC_ERROR||l===V.BUFFER_APPEND_ERROR))&&A.some(({audioCodec:_})=>n.audioCodec!==_),C=e.sourceBufferName==="video"&&(l===V.BUFFER_ADD_CODEC_ERROR||l===V.BUFFER_APPEND_ERROR)&&A.some(({codecSet:_,audioCodec:D})=>n.codecSet!==_&&n.audioCodec===D),{type:y,groupId:x}=(o=e.context)!=null?o:{};for(let _=A.length;_--;){const D=(_+h)%A.length;if(D!==h&&D>=d&&D<=f&&A[D].loadError===0){var a,c;const F=A[D];if(l===V.FRAG_GAP&&g===Ee.MAIN&&e.frag){const O=A[D].details;if(O){const M=br(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&&(c=n.subtitleGroups)!=null&&c.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&&r.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Dt.SendAlternateToPenaltyBox,flags:oi.None,nextAutoLevel:u}}return{action:Dt.SendAlternateToPenaltyBox,flags:oi.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case Dt.DoNothing:break;case Dt.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,r=e.errorAction;if(!r)return;const{flags:n,hdcpLevel:s,nextAutoLevel:o}=r;switch(n){case oi.None:this.switchLevel(e,o);break;case oi.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=Ul[Ul.indexOf(s)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}r.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 r=_d(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===r&&this.hls.removeLevel(s)}}}function qn(i){const e={action:Dt.DoNothing,flags:oi.None};return i&&(e.resolved=!0),e}var It={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class TB{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 r=this.activePartLists[t];if(r)for(let n=r.length;n--;){const s=r[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,r){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&&(!r||a.buffered)){const c=a.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,r,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 c=this.fragments[a];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||s)){c.body.type===r&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(u=>{const A=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return A&&this.removeFragment(c.body),A})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,n=Vr(r),s=this.fragments[n];if(!s||s.buffered&&r.gap)return;const o=!r.relurl;Object.keys(t).forEach(a=>{const c=r.elementaryStreams[a];if(!c)return;const l=t[a],u=o||c.partial===!0;s.range[a]=this.getBufferedTimes(r,e.part,u,l)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=r.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),wo(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=Vd(r,n=>n.fragment.sn>=e))}fragBuffered(e,t){const r=Vr(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={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,r,n){const s={time:[],partial:r},o=e.start,a=e.end,c=e.minEndPTS||a,l=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const A=n.start(u)-this.bufferPadding,h=n.end(u)+this.bufferPadding;if(l>=A&&c<=h){s.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(a,n.end(u))});break}else if(o<h&&a>A){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<=A)break}return s}getPartialFragment(e){let t=null,r,n,s,o=0;const{bufferPadding:a,fragments:c}=this;return Object.keys(c).forEach(l=>{const u=c[l];u&&wo(u)&&(n=u.body.start-a,s=u.body.end+a,e>=n&&e<=s&&(r=Math.min(e-n,s-e),o<=r&&(t=u.body,o=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||wo(t))}getState(e){const t=Vr(e),r=this.fragments[t];return r?r.buffered?wo(r)?It.PARTIAL:It.OK:It.APPENDING:It.NOT_LOADED}isTimeBuffered(e,t,r){let n,s;for(let o=0;o<r.length;o++){if(n=r.start(o)-this.bufferPadding,s=r.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 r=t.frag,n=t.part?null:t,s=Vr(r);this.fragments[s]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s,type:o}=t;if(r.sn==="initSegment")return;const a=r.type;if(n){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(n)}this.timeRanges=s;const c=s[o];this.detectEvictedFragments(o,c,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Vr(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const s=t[r[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,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const c=a.body;c.type!==r||n&&!c.gap||c.start<t&&c.end>e&&(a.buffered||s)&&this.removeFragment(c)})}removeFragment(e){const t=Vr(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const n=e.sn;this.activePartLists[e.type]=Vd(r,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 r=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function wo(i){var e,t,r;return i.buffered&&(i.body.gap||((e=i.range.video)==null?void 0:e.partial)||((t=i.range.audio)==null?void 0:t.partial)||((r=i.range.audiovideo)==null?void 0:r.partial))}function Vr(i){return`${i.type}_${i.level}_${i.sn}`}function Vd(i,e){return i.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}var tr={cbc:0,ctr:1};class bB{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case tr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tr.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 SB(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class xB{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),r=new Uint32Array(4);for(let n=0;n<4;n++)r[n]=t.getUint32(n*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],o=r[2],a=r[3],c=this.invSubMix,l=c[0],u=c[1],A=c[2],h=c[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,l[v]=x<<24|x>>>8,u[v]=x<<16|x>>>16,A[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 r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)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,c;const l=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),A=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=l[a]=t[a];continue}C=B,a%s===0?(C=C<<8|C>>>24,C=A[C>>>24]<<24|A[C>>>16&255]<<16|A[C>>>8&255]<<8|A[C&255],C^=h[a/s|0]<<24):s>6&&a%s===4&&(C=A[C>>>24]<<24|A[C>>>16&255]<<16|A[C>>>8&255]<<8|A[C&255]),l[a]=B=(l[a-s]^C)>>>0}for(c=0;c<o;c++)a=o-c,c&3?C=l[a]:C=l[a-4],c<4||a<=4?u[c]=C:u[c]=f[A[C>>>24]]^g[A[C>>>16&255]]^p[A[C>>>8&255]]^v[A[C&255]],u[c]=u[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,c=a[0],l=a[1],u=a[2],A=a[3],h=this.uint8ArrayToUint32Array_(r);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,_,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=c[D>>>24]^l[F>>16&255]^u[O>>8&255]^A[M&255]^s[L],y=c[F>>>24]^l[O>>16&255]^u[M>>8&255]^A[D&255]^s[L+1],x=c[O>>>24]^l[M>>16&255]^u[D>>8&255]^A[F&255]^s[L+2],_=c[M>>>24]^l[D>>16&255]^u[F>>8&255]^A[O&255]^s[L+3],D=C,F=y,O=x,M=_,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],_=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(_^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 QB{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=wB(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function wB(i){switch(i){case tr.cbc:return"AES-CBC";case tr.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const _B=16;class Hl{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 r=self.crypto;r&&(this.subtle=r.subtle||r.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 r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?SB(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,n);const c=this.flush();c?s(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:s,currentResult:o,remainderData:a}=this;if(n!==tr.cbc||t.byteLength!==16)return Oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=jt(a,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xB),l.expandKey(t);const u=o;return this.currentResult=l.decrypt(c.buffer,0,r),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new QB(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bB(this.subtle,new Uint8Array(r),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,r,n)))}onWebCryptoError(e,t,r,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,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 r=e.length-e.length%_B;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Kd=Math.pow(2,17);class RB{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 r=e.url;if(!r)return Promise.reject(new Ri({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(qd(e));return}else e.gap=!1;const l=this.loader=s?new s(n):new o(n),u=Wd(e);e.loader=l;const A=Yd(n.fragLoadPolicy.default),h={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kd};e.stats=l.stats;const d={onSuccess:(f,g,p,v)=>{this.resetLoader(e,l);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,l),c(new Ri({type:Ie.NETWORK_ERROR,details:V.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ye({url:r,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{this.resetLoader(e,l),c(new Ri({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,l),c(new Ri({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})),l.load(u,h,d)})}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(qd(e,t));return}const l=this.loader=s?new s(n):new o(n),u=Wd(e,t);e.loader=l;const A=Yd(n.fragLoadPolicy.default),h={loadPolicy:A,timeout:A.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kd};t.stats=l.stats,l.load(u,h,{onSuccess:(d,f,g,p)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:d.data,networkDetails:p};r(v),a(v)},onError:(d,f,g,p)=>{this.resetLoader(e,l),c(new Ri({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,l),c(new Ri({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,l),c(new Ri({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 r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(r.loaded/s),c),A=(c-l)*Math.round(r.loaded/l);r.total=r.loaded+A}else r.total=Math.max(r.loaded,r.total);const o=r.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 Wd(i,e=null){const t=e||i,r={frag:i,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,c=s;if(i.sn==="initSegment"&&DB((o=i.decryptdata)==null?void 0:o.method)){const l=s-n;l%16&&(c=s+(16-l%16)),n!==0&&(r.resetIV=!0,a=n-16)}r.rangeStart=a,r.rangeEnd=c}return r}function qd(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),r={type:Ie.MEDIA_ERROR,details:V.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(r.part=e),(e||i).stats.aborted=!0,new Ri(r)}function DB(i){return i==="AES-128"||i==="AES-256"}class Ri extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Jd extends _i{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 Yl{constructor(e,t,r,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=_o(),this.buffering={audio:_o(),video:_o(),audiovideo:_o()},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=o}}function _o(){return{start:0,executeStart:0,executeEnd:0,end:0}}const jd={length:0,start:()=>0,end:()=>0};class Le{static isBuffered(e,t){if(e){const r=Le.getBuffered(e);for(let n=r.length;n--;)if(t>=r.start(n)&&t<=r.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 r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const n=Le.bufferedRanges(e);if(n.length)return Le.bufferedInfo(n,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((u,A)=>u.start-A.start||A.end-u.end);let n=-1,s=[];if(r)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const A=s.length;if(A){const h=s[A-1].end;e[u].start-h<r?e[u].end>h&&(s[A-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,c=t,l=t;for(let u=0;u<s.length;u++){const A=s[u].start,h=s[u].end;if(n===-1&&t>=A&&t<=h&&(n=u),t+r>=A&&t<h)c=A,l=h,o=l-t;else if(t+r<A){a=A;break}}return{len:o,start:c||0,end:l||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||jd}catch(t){return Oe.log("failed to get media.buffered",t),jd}}}const Xd=/\{\$([a-zA-Z0-9-_]+)\}/g;function zd(i){return Xd.test(i)}function Vl(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(Xd,r=>{const n=r.substring(2,r.length-1),s=t==null?void 0:t[n];return s===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),r):s})}return e}function Zd(i,e,t){let r=i.variableList;r||(i.variableList=r={});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){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,s=e.VALUE;n in r?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):r[n]=s||""}function LB(i,e,t){const r=e.IMPORT;if(t&&r in t){let n=i.variableList;n||(i.variableList=n={}),n[r]=t[r]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const kB=/^(\d+)x(\d+)$/,ef=/(.+?)=(".*?"|.*?)(?:,|$)/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 r=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}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 r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((n,s)=>(n[s.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=kB.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const n={},s='"';for(ef.lastIndex=0;(r=ef.exec(e))!==null;){const o=r[1].trim();let a=r[2];const c=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let l=!1;if(c)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))a=Vl(t,a);else if(!l&&!c)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 MB="com.apple.hls.interstitial";function FB(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function PB(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class tf{constructor(e,t,r=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:r,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===MB}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 NB=10;class OB{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,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>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||NB}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 r=e.length;r--;)if(e[r].index>t)return e[r].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 Kr(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Kl(i){switch(i){case"AES-128":case"AES-256":return tr.cbc;case"AES-256-CTR":return tr.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Wl(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function ql(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function UB(i){const e=ql(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function GB(i){const e=function(r,n,s){const o=r[n];r[n]=r[s],r[s]=o};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function $B(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),n=r[r.length-1].split(",");if(n.length===2){const s=n[0]==="base64",o=n[1];s?(r.splice(-1,1),t=Wl(o)):t=UB(o)}}return t}const Ro=typeof self<"u"?self:void 0;var Ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Nt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Jl(i){switch(i){case Nt.FAIRPLAY:return Ve.FAIRPLAY;case Nt.PLAYREADY:return Ve.PLAYREADY;case Nt.WIDEVINE:return Ve.WIDEVINE;case Nt.CLEARKEY:return Ve.CLEARKEY}}var Do={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function jl(i){if(i===Do.WIDEVINE)return Ve.WIDEVINE;if(i===Do.PLAYREADY)return Ve.PLAYREADY;if(i===Do.CENC||i===Do.CLEARKEY)return Ve.CLEARKEY}function Xl(i){switch(i){case Ve.FAIRPLAY:return Nt.FAIRPLAY;case Ve.PLAYREADY:return Nt.PLAYREADY;case Ve.WIDEVINE:return Nt.WIDEVINE;case Ve.CLEARKEY:return Nt.CLEARKEY}}function Lo(i){const{drmSystems:e,widevineLicenseUrl:t}=i,r=e?[Ve.FAIRPLAY,Ve.WIDEVINE,Ve.PLAYREADY,Ve.CLEARKEY].filter(n=>!!e[n]):[];return!r[Ve.WIDEVINE]&&t&&r.push(Ve.WIDEVINE),r}const rf=function(i){return Ro!=null&&(i=Ro.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function HB(i,e,t,r){let n;switch(i){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: ${i}`)}return YB(n,e,t,r)}function YB(i,e,t,r){return[{initDataTypes:i,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function VB(i){var e;return i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function nf(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),r=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const c=Wl(a).subarray(0,16);return GB(c),c}}return null}let ko={};class Jn{static clearKeyUriToKeyIdMap(){ko={}}constructor(e,t,r,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=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Kr(e)}isSupported(){if(this.method){if(Kr(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Nt.FAIRPLAY:case Nt.WIDEVINE:case Nt.PLAYREADY:case Nt.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(Kr(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 r=KB(e);return new Jn(this.method,this.uri,"identity",this.keyFormatVersions,r)}const t=$B(this.uri);if(t)switch(this.keyFormat){case Nt.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Nt.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=XC(r,null,t),this.keyId=nf(t);break}default:{let r=t.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r=ko[this.uri];if(!r){const n=Object.keys(ko).length%Number.MAX_SAFE_INTEGER;r=new Uint8Array(16),new DataView(r.buffer,12,4).setUint32(0,n),ko[this.uri]=r}this.keyId=r}return this}}function KB(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const sf=/#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,of=/#EXT-X-MEDIA:(.*)/g,WB=/^#EXT(?:INF|-X-TARGETDURATION):/m,zl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),qB=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 mi{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static resolve(e,t){return Dl.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return WB.test(e)}static parseMasterPlaylist(e,t){const r=zd(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},s=[];sf.lastIndex=0;let o;for(;(o=sf.exec(e))!=null;)if(o[1]){var a;const l=new st(o[1],n),u=Vl(n,o[2]),A={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:mi.resolve(u,t)},h=l.decimalResolution("RESOLUTION");h&&(A.width=h.width,A.height=h.height),Af(l.CODECS,A);const d=l["SUPPLEMENTAL-CODECS"];d&&(A.supplemental={},Af(d,A.supplemental)),(a=A.unknownCodecs)!=null&&a.length||s.push(A),n.levels.push(A)}else if(o[3]){const l=o[3],u=o[4];switch(l){case"SESSION-DATA":{const A=new st(u,n),h=A["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=A);break}case"SESSION-KEY":{const A=lf(u,t,n);A.encrypted&&A.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(A)):Oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const A=new st(u,n);Zd(n,A,t)}break}case"CONTENT-STEERING":{const A=new st(u,n);n.contentSteering={uri:mi.resolve(A["SERVER-URI"],t),pathwayId:A["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=cf(u);break}}}const c=s.length>0&&s.length<n.levels.length;return n.levels=c?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,r){let n;const s={},o=r.levels,a={AUDIO:o.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:o.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(of.lastIndex=0;(n=of.exec(e))!==null;){const l=new st(n[1],r),u=l.TYPE;if(u){const A=a[u],h=s[u]||[];s[u]=h;const d=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],g=l.CHANNELS,p=l.CHARACTERISTICS,v=l["INSTREAM-ID"],B={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||d||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:d,url:l.URI?mi.resolve(l.URI,t):""};if(f&&(B.assocLang=f),g&&(B.channels=g),p&&(B.characteristics=p),v&&(B.instreamId=v),A!=null&&A.length){const C=mi.findGroup(A,B.groupId)||A[0];uf(B,C,"audioCodec"),uf(B,C,"textCodec")}h.push(B)}}return s}static parseLevelPlaylist(e,t,r,n,s,o){var a;const c={url:t},l=new OB(t),u=l.fragments,A=[];let h=null,d=0,f=0,g=0,p=0,v=0,B=null,C=new kl(n,c),y,x,_,D=-1,F=!1,O=null,M;if(zl.lastIndex=0,l.m3u8=e,l.hasVariableRefs=zd(e),((a=zl.exec(e))==null?void 0:a[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(y=zl.exec(e))!==null;){F&&(F=!1,C=new kl(n,c),C.playlistOffset=g,C.start=g,C.sn=d,C.cc=p,v&&(C.bitrate=v),C.level=r,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,_&&df(C,_,l),C.sn=d,C.level=r,C.cc=p,u.push(C);const L=(" "+y[3]).slice(1);C.relurl=Vl(l,L),Zl(C,B,A),B=C,g+=C.duration,d++,f=0,F=!0}}else{if(y=y[0].match(qB),!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":l.type&&Di(l,L,y),l.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Di(l,L,y):u.length>0&&ff(l,L,y),d=l.startSN=parseInt(U);break;case"SKIP":{l.skippedSegments&&Di(l,L,y);const R=new st(U,l),w=R.decimalInteger("SKIPPED-SEGMENTS");if(de(w)){l.skippedSegments+=w;for(let K=w;K--;)u.push(null);d+=w}const k=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");k&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(k.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Di(l,L,y),l.targetduration=Math.max(parseInt(U),1);break;case"VERSION":l.version!==null&&Di(l,L,y),l.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Di(l,L,y),l.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,l),w=new tf(R,l.dateRanges[R.ID],l.dateRangeTagCount);l.dateRangeTagCount++,w.isValid||l.skippedSegments?l.dateRanges[w.id]=w:Oe.warn(`Ignoring invalid DATERANGE tag: "${U}"`),C.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const R=new st(U,l);"IMPORT"in R?LB(l,R,o):Zd(l,R,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Di(l,L,y):u.length>0&&ff(l,L,y),l.startCC=p=parseInt(U);break;case"KEY":{const R=lf(U,t,l);if(R.isSupported()){if(R.method==="NONE"){_=void 0;break}_||(_={}),_[R.keyFormat]&&(_=We({},_)),_[R.keyFormat]=R}else Oe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":l.startTimeOffset=cf(U);break;case"MAP":{const R=new st(U,l);if(C.duration){const w=new kl(n,c);hf(w,R,r,_),h=w,C.initSegment=h,h.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=h.rawProgramDateTime)}else{const w=C.byteRangeEndOffset;if(w){const k=C.byteRangeStartOffset;O=`${w-k}@${k}`}else O=null;hf(C,R,r,_),h=C,F=!0}h.cc=p;break}case"SERVER-CONTROL":{M&&Di(l,L,y),M=new st(U),l.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),l.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Di(l,L,y);const R=new st(U);l.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=l.partList;R||(R=l.partList=[]);const w=f>0?R[R.length-1]:void 0,k=f++,K=new st(U,l),Y=new FC(K,C,c,k,w);R.push(Y),C.duration+=Y.duration;break}case"PRELOAD-HINT":{const R=new st(U,l);l.preloadHint=R;break}case"RENDITION-REPORT":{const R=new st(U,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(R);break}default:Oe.warn(`line parsed but not handled: ${y}`);break}}}B&&!B.relurl?(u.pop(),g-=B.duration,l.partList&&(l.fragmentHint=B)):l.partList&&(Zl(C,B,A),C.cc=p,l.fragmentHint=C,_&&df(C,_,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const j=u.length,X=u[0],le=u[j-1];if(g+=l.skippedSegments*l.targetduration,g>0&&j&&le){l.averagetargetduration=g/j;const oe=le.sn;l.endSN=oe!=="initSegment"?oe:0,l.live||(le.endList=!0),X&&l.startCC===void 0&&(l.startCC=X.cc),D>0&&(jB(u,D),X&&A.unshift(X))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(g+=l.fragmentHint.duration),l.totalduration=g,A.length&&l.dateRangeTagCount&&X&&af(A,l),l.endCC=p,l}}function af(i,e){const t=i.length,r=i[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]],c=a.startDate.getTime();a.tagAnchor=r.ref;for(let l=t;l--;){const u=JB(e,c,i,l,n);if(u!==-1){a.tagAnchor=e.fragments[u].ref;break}}}}function JB(i,e,t,r,n){const s=t[r];if(s){const a=s.programDateTime;if(e>=a||r===0){var o;const c=(((o=t[r+1])==null?void 0:o.start)||n)-s.start;if(e<=a+c*1e3){const l=t[r].sn-i.startSN,u=i.fragments;if(u.length>t.length){const h=(t[r+1]||u[u.length-1]).sn-i.startSN;for(let d=h;d>l;d--){const f=u[d].programDateTime;if(e>=f&&e<f+u[d].duration*1e3)return d}}return l}}}return-1}function lf(i,e,t){var r,n;const s=new st(i,t),o=(r=s.METHOD)!=null?r:"",a=s.URI,c=s.hexadecimalInteger("IV"),l=s.KEYFORMATVERSIONS,u=(n=s.KEYFORMAT)!=null?n:"identity";a&&s.IV&&!c&&Oe.error(`Invalid IV: ${s.IV}`);const A=a?mi.resolve(a,e):"",h=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Jn(o,A,u,h,c)}function cf(i){const t=new st(i).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function Af(i,e){let t=(i||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const n=t.filter(s=>Sd(s,r));n.length&&(e[`${r}Codec`]=n.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>n.indexOf(s)===-1))}),e.unknownCodecs=t}function uf(i,e,t){const r=e[t];r&&(i[t]=r)}function jB(i,e){let t=i[e];for(let r=e;r--;){const n=i[r];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Zl(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function hf(i,e,t,r){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",r&&(i.levelkeys=r),i.initSegment=null}function df(i,e,t){i.levelkeys=e;const{encryptedFragments:r}=t;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&r.push(i)}function Di(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ff(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function ec(i,e){const t=e.startPTS;if(de(t)){let r=0,n;e.sn>i.sn?(r=t-i.start,n=i):(r=i.start-t,n=e),n.duration!==r&&n.setDuration(r)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function gf(i,e,t,r,n,s){r-t<=0&&(Oe.warn("Fragment should have a positive duration",e),r=t+e.duration,s=n+e.duration);let a=t,c=r;const l=e.startPTS,u=e.endPTS;if(de(l)){const p=Math.abs(l-t);de(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,a=Math.max(t,l),t=Math.min(t,l),n=Math.min(n,e.startDTS),c=Math.min(r,u),r=Math.max(r,u),s=Math.max(s,e.endDTS)}const A=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(r-e.start),e.startPTS=t,e.maxStartPTS=a,e.startDTS=n,e.endPTS=r,e.minEndPTS=c,e.endDTS=s;const h=e.sn;if(!i||h<i.startSN||h>i.endSN)return 0;let d;const f=h-i.startSN,g=i.fragments;for(g[f]=e,d=f;d>0;d--)ec(g[d],g[d-1]);for(d=f;d<g.length-1;d++)ec(g[d],g[d+1]);return i.fragmentHint&&ec(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,A}function XB(i,e){if(i===e)return;let t=null;const r=i.fragments;for(let c=r.length-1;c>=0;c--){const l=r[c].initSegment;if(l){t=l;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;eT(i,e,(c,l,u,A)=>{if(!e.startCC&&l.cc!==c.cc){var h,d;const f=c.cc-l.cc;for(let g=u;g<A.length;g++)A[g].cc+=f;e.startCC=(h=(d=If(i,e.startSN-1))==null?void 0:d.cc)!=null?h:A[0].cc,e.endCC=A[A.length-1].cc}de(c.startPTS)&&de(c.endPTS)&&(l.setStart(l.startPTS=c.startPTS),l.startDTS=c.startDTS,l.maxStartPTS=c.maxStartPTS,l.endPTS=c.endPTS,l.endDTS=c.endDTS,l.minEndPTS=c.minEndPTS,l.setDuration(c.endPTS-c.startPTS),l.duration&&(n=l),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(l.elementaryStreams=c.elementaryStreams),l.loader=c.loader,c.hasStats&&(l.stats=c.stats),c.initSegment&&(l.initSegment=c.initSegment,t=c.initSegment)});const s=e.fragments,o=e.fragmentHint?s.concat(e.fragmentHint):s;if(t&&o.forEach(c=>{var l;c&&(!c.initSegment||c.initSegment.relurl===((l=t)==null?void 0:l.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=s.some(c=>!c),e.deltaUpdateFailed){Oe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)s.shift();e.startSN=s[0].sn}else{e.endCC=s[s.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=zB(i.dateRanges,e));const c=i.fragments.filter(l=>l.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let l=1;l<o.length;l++)o[l].programDateTime===null&&Zl(o[l],o[l-1],c);af(c,e)}ZB(i.partList,e.partList,(c,l)=>{l.elementaryStreams=c.elementaryStreams,l.stats=c.stats}),n?gf(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):mf(i,e),s.length&&(e.totalduration=e.edge-s[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const c=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=c),e.driftEndTime=a,e.driftEnd=c}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function zB(i,e){const{dateRanges:t,recentlyRemovedDateranges:r}=e,n=We({},i);r&&r.forEach(a=>{delete n[a]});const o=Object.keys(n).length;return o&&Object.keys(t).forEach(a=>{const c=n[a],l=new tf(t[a].attr,c);l.isValid?(n[a]=l,c||(l.tagOrder+=o)):Oe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${it(t[a].attr)}"`)}),n}function ZB(i,e,t){if(i&&e){let r=0;for(let n=0,s=i.length;n<=s;n++){const o=i[n],a=e[n+r];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):r--}}}function eT(i,e,t){const r=e.skippedSegments,n=Math.max(i.startSN,e.startSN)-e.startSN,s=(i.fragmentHint?1:0)+(r?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,o=e.startSN-i.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let l=n;l<=s;l++){const u=c[o+l];let A=a[l];if(r&&!A&&u&&(A=e.fragments[l]=u),u&&A){if(t(u,A,l,a),u.url&&u.url!==A.url){e.playlistParsingError=pf(`media sequence mismatch ${A.sn}:`,i,e,u,A);return}else if(u.cc!==A.cc){e.playlistParsingError=pf(`discontinuity sequence mismatch (${u.cc}!=${A.cc})`,i,e,u,A);return}}}}function pf(i,e,t,r,n){return new Error(`${i} ${n.url}
2496
2496
  Playlist starting @${e.startSN}
2497
2497
  ${e.m3u8}
2498
2498
 
2499
2499
  Playlist starting @${t.startSN}
2500
- ${t.m3u8}`)}function mf(i,e,t=!0){const r=e.startSN+e.skippedSegments-i.startSN,n=i.fragments,s=r>=0;let o=0;if(s&&r<n.length)o=n[r].start;else if(s&&e.startSN===i.endSN+1)o=i.fragmentEnd;else if(s&&t)o=i.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=i.fragmentStart;else return;tc(e,o)}function tc(i,e){if(e){const t=i.fragments;for(let r=i.skippedSegments;r<t.length;r++)t[r].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function Ef(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const r=i.fragments;if(r.length&&t*4>e){const s=r[r.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function If(i,e,t){if(!i)return null;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e)?r:e<i.startSN&&t&&t.sn===e?t:null}function vf(i,e,t){return i?yf(i.partList,e,t):null}function yf(i,e,t){if(i)for(let r=i.length;r--;){const n=i[r];if(n.index===t&&n.fragment.sn===e)return n}return null}function Cf(i){i.forEach((e,t)=>{var r;(r=e.details)==null||r.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function jn(i,e){for(let r=0,n=i.length;r<n;r++){var t;if(((t=i[r])==null?void 0:t.cc)===e)return i[r]}return null}function tT(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function Bf(i,e){if(i){const t=i.start+e;i.start=i.startPTS=t,i.endPTS=t+i.duration}}function Tf(i,e){const t=e.fragments;for(let r=0,n=t.length;r<n;r++)Bf(t[r],i);e.fragmentHint&&Bf(e.fragmentHint,i),e.alignedSliding=!0}function iT(i,e){i&&(bf(e,i),!e.alignedSliding&&i&&Mo(e,i),!e.alignedSliding&&i&&!e.skippedSegments&&mf(i,e,!1))}function bf(i,e){if(!tT(e,i))return;const t=Math.min(e.endCC,i.endCC),r=jn(e.fragments,t),n=jn(i.fragments,t);if(!r||!n)return;Oe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=r.start-n.start;Tf(s,i)}function Mo(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,r=e.fragments;if(!t.length||!r.length)return;let n,s;const o=Math.min(e.endCC,i.endCC);e.startCC<o&&i.startCC<o&&(n=jn(r,o),s=jn(t,o)),(!n||!s)&&(n=r[Math.floor(r.length/2)],s=jn(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,c=s.programDateTime;if(!a||!c)return;const l=(c-a)/1e3-(s.start-n.start);Tf(l,i)}const rT={toString:function(i){let e="";const t=i.length;for(let r=0;r<t;r++)e+=`[${i.start(r).toFixed(3)}-${i.end(r).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 ic extends Jd{constructor(e,t,r,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:c,mediaBuffer:l,state:u}=this,A=c?c.currentTime:0,h=Le.bufferInfo(l||c,A,o.maxBufferHole);if(this.log(`media seeking to ${de(A)?A.toFixed(3):A}, 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=A>g;(A<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(c){this.fragmentTracker.removeFragmentsInRange(A,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(A>d&&(this.lastCurrentTime=A),!this.loadingParts){const f=Math.max(h.end,A),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${A.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${A} because of seek before start`),this.nextLoadPosition=this.startPosition=A),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 RB(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Hl(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 r=e.end||0,n=this.config.timelineOffset||0;if(r<=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 l=a[a.length-1];return Le.isBuffered(this.media,l.start+l.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}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 r=this.media=this.mediaBuffer=t.media;r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),r.addEventListener("seeking",this.onMediaSeeking),r.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!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&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){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,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){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,r,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:r}=this;if(r.getState(e)===It.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===It.PARTIAL&&r.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,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const n=r==null?void 0:r.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:n}=this,{frag:s,payload:o}=r,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Kr(a.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,Kl(a.method)).catch(l=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:s}),l}).then(l=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:l,stats:{tstart:c,tdecrypt:u}}),r.payload=l,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.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 r=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:${r?rT.toString(Le.getBuffered(r)):"(detached)"})`),Ct(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:r,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(c=>!c),a=new Yl(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=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(A=>{if(!this.fragContextChanged(A.frag))return this.hls.trigger(I.KEY_LOADED,A),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),A}),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 c=this.fragPrevious;if(Ct(e)&&(!c||e.sn!==c.sn)){const A=this.shouldLoadParts(t.details,e.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=A)}if(r=Math.max(e.start,r||0),this.loadingParts&&Ct(e)){const A=o.partList;if(A&&n){r>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(A,e,r);if(h>-1){const d=A[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${A.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(r.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:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(A,r))return Promise.resolve(null)}}if(Ct(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.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(r.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const l=this.config.progressive;let u;return l&&a?u=a.then(A=>!A||this.fragContextChanged(A==null?void 0:A.frag)?null:this.fragmentLoader.load(e,n)).catch(A=>this.handleFragLoadError(A)):u=Promise.all([this.fragmentLoader.load(e,l?n:void 0),a]).then(([A])=>(!l&&A&&n&&n(A),A)).catch(A=>this.handleFragLoadError(A)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,r,n){return new Promise((s,o)=>{var a;const c=[],l=(a=r.details)==null?void 0:a.partList,u=A=>{this.fragmentLoader.loadPart(e,A,n).then(h=>{c[A.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=vf(r.details,e.sn,A.index+1)||yf(l,e.sn,A.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:c})}).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:r,part:n,level:s}=t,o=self.performance.now();r.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),l=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(r,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var r;const s=e.partList[0],o=s.end+(((r=e.fragmentHint)==null?void 0:r.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:r}=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],c=a.details,l=o>-1?vf(c,s,o):null,u=l?l.fragment:If(c,s,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:a}):null}bufferFragmentData(e,t,r,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:c}=e;let l=a;if(a&&c&&(l=jt(a,c)),!((o=l)!=null&&o.length))return;const u={type:e.type,frag:t,part:r,chunkMeta:n,parent:t.type,data:l};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!r){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 r=t.currentTime,n=Le.bufferInfo(t,r,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),r+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,r,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,r);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 r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-t*3,r.maxMaxBufferLength/2,n);return s>=n?(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var r;const n=(r=this.fragmentTracker)==null?void 0:r.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:s}=this,o=r[0].start,a=s.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const A=s.initialLiveManifestSize;if(n<A)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${A})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t,r);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=c?(h!==-1&&h>=o?h:d)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(c=r[0]);if(!c){const A=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,A,t)}let u=this.filterReplacedPrimary(c,t);if(!u&&c){const A=c.sn-t.startSN;u=this.filterReplacedPrimary(r[A+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===It.OK||r===It.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&r.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(a!==null&&r.len+a.len>=s){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(Sf(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(Sf(this.hls.config)&&e.type!==Ee.SUBTITLE){const r=this.hls.interstitialsManager,n=r==null?void 0:r.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=r==null?void 0:r.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,r){let n=-1,s=!1,o=!0;for(let a=0,c=e.length;a<c;a++){const l=e[a];if(o=o&&!l.independent,n>-1&&r<l.start)break;const u=l.loaded;u?n=-1:(s||l.independent||o)&&l.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const r=e[e.length-1];return r&&t>r.start&&r.loaded}getInitialLiveFragment(e,t){const r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=EB(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];r.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=$d(t,r.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,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:l}=n,u=r.partList,A=!!(this.loadingParts&&u!=null&&u.length&&c);A&&c&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(o=o.concat(c),a=c.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-l||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:l;h=br(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-r.startSN,g=this.fragmentTracker.getState(h);if((g===It.OK||g===It.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!A||u[0].fragment.sn>h.sn||!r.live&&!A)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==It.OK?h=v:h=null}}return h}alignPlaylists(e,t,r){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){iT(r,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),c}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(r===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(r=t+o,o<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ct(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 r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const o=t.errorAction,{action:a,flags:c,retryCount:l=0,retryConfig:u}=o||{},A=!!o&&!!u,h=A&&a===Dt.RetryRequest,d=A&&!o.resolved&&c===si.MoveAllAlternatesMatchingHost;if(!h&&d&&Ct(r)&&!r.endList)this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((h||d)&&l<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=$l(u,l);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${l+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),l<u.maxNumRetry)!s&&a!==Dt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${l})`);return}else a===Dt.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,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),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 ${r} 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,r){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),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,r,n){const s=r.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const u=e.elementaryStreams[l];if(u){const A=u.endPTS-u.startPTS;if(A<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${A})`),c||!1;const h=n?0:gf(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:r,drift:h,type:l,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var a;if(r.fragmentError===0&&this.treatAsGap(e,r),((a=this.transmuxer)==null?void 0:a.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.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,r){var n,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((n=t&&!r?e.startPTS:(r||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!r?e.endPTS:(r||e).end)!=null?s:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.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 Sf(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class xf{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;if(e.length)e.length===1?r=e[0]:r=nT(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function nT(i,e){const t=new Uint8Array(e);let r=0;for(let n=0;n<i.length;n++){const s=i[n];t.set(s,r),r+=s.length}return t}var rc={exports:{}},Qf;function sT(){return Qf||(Qf=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function s(c,l,u,A,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,A||c,h),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],d]:c._events[f].push(d):(c._events[f]=d,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,A;if(this._eventsCount===0)return l;for(A in u=this._events)e.call(u,A)&&l.push(t?A.slice(1):A);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=t?t+l:l,A=this._events[u];if(!A)return[];if(A.fn)return[A.fn];for(var h=0,d=A.length,f=new Array(d);h<d;h++)f[h]=A[h].fn;return f},a.prototype.listenerCount=function(l){var u=t?t+l:l,A=this._events[u];return A?A.fn?1:A.length:0},a.prototype.emit=function(l,u,A,h,d,f){var g=t?t+l:l;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(l,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,A),!0;case 4:return p.fn.call(p.context,u,A,h),!0;case 5:return p.fn.call(p.context,u,A,h,d),!0;case 6:return p.fn.call(p.context,u,A,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(l,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,A);break;case 4:p[C].fn.call(p[C].context,u,A,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(l,u,A){return s(this,l,u,A,!1)},a.prototype.once=function(l,u,A){return s(this,l,u,A,!0)},a.prototype.removeListener=function(l,u,A,h){var d=t?t+l:l;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)&&(!A||f.context===A)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||A&&f[g].context!==A)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&o(this,u)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a}(rc)),rc.exports}var oT=sT(),nc=kC(oT);const Xn="1.6.2",Wr={};function aT(){return typeof __HLS_WORKER_BUNDLE__=="function"}function lT(){const i=Wr[Xn];if(i)return i.clientCount++,i;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 Wr[Xn]=n,n}function cT(i){const e=Wr[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wr[i]=n,n}function AT(i){const e=Wr[i||Xn];if(e&&e.clientCount--===1){const{worker:r,objectURL:n}=e;delete Wr[i||Xn],n&&self.URL.revokeObjectURL(n),r.terminate()}}function wf(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function sc(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Fo(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function zn(i,e){const t=e;let r=0;for(;sc(i,e);){r+=10;const n=Fo(i,e+6);r+=n,wf(i,e+10)&&(r+=10),e+=r}if(r>0)return i.subarray(t,t+r)}function uT(i,e,t,r){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}`);i.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,c=e[t+3]>>6&3|(s&1)<<2,l="mp4a.40."+a,u=n[o];let A=o;(a===5||a===29)&&(A-=3);const h=[a<<3|(A&14)>>1,(A&1)<<7|c<<3];return Oe.log(`manifest codec:${r}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:r}}function _f(i,e){return i[e]===255&&(i[e+1]&246)===240}function Rf(i,e){return i[e+1]&1?7:9}function oc(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function hT(i,e){return e+5<i.length}function Po(i,e){return e+1<i.length&&_f(i,e)}function dT(i,e){return hT(i,e)&&_f(i,e)&&oc(i,e)<=i.length-e}function fT(i,e){if(Po(i,e)){const t=Rf(i,e);if(e+t>=i.length)return!1;const r=oc(i,e);if(r<=t)return!1;const n=e+r;return n===i.length||Po(i,n)}return!1}function Df(i,e,t,r,n){if(!i.samplerate){const s=uT(e,t,r,n);if(!s)return;We(i,s)}}function Lf(i){return 9216e4/i}function gT(i,e){const t=Rf(i,e);if(e+t<=i.length){const r=oc(i,e)-t;if(r>0)return{headerLength:t,frameLength:r}}}function kf(i,e,t,r,n){const s=Lf(i.samplerate),o=r+n*s,a=gT(e,t);let c;if(a){const{frameLength:A,headerLength:h}=a,d=h+A,f=Math.max(0,t+d-e.length);f?(c=new Uint8Array(d-h),c.set(e.subarray(t+h,e.length),0)):c=e.subarray(t+h,t+d);const g={unit:c,pts:o};return f||i.samples.push(g),{sample:g,length:d,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:l,missing:-1}}function pT(i,e){return sc(i,e)&&Fo(i,e+6)+10<=i.length-e}function mT(i){if(i.size<2)return;const e=Ht(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function ET(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const r=Ht(i.data.subarray(t),!0);t+=r.length+1;const n=Ht(i.data.subarray(t));return{key:i.type,info:r,data:n}}const e=Ht(i.data.subarray(1));return{key:i.type,info:"",data:e}}function IT(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const r=Ht(i.data.subarray(t),!0);t+=r.length+1;const n=Ht(i.data.subarray(t));return{key:i.type,info:r,data:n}}const e=Ht(i.data);return{key:i.type,info:"",data:e}}function vT(i){return btoa(String.fromCharCode(...i))}function Mf(i,e){if(i<0)return-Mf(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const n=Math.floor(i*t);return(n%2===0?n:n+1)/t}else return Math.round(i*t)/t}function yT(i,e){const t=new URL(i),r=new URL(e);if(t.origin!==r.origin)return i;const n=t.pathname.split("/").slice(1),s=r.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 CT(){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 BT(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function ac(i,e=0,t=1/0){return TT(i,e,t,Uint8Array)}function TT(i,e,t,r){const n=bT(i);let s=1;"BYTES_PER_ELEMENT"in r&&(s=r.BYTES_PER_ELEMENT);const o=ST(i)?i.byteOffset:0,a=(o+i.byteLength)/s,c=(o+e)/s,l=Math.floor(Math.max(0,Math.min(c,a))),u=Math.floor(Math.min(l+Math.max(t,0),a));return new r(n,l,u-l)}function bT(i){return i instanceof ArrayBuffer?i:i.buffer}function ST(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function xT(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const r=i.data.subarray(1).indexOf(0);if(r===-1)return;const n=Ht(ac(i.data,1,r)),s=i.data[2+r],o=i.data.subarray(3+r).indexOf(0);if(o===-1)return;const a=Ht(ac(i.data,3+r,o));let c;return n==="-->"?c=Ht(ac(i.data,4+r+o)):c=BT(i.data.subarray(4+r+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=c,e}function QT(i){return i.type==="PRIV"?mT(i):i.type[0]==="W"?IT(i):i.type==="APIC"?xT(i):ET(i)}function wT(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Fo(i,4),r=10;return{type:e,size:t,data:i.subarray(r,r+t)}}const No=10,_T=10;function Ff(i){let e=0;const t=[];for(;sc(i,e);){const r=Fo(i,e+6);i[e+5]>>6&1&&(e+=No),e+=No;const n=e+r;for(;e+_T<n;){const s=wT(i.subarray(e)),o=QT(s);o&&t.push(o),e+=s.size+No}wf(i,e)&&(e+=No)}return t}function Pf(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function RT(i){if(i.data.byteLength===8){const e=new Uint8Array(i.data),t=e[3]&1;let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,t&&(r+=4772185884e-2),Math.round(r)}}function lc(i){const e=Ff(i);for(let t=0;t<e.length;t++){const r=e[t];if(Pf(r))return RT(r)}}let Yt=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function Ei(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class cc{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,r,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,r){}demux(e,t){this.cachedData&&(e=jt(this.cachedData,e),this.cachedData=null);let r=zn(e,0),n=r?r.length:0,s;const o=this._audioTrack,a=this._id3Track,c=r?lc(r):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&de(c))&&(this.basePTS=DT(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Yt.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){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=l}else pT(e,n)?(r=zn(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Yt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===l&&s!==l){const u=e.slice(s);this.cachedData?this.cachedData=jt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:Ei(),id3Track:a,textTrack:Ei()}}demuxSampleAes(e,t,r){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:Ei(),id3Track:this._id3Track,textTrack:Ei()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const DT=(i,e,t)=>{if(de(i))return i*90;const r=t?t.baseTime*9e4/t.timescale:0;return e*9e4+r};let Oo=null;const LT=[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],kT=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],MT=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],FT=[0,1,1,4];function Nf(i,e,t,r,n){if(t+24>e.length)return;const s=Of(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=r+n*o,c={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return i.config=[],i.channelCount=s.channelCount,i.samplerate=s.sampleRate,i.samples.push(c),{sample:c,length:s.frameLength,missing:0}}}function Of(i,e){const t=i[e+1]>>3&3,r=i[e+1]>>1&3,n=i[e+2]>>4&15,s=i[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=i[e+2]>>1&1,a=i[e+3]>>6,c=t===3?3-r:r===3?3:4,l=LT[c*14+n-1]*1e3,A=kT[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=MT[t][r],f=FT[r],g=d*8*f,p=Math.floor(d*l/A+o)*f;if(Oo===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Oo=C?parseInt(C[1]):0}return!!Oo&&Oo<=87&&r===2&&l>=224e3&&a===0&&(i[e+3]=i[e+3]|128),{sampleRate:A,channelCount:h,frameLength:p,samplesPerFrame:g}}}function Ac(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Uf(i,e){return e+1<i.length&&Ac(i,e)}function PT(i,e){return Ac(i,e)&&4<=i.length-e}function Gf(i,e){if(e+1<i.length&&Ac(i,e)){const r=Of(i,e);let n=4;r!=null&&r.frameLength&&(n=r.frameLength);const s=e+n;return s===i.length||Uf(i,s)}return!1}class NT extends cc{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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 r=zn(e,0);let n=(r==null?void 0:r.length)||0;if(Gf(e,n))return!1;for(let s=e.length;n<s;n++)if(fT(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return dT(e,t)}appendFrame(e,t,r){Df(e,this.observer,t,r,e.manifestCodec);const n=kf(e,t,r,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const $f=(i,e)=>{let t=0,r=5;e+=r;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=i[e];const a=Math.min(r,8),c=8-a;s[0]=4278190080>>>24+c<<c,n[0]=(o[0]&s[0])>>c,t=t?t<<a|n[0]:n[0],e+=1,r-=a}return t};class OT extends cc{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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,r){const n=Hf(e,t,r,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=zn(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&lc(t)!==void 0&&$f(e,r)<16}}function Hf(i,e,t,r,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],c=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][c*3+s]*2;if(t+u>e.length)return-1;const A=e[t+6]>>5;let h=0;A===2?h+=2:(A&1&&A!==1&&(h+=2),A&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][A]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|A<<3|d<<2|c>>4,c<<4&224]),C=1536/a*9e4,y=r+n*C,x=e.subarray(t,t+u);return i.config=B,i.channelCount=g,i.samplerate=a,i.samples.push({unit:x,pts:y}),u}class UT extends cc{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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=zn(e,0);let r=(t==null?void 0:t.length)||0;if(t&&e[r]===11&&e[r+1]===119&&lc(t)!==void 0&&$f(e,r)<=16)return!1;for(let n=e.length;r<n;r++)if(Gf(e,r))return Oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return PT(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return Nf(e,t,r,this.basePTS,this.frameIndex)}}const GT=/\/emsg[-/]ID3/i;class $T{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,r,n){const s=this.videoTrack=Ei("video",1),o=this.audioTrack=Ei("audio",1),a=this.txtTrack=Ei("text",1);if(this.id3Track=Ei("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=yd(e);if(c.video){const{id:l,timescale:u,codec:A,supplemental:h}=c.video;s.id=l,s.timescale=a.timescale=u,s.codec=A,s.supplemental=h}if(c.audio){const{id:l,timescale:u,codec:A}=c.audio;o.id=l,o.timescale=u,o.codec=A}a.id=md.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return OC(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=jt(this.remainderData,e));const a=WC(r);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=r;const o=this.extractID3Track(n,t);return s.samples=Bd(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=Bd(e,t),{videoTrack:t,audioTrack:Ei(),id3Track:n,textTrack:Ei()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=_e(e.samples,["emsg"]);n&&n.forEach(s=>{const o=JC(s);if(GT.test(o.schemeIdUri)){const a=Yf(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=o.payload;r.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:Yt.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Yf(o,t);r.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Yt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){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 Yf(i,e){return de(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class HT{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Hl(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,tr.cbc)}decryptAacSample(e,t,r){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 c=new Uint8Array(a);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)})}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)r.set(e.subarray(s,s+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(r.subarray(n,n+16),s);return e}decryptAvcSample(e,t,r,n,s){const o=Td(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(c=>{s.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)})}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(r>=s.length);r++){const o=s[r];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,r,n,o),!this.decrypter.isSync()))return}}}}class Vf{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r=this.VideoSample,n;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const s=r.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,n=r.length;if(n){const s=r[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let c=0,l,u,A,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,c=1);c<n;){if(l=t[c++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(u=c-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&&c<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=jt(f.data,t.subarray(0,u)),f.state=0))}c<n?(A=this.getNALuType(t,c),h=c,d=A,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=jt(f.data,t))}return e.naluState=s,a}}class Zn{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,r=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(r,r+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 r=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?r<<t|this.readBits(t):r}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 Kf extends Vf{parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let o=this.VideoSample,a,c=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(l=>{var u,A;switch(l.type){case 1:{let g=!1;a=!0;const p=l.data;if(c&&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,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,Pl(l.data,1,r.pts,t.samples);break}case 7:{var d,f;a=!0,c=!0;const g=l.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=[l.data];break;case 9:a=!0,e.audFound=!0,(A=o)!=null&&A.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Zn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(r+s+256)%256),r=n===0?r:n}readSPS(e){const t=new Zn(e);let r=0,n=0,s=0,o=0,a,c,l;const u=t.readUByte.bind(t),A=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(A(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(c=F!==3?8:12,l=0;l<c;l++)d()&&(l<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(),l=0;l<a;l++)g();p(),f(1);const y=h(),x=h(),_=A(1);_===0&&f(1),f(1),d()&&(r=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-r*2-n*2),height:(2-_)*(x+1)*16-(_?2:4)*(s+o),pixelRatio:D}}}class Wf extends Vf{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let o=this.VideoSample,a,c=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(l=>{var u,A;switch(l.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,r.pts,r.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,c){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,Pl(l.data,2,r.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=We(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(l.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,l.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(l.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(A=o)!=null&&A.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Zn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:n}}readSPS(e){const t=new Zn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),A=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<r;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(r>0)for(let ye=r;ye<8;ye++)t.readBits(2);for(let ye=0;ye<r;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(),_=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:r;ye<=r;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 w=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<=w;Xe++){const Ge=t.readBoolean();let $e=!1;Ge||($e=t.readBoolean()),(Ge||$e)&&Ue++}w=Ue}else{const Ue=t.readUEG(),Xe=t.readUEG();w=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,ie=1,re=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let we=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),tt=[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=tt[Ce-1],ie=ot[Ce-1]):Ce===255&&(Y=t.readBits(16),ie=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(),we=t.readBoolean(),we&&(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(),et=t.readBoolean();let ze=!1;(ot||et)&&(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<=r;T++){re=t.readBoolean();const m=re||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(et)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=_;if(D||we){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=_-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Ne=a<<24|c<<16|l<<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,c,l,u],general_constraint_indicator_flags:[A,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:re,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,ie]}}readPPS(e){const t=new Zn(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 Bt=188;class ir{constructor(e,t,r,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=r,this.logger=n,this.videoParser=null}static probe(e,t){const r=ir.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const t=e.length;let r=Math.min(Bt*5,t-Bt)+1,n=0;for(;n<r;){let s=!1,o=-1,a=0;for(let c=n;c<t;c+=Bt)if(e[c]===71&&(t-c===Bt||e[c+Bt]===71)){if(a++,o===-1&&(o=c,o!==0&&(r=Math.min(o+Bt*99,e.length-Bt)+1)),s||(s=uc(e,c)===0),s&&a>1&&(o===0&&a>2||c+Bt>r))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:md[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ir.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=ir.createTrack("audio",n),this._id3Track=ir.createTrack("id3"),this._txtTrack=ir.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,n=!1){r||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,c=this._id3Track,l=this._txtTrack;let u=o.pid,A=o.pesData,h=a.pid,d=c.pid,f=a.pesData,g=c.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=jt(this.remainderData,e),C=e.length,this.remainderData=null),C<Bt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};const y=Math.max(0,ir.syncOffset(e));C-=(C-y)%Bt,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+=Bt)if(e[D]===71){const F=!!(e[D+1]&64),O=uc(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+Bt)continue}else j=D+4;switch(O){case u:if(F){if(A&&(s=qr(A,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new Kf;break;case"hevc":this.videoParser=new Wf;break}this.videoParser!==null&&this.videoParser.parsePES(o,l,s,!1)}A={data:[],size:0}}A&&(A.data.push(e.subarray(j,D+Bt)),A.size+=D+Bt-j);break;case h:if(F){if(f&&(s=qr(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+Bt)),f.size+=D+Bt-j);break;case d:F&&(g&&(s=qr(g,this.logger))&&this.parseID3PES(c,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+Bt)),g.size+=D+Bt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=YT(e,j);break;case B:{F&&(j+=e[j]+1);const X=VT(e,j,this.typeSupported,r,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&&(c.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&&hc(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=A,a.pesData=f,c.pesData=g;const _={audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};return n&&this.extractRemainingSamples(_),_}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:r,id3Track:n,textTrack:s}=e,o=r.pesData,a=t.pesData,c=n.pesData;let l;if(o&&(l=qr(o,this.logger))){if(this.videoParser===null)switch(r.segmentCodec){case"avc":this.videoParser=new Kf;break;case"hevc":this.videoParser=new Wf;break}this.videoParser!==null&&(this.videoParser.parsePES(r,s,l,!0),r.pesData=null)}else r.pesData=o;if(a&&(l=qr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;c&&(l=qr(c,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new HT(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(r=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{r(e)}):r(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{r(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 r=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const A=n.missing,h=n.sample.unit.byteLength;if(A===-1)s=jt(n.sample.unit,s);else{const d=h-A;n.sample.unit.set(s.subarray(0,A),d),e.samples.push(n.sample),r=n.missing}}let o,a;for(o=r,a=s.length;o<a-1&&!Po(s,o);o++);if(o!==r){let A;const h=o<a-1;if(h?A=`AAC PES did not start with ADTS header,offset:${o}`:A="No ADTS header found in AAC PES",hc(this.observer,new Error(A),h,this.logger),!h)return}Df(e,this.observer,s,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(n){const A=Lf(e.samplerate);c=n.sample.pts+A}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,u;for(;o<a;)if(u=kf(e,s,o,c,l),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;o<a-1&&!Po(s,o);o++);}parseMPEGPES(e,t){const r=t.data,n=r.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(Uf(r,o)){const c=Nf(e,r,o,a,s);if(c)o+=c.length,s++;else break}else o++}parseAC3PES(e,t){{const r=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=r.length;let o=0,a=0,c;for(;a<s&&(c=Hf(e,r,a,n,o++))>0;)a+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=We({},t,{type:this._videoTrack?Yt.emsg:Yt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function uc(i,e){return((i[e+1]&31)<<8)+i[e+2]}function YT(i,e){return(i[e+10]&31)<<8|i[e+11]}function VT(i,e,t,r,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(i[e+1]&15)<<8|i[e+2],c=e+3+a-4,l=(i[e+10]&15)<<8|i[e+11];for(e+=12+l;e<c;){const u=uc(i,e),A=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!r){dc("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(!r){dc("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(!r){dc("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&&A>0){let h=e+5,d=A;for(;d>2;){switch(i[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=i[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return hc(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+=A+5}return o}function hc(i,e,t,r){r.warn(`parsing error: ${e.message}`),i.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function dc(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function qr(i,e){let t=0,r,n,s,o,a;const c=i.data;if(!i||i.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=jt(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(n=(r[4]<<8)+r[5],n&&n>i.size-6)return null;const u=r[7];u&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(a=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[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=r[8];let A=s+9;if(i.size<=A)return null;i.size-=A;const h=new Uint8Array(i.size);for(let d=0,f=c.length;d<f;d++){r=c[d];let g=r.byteLength;if(A)if(A>g){A-=g;continue}else r=r.subarray(A),g-=A,A=0;h.set(r,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class KT{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 rr=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]),r=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:r};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]),c=new Uint8Array([0,0,0,1]);H.FTYP=H.box(H.types.ftyp,o,c,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let r=8,n=t.length;const s=n;for(;n--;)r+=t[n].byteLength;const o=new Uint8Array(r);for(o[0]=r>>24&255,o[1]=r>>16&255,o[2]=r>>8&255,o[3]=r&255,o.set(e,4),n=0,r=8;n<s;n++)o.set(t[n],r),r+=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 r=Math.floor(t/(rr+1)),n=Math.floor(t%(rr+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,r>>24,r>>16&255,r>>8&255,r&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,r){return H.box(H.types.moof,H.mfhd(e),H.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(H.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(rr+1)),n=Math.floor(t%(rr+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,r>>24,r>>16&255,r>>8&255,r&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||[],r=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,r[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,r)}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=[],r=[],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,r.push(o>>>8&255),r.push(o&255),r=r.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(r))),c=e.width,l=e.height,u=e.pixelRatio[0],A=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,c>>8&255,c&255,l>>8&255,l&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,A>>24,A>>16&255,A>>8&255,A&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,r=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(r/(rr+1)),a=Math.floor(r%(rr+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 r=H.sdtp(e),n=e.id,s=Math.floor(t/(rr+1)),o=Math.floor(t%(rr+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,r.length+16+20+8+16+8+8),r)}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 r=e.samples||[],n=r.length,s=12+16*n,o=new Uint8Array(s);let a,c,l,u,A,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++)c=r[a],l=c.duration,u=c.size,A=c.flags,h=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,A.isLeading<<2|A.dependsOn,A.isDependedOn<<6|A.hasRedundancy<<4|A.paddingValue<<1|A.isNonSync,A.degradPrio&61440,A.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 jt(H.FTYP,t)}static hvc1(e){const t=e.params,r=[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),r.length]);let o=s.length;for(let f=0;f<r.length;f+=1){o+=3;for(let g=0;g<r[f].length;g+=1)o+=2+r[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const c=r.length-1;for(let f=0;f<r.length;f+=1){a.set(new Uint8Array([32+f|(f===c?128:0),0,r[f].length]),o),o+=3;for(let g=0;g<r[f].length;g+=1)a.set(new Uint8Array([r[f][g].length>>8,r[f][g].length&255]),o),o+=2,a.set(r[f][g],o),o+=r[f][g].length}const l=H.box(H.types.hvcC,a),u=e.width,A=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,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]),l,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 qf=9e4;function fc(i,e,t=1,r=!1){const n=i*e*t;return r?Math.round(n):n}function WT(i,e,t=1,r=!1){return fc(i,e,1/t,r)}function es(i,e=!1){return fc(i,1e3,1/qf,e)}function qT(i,e=1){return fc(i,qf,1/e)}const JT=10*1e3,jT=1024,XT=1152,zT=1536;let Jr=null,gc=null;function Jf(i,e,t,r){return{duration:e,size:t,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class Uo{constructor(e,t,r,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=r,this.logger=n,this.ISGenerated=!1,Jr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jr=o?parseInt(o[1]):0}if(gc===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);gc=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 r=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,c=a-s;return c<-4294967296&&(t=!0,a=Xt(a,r),c=a-s),c>0?s:a},r);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,r,n,s,o,a,c){let l,u,A,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||(A=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=ZT(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=(Xt(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"),A=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||c===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"),A=this.generateIS(e,t,s,o)),l=this.remuxVideo(t,p,j,oe)}}else x&&(l=this.remuxVideo(t,p,j,0));l&&(l.firstKeyFrame=X,l.independent=X!==-1,l.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(d=jf(r,s,this._initPTS,this._initDTS)),n.samples.length&&(h=Xf(n,s,this._initPTS))),{audio:u,video:l,initSegment:A,independent:f,text:h,id3:d}}generateIS(e,t,r,n){const s=e.samples,o=t.samples,a=this.typeSupported,c={},l=this._initPTS;let u=!l||n,A="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?(A="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:A,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!l||f!==l.timescale?h=d=s[0].pts-Math.round(f*r):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,c.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,!l||f!==l.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*r);d=Math.min(d,Xt(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(c).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:c,initPTS:h,timescale:f}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,o=e.samples,a=[],c=o.length,l=this._initPTS;let u=this.nextAvcDts,A=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!r||u===null){const w=t*s,k=o[0].pts-Xt(o[0].dts,o[0].pts);Jr&&u!==null&&Math.abs(w-k-u)<15e3?r=!0:u=w-k}const B=l.baseTime*s/l.timescale;for(let w=0;w<c;w++){const k=o[w];k.pts=Xt(k.pts-B,u),k.dts=Xt(k.dts-B,u),k.dts<o[w>0?w-1:w].dts&&(v=!0)}v&&o.sort(function(w,k){const K=w.dts-k.dts,Y=w.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/(c-1)):h||e.inputTimeScale/30;if(r){const w=d-u,k=w>y,K=w<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${es(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${es(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Jr)){d=u;const Y=o[0].pts-w;if(k)o[0].dts=d,o[0].pts=Y;else{let ie=!0;for(let re=0;re<o.length&&!(o[re].dts>Y&&ie);re++){const he=o[re].pts;if(o[re].dts-=w,o[re].pts-=w,re<o.length-1){const fe=o[re+1].pts,we=o[re].pts,be=fe<=we,Fe=fe<=he;ie=be==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${es(Y,!0)}/${es(d,!0)}, delta: ${es(w,!0)} ms`)}}d=Math.max(0,d);let x=0,_=0,D=d;for(let w=0;w<c;w++){const k=o[w],K=k.units,Y=K.length;let ie=0;for(let re=0;re<Y;re++)ie+=K[re].data.length;_+=ie,x+=Y,k.length=ie,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[c-1].dts;const F=_+4*x+8;let O;try{O=new Uint8Array(F)}catch(w){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:w,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 w=0;w<c;w++){const k=o[w],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const we=K[he],be=we.data,Fe=we.data.byteLength;M.setUint32(A,Fe),A+=4,O.set(be,A),A+=Fe,Y+=4+Fe}let ie;if(w<c-1)h=o[w+1].dts-k.dts,ie=o[w+1].pts-k.pts;else{const he=this.config,fe=w>0?k.dts-o[w-1].dts:y;if(ie=w>0?k.pts-o[w-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const we=Math.floor(he.maxBufferHole*s),be=(n?g+n*s:this.nextAudioPts)-k.pts;be>we?(h=be-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${be/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const re=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,ie),L=Math.max(L,ie),a.push(Jf(k.key,h,Y,re))}if(a.length){if(Jr){if(Jr<70){const w=a[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(gc&&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 w=d;for(let k=0,K=a.length;k<K;k++){const Y=w+a[k].duration,ie=w+a[k].cts;if(k<K-1){const re=Y+a[k+1].cts;a[k].duration=re-ie}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,w=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 XT;case"ac3":return zT;default:return jT}}remuxAudio(e,t,r,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,c=o/a,l=this.getSamplesPerFrame(e),u=l*c,A=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=A.baseTime*o/A.timescale;if(this.isAudioContiguous=r=r||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(Xt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=Xt(U.pts-C,B)}),!r||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 w=g[q],k=w.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<JT&&f){let ie=Math.round(K/u);R=k-ie*u,R<0&&(ie--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let re=0;re<ie;re++){const he=Math.max(R,0);let fe=KT.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=w.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}w.pts=R,R+=u}}let y=null,x=null,_,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],w=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/c)}else if(r&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{_=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(_.buffer).setUint32(0,D),_.set(H.types.mdat,4))}else return;_.set(w,p);const K=w.byteLength;p+=K,d.push(Jf(!0,l,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+c*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/c,We({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:_,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function Xt(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function ZT(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function jf(i,e,t,r){const n=i.samples.length;if(!n)return;const s=i.inputTimeScale;for(let a=0;a<n;a++){const c=i.samples[a];c.pts=Xt(c.pts-t.baseTime*s/t.timescale,e*s)/s,c.dts=Xt(c.dts-r.baseTime*s/r.timescale,e*s)/s}const o=i.samples;return i.samples=[],{samples:o}}function Xf(i,e,t){const r=i.samples.length;if(!r)return;const n=i.inputTimeScale;for(let o=0;o<r;o++){const a=i.samples[o];a.pts=Xt(a.pts-t.baseTime*n/t.timescale,e*n)/n}i.samples.sort((o,a)=>o.pts-a.pts);const s=i.samples;return i.samples=[],{samples:s}}class e1{constructor(e,t,r,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,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment($C(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=yd(e);n.audio&&(t=zf(n.audio,qe.AUDIO)),n.video&&(r=zf(n.video,qe.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+r,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:r,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,r,n,s,o){var a,c;let{initPTS:l,lastEndTime:u}=this;const A={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return A;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((c=f)!=null&&c.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),A;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=YC(h,f),p=HC(f,h),v=p===null?s:p;(o||!l)&&(t1(l,v,s,g)||d.timescale!==l.timescale)&&(d.initPTS=v-s,l&&l.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${l.baseTime/l.timescale} to ${d.initPTS}`),this.initPTS=l={baseTime:d.initPTS,timescale:1});const B=e?v-l.baseTime/l.timescale:u,C=B+g;KC(f,h,l.baseTime/l.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 _="";y&&(_+="audio"),x&&(_+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:_,hasAudio:y,hasVideo:x,nb:1,dropped:0};return A.audio=D.type==="audio"?D:void 0,A.video=D.type!=="audio"?D:void 0,A.initSegment=d,A.id3=jf(r,s,l,l),n.samples.length&&(A.text=Xf(n,s,l)),A}}function t1(i,e,t,r){if(i===null)return!0;const n=Math.max(r,1),s=e-i.baseTime/i.timescale;return Math.abs(s-t)>n}function zf(i,e){const t=i==null?void 0:i.codec;return t&&t.length>4?t:e===qe.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?Co(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 Li;try{Li=self.performance.now.bind(self.performance)}catch{Li=Date.now}const Go=[{demux:$T,remux:e1},{demux:ir,remux:Uo},{demux:NT,remux:Uo},{demux:UT,remux:Uo}];Go.splice(2,0,{demux:OT,remux:Uo});class Zf{constructor(e,t,r,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=r,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=Li();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:u,trackSwitch:A,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=c,y=i1(o,t);if(y&&Kr(y.method)){const F=this.getDecrypter(),O=Kl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(r.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=Li(),pc(r);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,r);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,A);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=Li(),pc(r)}(u||A||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const _=this.transmux(o,y,d,h,r);this.asyncResult=ts(_);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=Li(),_}flush(e){const t=e.transmuxing;t.executeStart=Li();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(r){const A=r.flush();A&&o.push(this.push(A.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=Li();const A=[pc(e)];return this.asyncResult?Promise.resolve(A):A}const u=c.flush(a);return ts(u)?(this.asyncResult=!0,u.then(A=>(this.flushRemux(o,A,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(n,s,o,a,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=Li()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,r,n,s):o=this.transmuxUnencrypted(e,r,n,s),o}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,c,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,r,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let s;for(let A=0,h=Go.length;A<h;A++){var o;if((o=Go[A].demux)!=null&&o.probe(e,this.logger)){s=Go[A];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,c=this.remuxer,l=s.remux,u=s.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(r,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(r,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 Hl(this.config)),e}}function i1(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const pc=i=>({remuxResult:{},chunkMeta:i});function ts(i){return"then"in i&&i.then instanceof Function}class r1{constructor(e,t,r,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=r,this.duration=n,this.defaultInitPts=s||null}}class n1{constructor(e,t,r,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=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}}let eg=0;class tg{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=eg++,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=c=>{const l=c.data,u=this.hls;if(!(!u||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var A;const h=(A=this.workerContext)==null?void 0:A.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{u.logger[l.data.logType]&&u.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,u.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.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:l})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const o=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===I.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new nc,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=wd(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(s.workerPath||aT()){try{s.workerPath?(c.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=cT(s.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=lT());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){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Zf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new Zf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=eg++;const t=this.hls.config,r=wd(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,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),AT(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,r,n,s,o,a,c,l,u){var A,h;l.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&&l.level===v.level),y=v?l.sn-v.sn:-1,x=this.part?l.part-this.part.index:-1,_=y===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||_&&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&&((A=s.initSegment)==null?void 0:A.url)===((h=v.initSegment)==null?void 0:h.url)),M=new n1(B,D,c,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${l.level} id: ${l.id}
2500
+ ${t.m3u8}`)}function mf(i,e,t=!0){const r=e.startSN+e.skippedSegments-i.startSN,n=i.fragments,s=r>=0;let o=0;if(s&&r<n.length)o=n[r].start;else if(s&&e.startSN===i.endSN+1)o=i.fragmentEnd;else if(s&&t)o=i.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=i.fragmentStart;else return;tc(e,o)}function tc(i,e){if(e){const t=i.fragments;for(let r=i.skippedSegments;r<t.length;r++)t[r].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function Ef(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const r=i.fragments;if(r.length&&t*4>e){const s=r[r.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function If(i,e,t){if(!i)return null;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e)?r:e<i.startSN&&t&&t.sn===e?t:null}function vf(i,e,t){return i?yf(i.partList,e,t):null}function yf(i,e,t){if(i)for(let r=i.length;r--;){const n=i[r];if(n.index===t&&n.fragment.sn===e)return n}return null}function Cf(i){i.forEach((e,t)=>{var r;(r=e.details)==null||r.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function jn(i,e){for(let r=0,n=i.length;r<n;r++){var t;if(((t=i[r])==null?void 0:t.cc)===e)return i[r]}return null}function tT(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function Bf(i,e){if(i){const t=i.start+e;i.start=i.startPTS=t,i.endPTS=t+i.duration}}function Tf(i,e){const t=e.fragments;for(let r=0,n=t.length;r<n;r++)Bf(t[r],i);e.fragmentHint&&Bf(e.fragmentHint,i),e.alignedSliding=!0}function iT(i,e){i&&(bf(e,i),!e.alignedSliding&&i&&Mo(e,i),!e.alignedSliding&&i&&!e.skippedSegments&&mf(i,e,!1))}function bf(i,e){if(!tT(e,i))return;const t=Math.min(e.endCC,i.endCC),r=jn(e.fragments,t),n=jn(i.fragments,t);if(!r||!n)return;Oe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=r.start-n.start;Tf(s,i)}function Mo(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,r=e.fragments;if(!t.length||!r.length)return;let n,s;const o=Math.min(e.endCC,i.endCC);e.startCC<o&&i.startCC<o&&(n=jn(r,o),s=jn(t,o)),(!n||!s)&&(n=r[Math.floor(r.length/2)],s=jn(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,c=s.programDateTime;if(!a||!c)return;const l=(c-a)/1e3-(s.start-n.start);Tf(l,i)}const rT={toString:function(i){let e="";const t=i.length;for(let r=0;r<t;r++)e+=`[${i.start(r).toFixed(3)}-${i.end(r).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 ic extends Jd{constructor(e,t,r,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:c,mediaBuffer:l,state:u}=this,A=c?c.currentTime:0,h=Le.bufferInfo(l||c,A,o.maxBufferHole);if(this.log(`media seeking to ${de(A)?A.toFixed(3):A}, 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=A>g;(A<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(c){this.fragmentTracker.removeFragmentsInRange(A,1/0,this.playlistType,!0);const d=this.lastCurrentTime;if(A>d&&(this.lastCurrentTime=A),!this.loadingParts){const f=Math.max(h.end,A),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${A.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${A} because of seek before start`),this.nextLoadPosition=this.startPosition=A),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 RB(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Hl(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 r=e.end||0,n=this.config.timelineOffset||0;if(r<=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 l=a[a.length-1];return Le.isBuffered(this.media,l.start+l.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}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 r=this.media=this.mediaBuffer=t.media;r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),r.addEventListener("seeking",this.onMediaSeeking),r.addEventListener("ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!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&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){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,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){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,r,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:r}=this;if(r.getState(e)===It.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===It.PARTIAL&&r.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,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(I.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const n=r==null?void 0:r.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:n}=this,{frag:s,payload:o}=r,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Kr(a.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,Kl(a.method)).catch(l=>{throw n.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:s}),l}).then(l=>{const u=self.performance.now();return n.trigger(I.FRAG_DECRYPTED,{frag:s,payload:l,stats:{tstart:c,tdecrypt:u}}),r.payload=l,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.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 r=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:${r?rT.toString(Le.getBuffered(r)):"(detached)"})`),Ct(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:r,part:n,partsLoaded:s}=e,o=!s||s.length===0||s.some(c=>!c),a=new Yl(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=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(A=>{if(!this.fragContextChanged(A.frag))return this.hls.trigger(I.KEY_LOADED,A),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),A}),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 c=this.fragPrevious;if(Ct(e)&&(!c||e.sn!==c.sn)){const A=this.shouldLoadParts(t.details,e.end);A!==this.loadingParts&&(this.log(`LL-Part loading ${A?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=A)}if(r=Math.max(e.start,r||0),this.loadingParts&&Ct(e)){const A=o.partList;if(A&&n){r>e.end&&o.fragmentHint&&(e=o.fragmentHint);const h=this.getNextPart(A,e,r);if(h>-1){const d=A[h];e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${h}/${A.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(r.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:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(A,r))return Promise.resolve(null)}}if(Ct(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.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(r.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;const l=this.config.progressive;let u;return l&&a?u=a.then(A=>!A||this.fragContextChanged(A==null?void 0:A.frag)?null:this.fragmentLoader.load(e,n)).catch(A=>this.handleFragLoadError(A)):u=Promise.all([this.fragmentLoader.load(e,l?n:void 0),a]).then(([A])=>(!l&&A&&n&&n(A),A)).catch(A=>this.handleFragLoadError(A)),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,r,n){return new Promise((s,o)=>{var a;const c=[],l=(a=r.details)==null?void 0:a.partList,u=A=>{this.fragmentLoader.loadPart(e,A,n).then(h=>{c[A.index]=h;const d=h.part;this.hls.trigger(I.FRAG_LOADED,h);const f=vf(r.details,e.sn,A.index+1)||yf(l,e.sn,A.index+1);if(f)u(f);else return s({frag:e,part:d,partsLoaded:c})}).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:r,part:n,level:s}=t,o=self.performance.now();r.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),l=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(r,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var r;const s=e.partList[0],o=s.end+(((r=e.fragmentHint)==null?void 0:r.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:r}=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],c=a.details,l=o>-1?vf(c,s,o):null,u=l?l.fragment:If(c,s,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:a}):null}bufferFragmentData(e,t,r,n,s){var o;if(!e||this.state!==Z.PARSING)return;const{data1:a,data2:c}=e;let l=a;if(a&&c&&(l=jt(a,c)),!((o=l)!=null&&o.length))return;const u={type:e.type,frag:t,part:r,chunkMeta:n,parent:t.type,data:l};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!r){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 r=t.currentTime,n=Le.bufferInfo(t,r,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,n.end-o),r+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!de(n))return null;const o=this.lastCurrentTime>n||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,r,n){const s=Le.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,r);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 r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-t*3,r.maxMaxBufferLength/2,n);return s>=n?(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Ee.MAIN){var r;const n=(r=this.fragmentTracker)==null?void 0:r.getAppendedFrag(e,t);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:s}=this,o=r[0].start,a=s.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const A=s.initialLiveManifestSize;if(n<A)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${A})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t,r);const h=this.hls.startPosition,d=this.hls.liveSyncPosition,f=c?(h!==-1&&h>=o?h:d)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${d} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=o&&(c=r[0]);if(!c){const A=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,A,t)}let u=this.filterReplacedPrimary(c,t);if(!u&&c){const A=c.sn-t.startSN;u=this.filterReplacedPrimary(r[A+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===It.OK||r===It.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&r.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(a!==null&&r.len+a.len>=s){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(Sf(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(Sf(this.hls.config)&&e.type!==Ee.SUBTITLE){const r=this.hls.interstitialsManager,n=r==null?void 0:r.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=r==null?void 0:r.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,r){let n=-1,s=!1,o=!0;for(let a=0,c=e.length;a<c;a++){const l=e[a];if(o=o&&!l.independent,n>-1&&r<l.start)break;const u=l.loaded;u?n=-1:(s||l.independent||o)&&l.fragment===t&&(n=a),s=u}return n}loadedEndOfParts(e,t){const r=e[e.length-1];return r&&t>r.start&&r.loaded}getInitialLiveFragment(e,t){const r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=EB(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];r.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=$d(t,r.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,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:l}=n,u=r.partList,A=!!(this.loadingParts&&u!=null&&u.length&&c);A&&c&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(o=o.concat(c),a=c.sn);let h;if(e<t){var d;const g=e<this.lastCurrentTime||e>t-l||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:l;h=br(s,o,e,g)}else h=o[o.length-1];if(h){const f=h.sn-r.startSN,g=this.fragmentTracker.getState(h);if((g===It.OK||g===It.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!A||u[0].fragment.sn>h.sn||!r.live&&!A)&&s&&h.level===s.level){const v=o[f+1];h.sn<a&&this.fragmentTracker.getState(v)!==It.OK?h=v:h=null}}return h}alignPlaylists(e,t,r){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){iT(r,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),c}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(r===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&de(o)?(r=t+o,o<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ct(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 r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const s=t.details===V.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const o=t.errorAction,{action:a,flags:c,retryCount:l=0,retryConfig:u}=o||{},A=!!o&&!!u,h=A&&a===Dt.RetryRequest,d=A&&!o.resolved&&c===oi.MoveAllAlternatesMatchingHost;if(!h&&d&&Ct(r)&&!r.endList)this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((h||d)&&l<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=$l(u,l);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${l+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),l<u.maxNumRetry)!s&&a!==Dt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${l})`);return}else a===Dt.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,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),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 ${r} 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,r){if(!e)return;const n=Le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),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,r,n){const s=r.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const u=e.elementaryStreams[l];if(u){const A=u.endPTS-u.startPTS;if(A<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${A})`),c||!1;const h=n?0:gf(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:s,level:r,drift:h,type:l,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var a;if(r.fragmentError===0&&this.treatAsGap(e,r),((a=this.transmuxer)==null?void 0:a.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.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,r){var n,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((n=t&&!r?e.startPTS:(r||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!r?e.endPTS:(r||e).end)!=null?s:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.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 Sf(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class xf{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;if(e.length)e.length===1?r=e[0]:r=nT(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function nT(i,e){const t=new Uint8Array(e);let r=0;for(let n=0;n<i.length;n++){const s=i[n];t.set(s,r),r+=s.length}return t}var rc={exports:{}},Qf;function sT(){return Qf||(Qf=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function s(c,l,u,A,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var d=new n(u,A||c,h),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],d]:c._events[f].push(d):(c._events[f]=d,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,A;if(this._eventsCount===0)return l;for(A in u=this._events)e.call(u,A)&&l.push(t?A.slice(1):A);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=t?t+l:l,A=this._events[u];if(!A)return[];if(A.fn)return[A.fn];for(var h=0,d=A.length,f=new Array(d);h<d;h++)f[h]=A[h].fn;return f},a.prototype.listenerCount=function(l){var u=t?t+l:l,A=this._events[u];return A?A.fn?1:A.length:0},a.prototype.emit=function(l,u,A,h,d,f){var g=t?t+l:l;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,B,C;if(p.fn){switch(p.once&&this.removeListener(l,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,A),!0;case 4:return p.fn.call(p.context,u,A,h),!0;case 5:return p.fn.call(p.context,u,A,h,d),!0;case 6:return p.fn.call(p.context,u,A,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(l,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,A);break;case 4:p[C].fn.call(p[C].context,u,A,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(l,u,A){return s(this,l,u,A,!1)},a.prototype.once=function(l,u,A){return s(this,l,u,A,!0)},a.prototype.removeListener=function(l,u,A,h){var d=t?t+l:l;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)&&(!A||f.context===A)&&o(this,d);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==u||h&&!f[g].once||A&&f[g].context!==A)&&p.push(f[g]);p.length?this._events[d]=p.length===1?p[0]:p:o(this,d)}return this},a.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&o(this,u)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a}(rc)),rc.exports}var oT=sT(),nc=kC(oT);const Xn="1.6.2",Wr={};function aT(){return typeof __HLS_WORKER_BUNDLE__=="function"}function lT(){const i=Wr[Xn];if(i)return i.clientCount++,i;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 Wr[Xn]=n,n}function cT(i){const e=Wr[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wr[i]=n,n}function AT(i){const e=Wr[i||Xn];if(e&&e.clientCount--===1){const{worker:r,objectURL:n}=e;delete Wr[i||Xn],n&&self.URL.revokeObjectURL(n),r.terminate()}}function wf(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function sc(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Fo(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function zn(i,e){const t=e;let r=0;for(;sc(i,e);){r+=10;const n=Fo(i,e+6);r+=n,wf(i,e+10)&&(r+=10),e+=r}if(r>0)return i.subarray(t,t+r)}function uT(i,e,t,r){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}`);i.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,c=e[t+3]>>6&3|(s&1)<<2,l="mp4a.40."+a,u=n[o];let A=o;(a===5||a===29)&&(A-=3);const h=[a<<3|(A&14)>>1,(A&1)<<7|c<<3];return Oe.log(`manifest codec:${r}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:r}}function _f(i,e){return i[e]===255&&(i[e+1]&246)===240}function Rf(i,e){return i[e+1]&1?7:9}function oc(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function hT(i,e){return e+5<i.length}function Po(i,e){return e+1<i.length&&_f(i,e)}function dT(i,e){return hT(i,e)&&_f(i,e)&&oc(i,e)<=i.length-e}function fT(i,e){if(Po(i,e)){const t=Rf(i,e);if(e+t>=i.length)return!1;const r=oc(i,e);if(r<=t)return!1;const n=e+r;return n===i.length||Po(i,n)}return!1}function Df(i,e,t,r,n){if(!i.samplerate){const s=uT(e,t,r,n);if(!s)return;We(i,s)}}function Lf(i){return 9216e4/i}function gT(i,e){const t=Rf(i,e);if(e+t<=i.length){const r=oc(i,e)-t;if(r>0)return{headerLength:t,frameLength:r}}}function kf(i,e,t,r,n){const s=Lf(i.samplerate),o=r+n*s,a=gT(e,t);let c;if(a){const{frameLength:A,headerLength:h}=a,d=h+A,f=Math.max(0,t+d-e.length);f?(c=new Uint8Array(d-h),c.set(e.subarray(t+h,e.length),0)):c=e.subarray(t+h,t+d);const g={unit:c,pts:o};return f||i.samples.push(g),{sample:g,length:d,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:l,missing:-1}}function pT(i,e){return sc(i,e)&&Fo(i,e+6)+10<=i.length-e}function mT(i){if(i.size<2)return;const e=Ht(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function ET(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const r=Ht(i.data.subarray(t),!0);t+=r.length+1;const n=Ht(i.data.subarray(t));return{key:i.type,info:r,data:n}}const e=Ht(i.data.subarray(1));return{key:i.type,info:"",data:e}}function IT(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const r=Ht(i.data.subarray(t),!0);t+=r.length+1;const n=Ht(i.data.subarray(t));return{key:i.type,info:r,data:n}}const e=Ht(i.data);return{key:i.type,info:"",data:e}}function vT(i){return btoa(String.fromCharCode(...i))}function Mf(i,e){if(i<0)return-Mf(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const n=Math.floor(i*t);return(n%2===0?n:n+1)/t}else return Math.round(i*t)/t}function yT(i,e){const t=new URL(i),r=new URL(e);if(t.origin!==r.origin)return i;const n=t.pathname.split("/").slice(1),s=r.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 CT(){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 BT(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function ac(i,e=0,t=1/0){return TT(i,e,t,Uint8Array)}function TT(i,e,t,r){const n=bT(i);let s=1;"BYTES_PER_ELEMENT"in r&&(s=r.BYTES_PER_ELEMENT);const o=ST(i)?i.byteOffset:0,a=(o+i.byteLength)/s,c=(o+e)/s,l=Math.floor(Math.max(0,Math.min(c,a))),u=Math.floor(Math.min(l+Math.max(t,0),a));return new r(n,l,u-l)}function bT(i){return i instanceof ArrayBuffer?i:i.buffer}function ST(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function xT(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const r=i.data.subarray(1).indexOf(0);if(r===-1)return;const n=Ht(ac(i.data,1,r)),s=i.data[2+r],o=i.data.subarray(3+r).indexOf(0);if(o===-1)return;const a=Ht(ac(i.data,3+r,o));let c;return n==="-->"?c=Ht(ac(i.data,4+r+o)):c=BT(i.data.subarray(4+r+o)),e.mimeType=n,e.pictureType=s,e.description=a,e.data=c,e}function QT(i){return i.type==="PRIV"?mT(i):i.type[0]==="W"?IT(i):i.type==="APIC"?xT(i):ET(i)}function wT(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Fo(i,4),r=10;return{type:e,size:t,data:i.subarray(r,r+t)}}const No=10,_T=10;function Ff(i){let e=0;const t=[];for(;sc(i,e);){const r=Fo(i,e+6);i[e+5]>>6&1&&(e+=No),e+=No;const n=e+r;for(;e+_T<n;){const s=wT(i.subarray(e)),o=QT(s);o&&t.push(o),e+=s.size+No}wf(i,e)&&(e+=No)}return t}function Pf(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function RT(i){if(i.data.byteLength===8){const e=new Uint8Array(i.data),t=e[3]&1;let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,t&&(r+=4772185884e-2),Math.round(r)}}function lc(i){const e=Ff(i);for(let t=0;t<e.length;t++){const r=e[t];if(Pf(r))return RT(r)}}let Yt=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function Ei(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class cc{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,r,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,r){}demux(e,t){this.cachedData&&(e=jt(this.cachedData,e),this.cachedData=null);let r=zn(e,0),n=r?r.length:0,s;const o=this._audioTrack,a=this._id3Track,c=r?lc(r):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&de(c))&&(this.basePTS=DT(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Yt.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){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=l}else pT(e,n)?(r=zn(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Yt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===l&&s!==l){const u=e.slice(s);this.cachedData?this.cachedData=jt(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:Ei(),id3Track:a,textTrack:Ei()}}demuxSampleAes(e,t,r){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:Ei(),id3Track:this._id3Track,textTrack:Ei()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const DT=(i,e,t)=>{if(de(i))return i*90;const r=t?t.baseTime*9e4/t.timescale:0;return e*9e4+r};let Oo=null;const LT=[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],kT=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],MT=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],FT=[0,1,1,4];function Nf(i,e,t,r,n){if(t+24>e.length)return;const s=Of(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=r+n*o,c={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return i.config=[],i.channelCount=s.channelCount,i.samplerate=s.sampleRate,i.samples.push(c),{sample:c,length:s.frameLength,missing:0}}}function Of(i,e){const t=i[e+1]>>3&3,r=i[e+1]>>1&3,n=i[e+2]>>4&15,s=i[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&s!==3){const o=i[e+2]>>1&1,a=i[e+3]>>6,c=t===3?3-r:r===3?3:4,l=LT[c*14+n-1]*1e3,A=kT[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,d=MT[t][r],f=FT[r],g=d*8*f,p=Math.floor(d*l/A+o)*f;if(Oo===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Oo=C?parseInt(C[1]):0}return!!Oo&&Oo<=87&&r===2&&l>=224e3&&a===0&&(i[e+3]=i[e+3]|128),{sampleRate:A,channelCount:h,frameLength:p,samplesPerFrame:g}}}function Ac(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Uf(i,e){return e+1<i.length&&Ac(i,e)}function PT(i,e){return Ac(i,e)&&4<=i.length-e}function Gf(i,e){if(e+1<i.length&&Ac(i,e)){const r=Of(i,e);let n=4;r!=null&&r.frameLength&&(n=r.frameLength);const s=e+n;return s===i.length||Uf(i,s)}return!1}class NT extends cc{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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 r=zn(e,0);let n=(r==null?void 0:r.length)||0;if(Gf(e,n))return!1;for(let s=e.length;n<s;n++)if(fT(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return dT(e,t)}appendFrame(e,t,r){Df(e,this.observer,t,r,e.manifestCodec);const n=kf(e,t,r,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const $f=(i,e)=>{let t=0,r=5;e+=r;const n=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=i[e];const a=Math.min(r,8),c=8-a;s[0]=4278190080>>>24+c<<c,n[0]=(o[0]&s[0])>>c,t=t?t<<a|n[0]:n[0],e+=1,r-=a}return t};class OT extends cc{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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,r){const n=Hf(e,t,r,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=zn(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&lc(t)!==void 0&&$f(e,r)<16}}function Hf(i,e,t,r,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],c=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][c*3+s]*2;if(t+u>e.length)return-1;const A=e[t+6]>>5;let h=0;A===2?h+=2:(A&1&&A!==1&&(h+=2),A&4&&(h+=2));const d=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][A]+d,p=e[t+5]>>3,v=e[t+5]&7,B=new Uint8Array([s<<6|p<<1|v>>2,(v&3)<<6|A<<3|d<<2|c>>4,c<<4&224]),C=1536/a*9e4,y=r+n*C,x=e.subarray(t,t+u);return i.config=B,i.channelCount=g,i.samplerate=a,i.samples.push({unit:x,pts:y}),u}class UT extends cc{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,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=zn(e,0);let r=(t==null?void 0:t.length)||0;if(t&&e[r]===11&&e[r+1]===119&&lc(t)!==void 0&&$f(e,r)<=16)return!1;for(let n=e.length;r<n;r++)if(Gf(e,r))return Oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return PT(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return Nf(e,t,r,this.basePTS,this.frameIndex)}}const GT=/\/emsg[-/]ID3/i;class $T{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,r,n){const s=this.videoTrack=Ei("video",1),o=this.audioTrack=Ei("audio",1),a=this.txtTrack=Ei("text",1);if(this.id3Track=Ei("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=yd(e);if(c.video){const{id:l,timescale:u,codec:A,supplemental:h}=c.video;s.id=l,s.timescale=a.timescale=u,s.codec=A,s.supplemental=h}if(c.audio){const{id:l,timescale:u,codec:A}=c.audio;o.id=l,o.timescale=u,o.codec=A}a.id=md.text,s.sampleDuration=0,s.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return OC(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=jt(this.remainderData,e));const a=WC(r);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=r;const o=this.extractID3Track(n,t);return s.samples=Bd(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=Bd(e,t),{videoTrack:t,audioTrack:Ei(),id3Track:n,textTrack:Ei()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=_e(e.samples,["emsg"]);n&&n.forEach(s=>{const o=JC(s);if(GT.test(o.schemeIdUri)){const a=Yf(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=o.payload;r.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:Yt.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Yf(o,t);r.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Yt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){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 Yf(i,e){return de(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class HT{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Hl(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,tr.cbc)}decryptAacSample(e,t,r){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 c=new Uint8Array(a);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)})}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)r.set(e.subarray(s,s+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(r.subarray(n,n+16),s);return e}decryptAvcSample(e,t,r,n,s){const o=Td(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(c=>{s.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)})}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(r>=s.length);r++){const o=s[r];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,r,n,o),!this.decrypter.isSync()))return}}}}class Vf{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r=this.VideoSample,n;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const s=r.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,n=r.length;if(n){const s=r[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let s=e.naluState||0;const o=s,a=[];let c=0,l,u,A,h=-1,d=0;for(s===-1&&(h=0,d=this.getNALuType(t,0),s=0,c=1);c<n;){if(l=t[c++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(u=c-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&&c<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),u>0&&(f.data=jt(f.data,t.subarray(0,u)),f.state=0))}c<n?(A=this.getNALuType(t,c),h=c,d=A,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=jt(f.data,t))}return e.naluState=s,a}}class Zn{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,r=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(r,r+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 r=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?r<<t|this.readBits(t):r}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 Kf extends Vf{parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let o=this.VideoSample,a,c=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(l=>{var u,A;switch(l.type){case 1:{let g=!1;a=!0;const p=l.data;if(c&&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,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,Pl(l.data,1,r.pts,t.samples);break}case 7:{var d,f;a=!0,c=!0;const g=l.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=[l.data];break;case 9:a=!0,e.audFound=!0,(A=o)!=null&&A.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Zn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,n=8,s;for(let o=0;o<e;o++)n!==0&&(s=t.readEG(),n=(r+s+256)%256),r=n===0?r:n}readSPS(e){const t=new Zn(e);let r=0,n=0,s=0,o=0,a,c,l;const u=t.readUByte.bind(t),A=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(A(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(c=F!==3?8:12,l=0;l<c;l++)d()&&(l<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(),l=0;l<a;l++)g();p(),f(1);const y=h(),x=h(),_=A(1);_===0&&f(1),f(1),d()&&(r=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-r*2-n*2),height:(2-_)*(x+1)*16-(_?2:4)*(s+o),pixelRatio:D}}}class Wf extends Vf{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let o=this.VideoSample,a,c=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(l=>{var u,A;switch(l.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,r.pts,r.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,c){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,Pl(l.data,2,r.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=We(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(l.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,l.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(l.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(A=o)!=null&&A.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Zn(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:n}}readSPS(e){const t=new Zn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),A=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<r;ye++)B.push(t.readBoolean()),C.push(t.readBoolean());if(r>0)for(let ye=r;ye<8;ye++)t.readBits(2);for(let ye=0;ye<r;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(),_=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:r;ye<=r;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 w=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<=w;Xe++){const Ge=t.readBoolean();let $e=!1;Ge||($e=t.readBoolean()),(Ge||$e)&&Ue++}w=Ue}else{const Ue=t.readUEG(),Xe=t.readUEG();w=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,ie=1,re=!0,he=1,fe=0;t.readBoolean(),t.readBoolean();let we=!1;if(t.readBoolean()){if(t.readBoolean()){const Ce=t.readUByte(),tt=[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=tt[Ce-1],ie=ot[Ce-1]):Ce===255&&(Y=t.readBits(16),ie=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(),we=t.readBoolean(),we&&(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(),et=t.readBoolean();let ze=!1;(ot||et)&&(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<=r;T++){re=t.readBoolean();const m=re||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(et)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=_;if(D||we){let ye=1,ke=1;y===1?ye=ke=2:y==2&&(ye=2),Fe=x-ye*O-ye*F,pe=_-ke*j-ke*M}const Qe=n?["A","B","C"][n]:"",Ne=a<<24|c<<16|l<<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,c,l,u],general_constraint_indicator_flags:[A,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:re,fps:fe/he}},width:Fe,height:pe,pixelRatio:[Y,ie]}}readPPS(e){const t=new Zn(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 Bt=188;class ir{constructor(e,t,r,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=r,this.logger=n,this.videoParser=null}static probe(e,t){const r=ir.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const t=e.length;let r=Math.min(Bt*5,t-Bt)+1,n=0;for(;n<r;){let s=!1,o=-1,a=0;for(let c=n;c<t;c+=Bt)if(e[c]===71&&(t-c===Bt||e[c+Bt]===71)){if(a++,o===-1&&(o=c,o!==0&&(r=Math.min(o+Bt*99,e.length-Bt)+1)),s||(s=uc(e,c)===0),s&&a>1&&(o===0&&a>2||c+Bt>r))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:md[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ir.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=ir.createTrack("audio",n),this._id3Track=ir.createTrack("id3"),this._txtTrack=ir.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,n=!1){r||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,c=this._id3Track,l=this._txtTrack;let u=o.pid,A=o.pesData,h=a.pid,d=c.pid,f=a.pesData,g=c.pesData,p=null,v=this.pmtParsed,B=this._pmtId,C=e.length;if(this.remainderData&&(e=jt(this.remainderData,e),C=e.length,this.remainderData=null),C<Bt&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};const y=Math.max(0,ir.syncOffset(e));C-=(C-y)%Bt,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+=Bt)if(e[D]===71){const F=!!(e[D+1]&64),O=uc(e,D),M=(e[D+3]&48)>>4;let j;if(M>1){if(j=D+5+e[D+4],j===D+Bt)continue}else j=D+4;switch(O){case u:if(F){if(A&&(s=qr(A,this.logger))){if(this.videoParser===null)switch(o.segmentCodec){case"avc":this.videoParser=new Kf;break;case"hevc":this.videoParser=new Wf;break}this.videoParser!==null&&this.videoParser.parsePES(o,l,s,!1)}A={data:[],size:0}}A&&(A.data.push(e.subarray(j,D+Bt)),A.size+=D+Bt-j);break;case h:if(F){if(f&&(s=qr(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+Bt)),f.size+=D+Bt-j);break;case d:F&&(g&&(s=qr(g,this.logger))&&this.parseID3PES(c,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(j,D+Bt)),g.size+=D+Bt-j);break;case 0:F&&(j+=e[j]+1),B=this._pmtId=YT(e,j);break;case B:{F&&(j+=e[j]+1);const X=VT(e,j,this.typeSupported,r,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&&(c.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&&hc(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=A,a.pesData=f,c.pesData=g;const _={audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};return n&&this.extractRemainingSamples(_),_}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:r,id3Track:n,textTrack:s}=e,o=r.pesData,a=t.pesData,c=n.pesData;let l;if(o&&(l=qr(o,this.logger))){if(this.videoParser===null)switch(r.segmentCodec){case"avc":this.videoParser=new Kf;break;case"hevc":this.videoParser=new Wf;break}this.videoParser!==null&&(this.videoParser.parsePES(r,s,l,!0),r.pesData=null)}else r.pesData=o;if(a&&(l=qr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;c&&(l=qr(c,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new HT(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise(r=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{r(e)}):r(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{r(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 r=0;const n=this.aacOverFlow;let s=t.data;if(n){this.aacOverFlow=null;const A=n.missing,h=n.sample.unit.byteLength;if(A===-1)s=jt(n.sample.unit,s);else{const d=h-A;n.sample.unit.set(s.subarray(0,A),d),e.samples.push(n.sample),r=n.missing}}let o,a;for(o=r,a=s.length;o<a-1&&!Po(s,o);o++);if(o!==r){let A;const h=o<a-1;if(h?A=`AAC PES did not start with ADTS header,offset:${o}`:A="No ADTS header found in AAC PES",hc(this.observer,new Error(A),h,this.logger),!h)return}Df(e,this.observer,s,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(n){const A=Lf(e.samplerate);c=n.sample.pts+A}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,u;for(;o<a;)if(u=kf(e,s,o,c,l),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;o<a-1&&!Po(s,o);o++);}parseMPEGPES(e,t){const r=t.data,n=r.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(Uf(r,o)){const c=Nf(e,r,o,a,s);if(c)o+=c.length,s++;else break}else o++}parseAC3PES(e,t){{const r=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=r.length;let o=0,a=0,c;for(;a<s&&(c=Hf(e,r,a,n,o++))>0;)a+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=We({},t,{type:this._videoTrack?Yt.emsg:Yt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function uc(i,e){return((i[e+1]&31)<<8)+i[e+2]}function YT(i,e){return(i[e+10]&31)<<8|i[e+11]}function VT(i,e,t,r,n,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(i[e+1]&15)<<8|i[e+2],c=e+3+a-4,l=(i[e+10]&15)<<8|i[e+11];for(e+=12+l;e<c;){const u=uc(i,e),A=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!r){dc("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(!r){dc("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(!r){dc("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&&A>0){let h=e+5,d=A;for(;d>2;){switch(i[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=i[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return hc(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+=A+5}return o}function hc(i,e,t,r){r.warn(`parsing error: ${e.message}`),i.emit(I.ERROR,I.ERROR,{type:Ie.MEDIA_ERROR,details:V.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function dc(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function qr(i,e){let t=0,r,n,s,o,a;const c=i.data;if(!i||i.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=jt(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(n=(r[4]<<8)+r[5],n&&n>i.size-6)return null;const u=r[7];u&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(a=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[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=r[8];let A=s+9;if(i.size<=A)return null;i.size-=A;const h=new Uint8Array(i.size);for(let d=0,f=c.length;d<f;d++){r=c[d];let g=r.byteLength;if(A)if(A>g){A-=g;continue}else r=r.subarray(A),g-=A,A=0;h.set(r,t),t+=g}return n&&(n-=s+3),{data:h,pts:o,dts:a,len:n}}return null}class KT{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 rr=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]),r=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:r};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]),c=new Uint8Array([0,0,0,1]);H.FTYP=H.box(H.types.ftyp,o,c,o,a),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let r=8,n=t.length;const s=n;for(;n--;)r+=t[n].byteLength;const o=new Uint8Array(r);for(o[0]=r>>24&255,o[1]=r>>16&255,o[2]=r>>8&255,o[3]=r&255,o.set(e,4),n=0,r=8;n<s;n++)o.set(t[n],r),r+=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 r=Math.floor(t/(rr+1)),n=Math.floor(t%(rr+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,r>>24,r>>16&255,r>>8&255,r&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,r){return H.box(H.types.moof,H.mfhd(e),H.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(H.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(rr+1)),n=Math.floor(t%(rr+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,r>>24,r>>16&255,r>>8&255,r&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||[],r=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,r[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return H.box(H.types.sdtp,r)}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=[],r=[],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,r.push(o>>>8&255),r.push(o&255),r=r.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(r))),c=e.width,l=e.height,u=e.pixelRatio[0],A=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,c>>8&255,c&255,l>>8&255,l&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,A>>24,A>>16&255,A>>8&255,A&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,r=(e.duration||0)*(e.timescale||0),n=e.width||0,s=e.height||0,o=Math.floor(r/(rr+1)),a=Math.floor(r%(rr+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 r=H.sdtp(e),n=e.id,s=Math.floor(t/(rr+1)),o=Math.floor(t%(rr+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,r.length+16+20+8+16+8+8),r)}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 r=e.samples||[],n=r.length,s=12+16*n,o=new Uint8Array(s);let a,c,l,u,A,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++)c=r[a],l=c.duration,u=c.size,A=c.flags,h=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,A.isLeading<<2|A.dependsOn,A.isDependedOn<<6|A.hasRedundancy<<4|A.paddingValue<<1|A.isNonSync,A.degradPrio&61440,A.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 jt(H.FTYP,t)}static hvc1(e){const t=e.params,r=[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),r.length]);let o=s.length;for(let f=0;f<r.length;f+=1){o+=3;for(let g=0;g<r[f].length;g+=1)o+=2+r[f][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const c=r.length-1;for(let f=0;f<r.length;f+=1){a.set(new Uint8Array([32+f|(f===c?128:0),0,r[f].length]),o),o+=3;for(let g=0;g<r[f].length;g+=1)a.set(new Uint8Array([r[f][g].length>>8,r[f][g].length&255]),o),o+=2,a.set(r[f][g],o),o+=r[f][g].length}const l=H.box(H.types.hvcC,a),u=e.width,A=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,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]),l,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 qf=9e4;function fc(i,e,t=1,r=!1){const n=i*e*t;return r?Math.round(n):n}function WT(i,e,t=1,r=!1){return fc(i,e,1/t,r)}function es(i,e=!1){return fc(i,1e3,1/qf,e)}function qT(i,e=1){return fc(i,qf,1/e)}const JT=10*1e3,jT=1024,XT=1152,zT=1536;let Jr=null,gc=null;function Jf(i,e,t,r){return{duration:e,size:t,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class Uo{constructor(e,t,r,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=r,this.logger=n,this.ISGenerated=!1,Jr===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jr=o?parseInt(o[1]):0}if(gc===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);gc=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 r=e[0].pts,n=e.reduce((s,o)=>{let a=o.pts,c=a-s;return c<-4294967296&&(t=!0,a=Xt(a,r),c=a-s),c>0?s:a},r);return t&&this.logger.debug("PTS rollover detected"),n}remux(e,t,r,n,s,o,a,c){let l,u,A,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||(A=this.generateIS(e,t,s,o));const j=this.isVideoContiguous;let X=-1,le;if(x&&(X=ZT(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=(Xt(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"),A=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,B||x||c===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"),A=this.generateIS(e,t,s,o)),l=this.remuxVideo(t,p,j,oe)}}else x&&(l=this.remuxVideo(t,p,j,0));l&&(l.firstKeyFrame=X,l.independent=X!==-1,l.firstKeyFramePTS=le)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(d=jf(r,s,this._initPTS,this._initDTS)),n.samples.length&&(h=Xf(n,s,this._initPTS))),{audio:u,video:l,initSegment:A,independent:f,text:h,id3:d}}generateIS(e,t,r,n){const s=e.samples,o=t.samples,a=this.typeSupported,c={},l=this._initPTS;let u=!l||n,A="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?(A="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:A,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(f=e.inputTimeScale,!l||f!==l.timescale?h=d=s[0].pts-Math.round(f*r):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,c.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,!l||f!==l.timescale){const g=this.getVideoStartPts(o),p=Math.round(f*r);d=Math.min(d,Xt(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(c).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:f},this._initDTS={baseTime:d,timescale:f}):h=f=void 0,{tracks:c,initPTS:h,timescale:f}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,o=e.samples,a=[],c=o.length,l=this._initPTS;let u=this.nextAvcDts,A=8,h=this.videoSampleDuration,d,f,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!r||u===null){const w=t*s,k=o[0].pts-Xt(o[0].dts,o[0].pts);Jr&&u!==null&&Math.abs(w-k-u)<15e3?r=!0:u=w-k}const B=l.baseTime*s/l.timescale;for(let w=0;w<c;w++){const k=o[w];k.pts=Xt(k.pts-B,u),k.dts=Xt(k.dts-B,u),k.dts<o[w>0?w-1:w].dts&&(v=!0)}v&&o.sort(function(w,k){const K=w.dts-k.dts,Y=w.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/(c-1)):h||e.inputTimeScale/30;if(r){const w=d-u,k=w>y,K=w<-1;if((k||K)&&(k?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${es(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${es(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||u>=o[0].pts||Jr)){d=u;const Y=o[0].pts-w;if(k)o[0].dts=d,o[0].pts=Y;else{let ie=!0;for(let re=0;re<o.length&&!(o[re].dts>Y&&ie);re++){const he=o[re].pts;if(o[re].dts-=w,o[re].pts-=w,re<o.length-1){const fe=o[re+1].pts,we=o[re].pts,be=fe<=we,Fe=fe<=he;ie=be==Fe}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${es(Y,!0)}/${es(d,!0)}, delta: ${es(w,!0)} ms`)}}d=Math.max(0,d);let x=0,_=0,D=d;for(let w=0;w<c;w++){const k=o[w],K=k.units,Y=K.length;let ie=0;for(let re=0;re<Y;re++)ie+=K[re].data.length;_+=ie,x+=Y,k.length=ie,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[c-1].dts;const F=_+4*x+8;let O;try{O=new Uint8Array(F)}catch(w){this.observer.emit(I.ERROR,I.ERROR,{type:Ie.MUX_ERROR,details:V.REMUX_ALLOC_ERROR,fatal:!1,error:w,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 w=0;w<c;w++){const k=o[w],K=k.units;let Y=0;for(let he=0,fe=K.length;he<fe;he++){const we=K[he],be=we.data,Fe=we.data.byteLength;M.setUint32(A,Fe),A+=4,O.set(be,A),A+=Fe,Y+=4+Fe}let ie;if(w<c-1)h=o[w+1].dts-k.dts,ie=o[w+1].pts-k.pts;else{const he=this.config,fe=w>0?k.dts-o[w-1].dts:y;if(ie=w>0?k.pts-o[w-1].pts:y,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const we=Math.floor(he.maxBufferHole*s),be=(n?g+n*s:this.nextAudioPts)-k.pts;be>we?(h=be-fe,h<0?h=fe:j=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${be/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=fe}else h=fe}const re=Math.round(k.pts-k.dts);X=Math.min(X,h),oe=Math.max(oe,h),le=Math.min(le,ie),L=Math.max(L,ie),a.push(Jf(k.key,h,Y,re))}if(a.length){if(Jr){if(Jr<70){const w=a[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(gc&&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 w=d;for(let k=0,K=a.length;k<K;k++){const Y=w+a[k].duration,ie=w+a[k].cts;if(k<K-1){const re=Y+a[k+1].cts;a[k].duration=re-ie}else a[k].duration=k?a[k-1].duration:y;a[k].cts=0,w=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 XT;case"ac3":return zT;default:return jT}}remuxAudio(e,t,r,n,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,c=o/a,l=this.getSamplesPerFrame(e),u=l*c,A=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=A.baseTime*o/A.timescale;if(this.isAudioContiguous=r=r||g.length&&v>0&&(n&&Math.abs(B-v)<9e3||Math.abs(Xt(g[0].pts-C,B)-v)<20*u),g.forEach(function(U){U.pts=Xt(U.pts-C,B)}),!r||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 w=g[q],k=w.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<JT&&f){let ie=Math.round(K/u);R=k-ie*u,R<0&&(ie--,R+=u),q===0&&(this.nextAudioPts=v=R),this.logger.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(R/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let re=0;re<ie;re++){const he=Math.max(R,0);let fe=KT.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=w.unit.subarray()),g.splice(q,0,{unit:fe,pts:he}),R+=u,q++}}w.pts=R,R+=u}}let y=null,x=null,_,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],w=R.unit;let k=R.pts;if(x!==null){const Y=d[U-1];Y.duration=Math.round((k-x)/c)}else if(r&&e.segmentCodec==="aac"&&(k=v),y=k,D>0){D+=p;try{_=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(_.buffer).setUint32(0,D),_.set(H.types.mdat,4))}else return;_.set(w,p);const K=w.byteLength;p+=K,d.push(Jf(!0,l,K,0)),x=k}const O=d.length;if(!O)return;const M=d[d.length-1];this.nextAudioPts=v=x+c*M.duration;const j=h?new Uint8Array(0):H.moof(e.sequenceNumber++,y/c,We({},e,{samples:d}));e.samples=[];const X=y/o,le=v/o,L={data1:j,data2:_,startPTS:X,endPTS:le,startDTS:X,endDTS:le,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,L}}function Xt(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function ZT(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function jf(i,e,t,r){const n=i.samples.length;if(!n)return;const s=i.inputTimeScale;for(let a=0;a<n;a++){const c=i.samples[a];c.pts=Xt(c.pts-t.baseTime*s/t.timescale,e*s)/s,c.dts=Xt(c.dts-r.baseTime*s/r.timescale,e*s)/s}const o=i.samples;return i.samples=[],{samples:o}}function Xf(i,e,t){const r=i.samples.length;if(!r)return;const n=i.inputTimeScale;for(let o=0;o<r;o++){const a=i.samples[o];a.pts=Xt(a.pts-t.baseTime*n/t.timescale,e*n)/n}i.samples.sort((o,a)=>o.pts-a.pts);const s=i.samples;return i.samples=[],{samples:s}}class e1{constructor(e,t,r,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,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment($C(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=yd(e);n.audio&&(t=zf(n.audio,qe.AUDIO)),n.video&&(r=zf(n.video,qe.VIDEO));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+r,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:r,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,r,n,s,o){var a,c;let{initPTS:l,lastEndTime:u}=this;const A={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};de(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!(h!=null&&h.length))return A;const d={initPTS:void 0,timescale:1};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((c=f)!=null&&c.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),A;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=YC(h,f),p=HC(f,h),v=p===null?s:p;(o||!l)&&(t1(l,v,s,g)||d.timescale!==l.timescale)&&(d.initPTS=v-s,l&&l.timescale===1&&this.logger.warn(`Adjusting initPTS @${s} from ${l.baseTime/l.timescale} to ${d.initPTS}`),this.initPTS=l={baseTime:d.initPTS,timescale:1});const B=e?v-l.baseTime/l.timescale:u,C=B+g;KC(f,h,l.baseTime/l.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 _="";y&&(_+="audio"),x&&(_+="video");const D={data1:h,startPTS:B,startDTS:B,endPTS:C,endDTS:C,type:_,hasAudio:y,hasVideo:x,nb:1,dropped:0};return A.audio=D.type==="audio"?D:void 0,A.video=D.type!=="audio"?D:void 0,A.initSegment=d,A.id3=jf(r,s,l,l),n.samples.length&&(A.text=Xf(n,s,l)),A}}function t1(i,e,t,r){if(i===null)return!0;const n=Math.max(r,1),s=e-i.baseTime/i.timescale;return Math.abs(s-t)>n}function zf(i,e){const t=i==null?void 0:i.codec;return t&&t.length>4?t:e===qe.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?Co(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 Li;try{Li=self.performance.now.bind(self.performance)}catch{Li=Date.now}const Go=[{demux:$T,remux:e1},{demux:ir,remux:Uo},{demux:NT,remux:Uo},{demux:UT,remux:Uo}];Go.splice(2,0,{demux:OT,remux:Uo});class Zf{constructor(e,t,r,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=r,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=Li();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:u,trackSwitch:A,accurateTimeOffset:h,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:B,initSegmentData:C}=c,y=i1(o,t);if(y&&Kr(y.method)){const F=this.getDecrypter(),O=Kl(y.method);if(F.isSync()){let M=F.softwareDecrypt(o,y.key.buffer,y.iv.buffer,O);if(r.part>-1){const X=F.flush();M=X&&X.buffer}if(!M)return s.executeEnd=Li(),pc(r);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,r);return this.decryptionPromise=null,j}),this.decryptionPromise}const x=this.needsProbing(u,A);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=Li(),pc(r)}(u||A||f||x)&&this.resetInitSegment(C,g,p,B,t),(u||f||x)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const _=this.transmux(o,y,d,h,r);this.asyncResult=ts(_);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,s.executeEnd=Li(),_}flush(e){const t=e.transmuxing;t.executeStart=Li();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(r){const A=r.flush();A&&o.push(this.push(A.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=Li();const A=[pc(e)];return this.asyncResult?Promise.resolve(A):A}const u=c.flush(a);return ts(u)?(this.asyncResult=!0,u.then(A=>(this.flushRemux(o,A,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Ee.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(n,s,o,a,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=Li()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,r,n,s):o=this.transmuxUnencrypted(e,r,n,s),o}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,c,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,r,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let s;for(let A=0,h=Go.length;A<h;A++){var o;if((o=Go[A].demux)!=null&&o.probe(e,this.logger)){s=Go[A];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,c=this.remuxer,l=s.remux,u=s.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(r,t,n,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(r,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 Hl(this.config)),e}}function i1(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const pc=i=>({remuxResult:{},chunkMeta:i});function ts(i){return"then"in i&&i.then instanceof Function}class r1{constructor(e,t,r,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=r,this.duration=n,this.defaultInitPts=s||null}}class n1{constructor(e,t,r,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=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}}let eg=0;class tg{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=eg++,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=c=>{const l=c.data,u=this.hls;if(!(!u||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var A;const h=(A=this.workerContext)==null?void 0:A.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{u.logger[l.data.logType]&&u.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,u.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.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:l})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const o=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===I.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new nc,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);const a=wd(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(s.workerPath||aT()){try{s.workerPath?(c.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=cT(s.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=lT());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){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Zf(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new Zf(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=eg++;const t=this.hls.config,r=wd(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,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),AT(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,r,n,s,o,a,c,l,u){var A,h;l.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&&l.level===v.level),y=v?l.sn-v.sn:-1,x=this.part?l.part-this.part.index:-1,_=y===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),D=!C&&(y===1||y===0&&(x===1||_&&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&&((A=s.initSegment)==null?void 0:A.url)===((h=v.initSegment)==null?void 0:h.url)),M=new n1(B,D,c,C,g,O);if(!D||B||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Ee.MAIN?"level":"track"}: ${l.level} id: ${l.id}
2501
2501
  discontinuity: ${B}
2502
2502
  trackSwitch: ${C}
2503
2503
  contiguous: ${D}
@@ -2508,10 +2508,10 @@ ${this.list("video")}
2508
2508
  ${this.list("audio")}
2509
2509
  ${this.list("audiovideo")}}`}list(e){var t,r;return(t=this.queues)!=null&&t[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=(t=this.tracks)==null?void 0:t[e],n=r==null?void 0:r.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(r=>r.label).join(", "))||""}}const ng=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,sg="HlsJsTrackRemovedError";class l1 extends Error{constructor(e){super(e),this.name=sg}}class c1 extends _i{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=r=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:n,mediaSource:s}=this;r&&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:r,_objectUrl:n}=this;r!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${r})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=LC(er(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 r={};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(r,n.tracks):this.sourceBuffers.forEach(s=>{const[o]=s;o&&(r[o]=We({},this.tracks[o]),this.removeBuffer(o)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:r}}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 r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media,n=er(this.appendSource);if(this.transferData=this.overrides=void 0,r&&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=r.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{r.removeAttribute("src");const c=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||c&&o instanceof c,og(r),A1(r,a),r.load()}catch{r.src=a}else r.src=a}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.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 r=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(r,(c,l)=>c==="initSegment"?void 0:l)};
2511
- transfer tracks: ${it(n,(c,l)=>c==="initSegment"?void 0:l)}}`),!dd(n,r)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,u=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(c=>{const l=c,u=n[l];if(u){const A=u.buffer;if(A){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(A);h.detectEvictedFragments(l,p,d,null,!0)}const f=Ic(l),g=[l,A];this.sourceBuffers[f]=g,A.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,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 r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const c=s.sourceBuffers;for(let l=c.length;l--;)a&&c[l].abort(),s.removeSourceBuffer(c[l]);a&&s.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.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),r||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&og(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 r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ic(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new a1(this.tracks)}onBufferCodecs(e,t){const r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!r[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var c,l,u;const A=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=A;let B=r[a];const C=(c=this.transferData)==null||(l=c.tracks)==null?void 0:l[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),_=y==null?void 0:y.levelCodec;B||(B=r[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=Bo(x,_),F=D==null?void 0:D.replace(ng,"$1");let O=Bo(d,f);const M=(u=O)==null?void 0:u.replace(ng,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=Co(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 r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,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=r,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 r=e.start,n=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&Le.isBuffered(c.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:r}=this,{data:n,type:s,parent:o,frag:a,part:c,chunkMeta:l}=t,u=l.buffering[s],A=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=c?c.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=r.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&A!=="initSegment"){const x=c||a,_=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(_){const F=_.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(c||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const _=x.buffer;if(_){const D=C-_.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${A})`),_.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 _={};this.sourceBuffers.forEach(([D,F])=>{D&&(_[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:c,chunkMeta:l,parent:a.type,timeRanges:_})},onError:x=>{var _;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:c,chunkMeta:l,error:x,err:x,fatal:!1},F=(_=this.media)==null?void 0:_.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=qn(!0);else if(x.name===sg&&this.sourceBufferCount===0)D.errorAction=qn(!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,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:s}=t;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],o=n?n.elementaryStreams:r.elementaryStreams;o[qe.AUDIOVIDEO]?s.push("audiovideo"):(o[qe.AUDIO]&&s.push("audio"),o[qe.VIDEO]&&s.push("video"));const a=()=>{const c=self.performance.now();r.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const l=n?n.stats:r.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:r,part:n,stats:l,id:r.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(a,s).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,r;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((r=this.tracks[e])==null?void 0:r.ending))})}onBufferEos(e,t){var r;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=((r=this.overrides)==null?void 0:r.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 r;const n=(r=t.errorAction)==null?void 0:r.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:r}=this;if(!r||t===null||!this.sourceBufferCount)return;const n=e.config,s=r.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const c=Math.max(a,o),l=Math.floor(s/o)*o-c;this.flushBackBuffer(s,o,l)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),l=Math.max(c,o),u=Math.floor(s/o)*o+l;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&r>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const c=o.start(a-1),l=o.end(a-1);if(r>c||e>=c&&e<=l)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&r.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),u=Math.max(l,n);return{duration:1/0,start:l,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(r.duration)?r.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){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&&r!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${it(r)}`),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,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,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:r}=this;if(!r)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 c=this.getTrackCodec(a,o),l=`${a.container};codecs=${c}`;a.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(o)?" Queued":""} ${it(a)}`);try{const u=r.addSourceBuffer(l),A=Ic(o),h=[o,u];t[A]=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:l,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&(t==="video"||t==="audiovideo")&&Nl(r,"video")&&(n=iB(n,r));const s=Bo(n,e.levelCodec);return s?t.slice(0,5)==="audio"?Co(s,this.appendSource):s:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,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 r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r==null?void 0:r.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 r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.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,r){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 c=de(n.duration)?n.duration:1/0,l=de(s.duration)?s.duration:1/0,u=Math.max(0,t),A=Math.min(r,c,l);A>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${A}] from the ${e} SourceBuffer`),a.remove(u,A)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=r==null?void 0:r.buffer;if(!n)throw new l1(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.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:r}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}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,r){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=r.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 r=t.buffer;r&&(t.listeners.forEach(n=>{r.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function og(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function A1(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Ic(i){return i==="audio"?1:0}class vc{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 r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.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 r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.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,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,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 r=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,vc.getMaxLevelByMediaSize(r,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 r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,!t.width&&!t.height&&(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.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(r=>e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height)}static getMaxLevelByMediaSize(e,t,r){if(!(e!=null&&e.length))return-1;const n=(a,c)=>c?a.width!==c.width||a.height!==c.height:!0;let s=e.length-1;const o=Math.max(t,r);for(let a=0;a<e.length;a+=1){const c=e[a];if((c.width>=o||c.height>=o)&&n(c,e[a+1])){s=a;break}}return s}}const Ot={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},u1={HLS:"h"},rs={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},h1={[rs.OBJECT]:["br","d","ot","tb"],[rs.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[rs.SESSION]:["cid","pr","sf","sid","st","v"],[rs.STATUS]:["bs","rtp"]};class jr{constructor(e,t){Array.isArray(e)&&(e=e.map(r=>r instanceof jr?r:new jr(r))),this.value=e,this.params=t}}const d1="Dict";function f1(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function g1(i,e,t,r){return new Error(`failed to ${i} "${f1(e)}" as ${t}`,{cause:r})}function Ii(i,e,t){return g1("serialize",i,e,t)}class ag{constructor(e){this.description=e}}const lg="Bare Item",p1="Boolean";function m1(i){if(typeof i!="boolean")throw Ii(i,p1);return i?"?1":"?0"}const E1="Byte Sequence";function I1(i){if(ArrayBuffer.isView(i)===!1)throw Ii(i,E1);return`:${vT(i)}:`}const v1="Integer";function y1(i){return i<-999999999999999||999999999999999<i}function cg(i){if(y1(i))throw Ii(i,v1);return i.toString()}function C1(i){return`@${cg(i.getTime()/1e3)}`}const B1="Decimal";function T1(i){const e=Mf(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ii(i,B1);const t=e.toString();return t.includes(".")?t:`${t}.0`}const b1="String",S1=/[\x00-\x1f\x7f]+/;function x1(i){if(S1.test(i))throw Ii(i,b1);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Q1(i){return i.description||i.toString().slice(7,-1)}const w1="Token";function Ag(i){const e=Q1(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ii(e,w1);return e}function yc(i){switch(typeof i){case"number":if(!de(i))throw Ii(i,lg);return Number.isInteger(i)?cg(i):T1(i);case"string":return x1(i);case"symbol":return Ag(i);case"boolean":return m1(i);case"object":if(i instanceof Date)return C1(i);if(i instanceof Uint8Array)return I1(i);if(i instanceof ag)return Ag(i);default:throw Ii(i,lg)}}const _1="Key";function Cc(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw Ii(i,_1);return i}function Bc(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Cc(e)}`:`;${Cc(e)}=${yc(t)}`).join("")}function ug(i){return i instanceof jr?`${yc(i.value)}${Bc(i.params)}`:yc(i)}function R1(i){return`(${i.value.map(ug).join(" ")})${Bc(i.params)}`}function D1(i,e={whitespace:!0}){if(typeof i!="object")throw Ii(i,d1);const t=i instanceof Map?i.entries():Object.entries(i),r=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof jr||(s=new jr(s));let o=Cc(n);return s.value===!0?o+=Bc(s.params):(o+="=",Array.isArray(s.value)?o+=R1(s):o+=ug(s)),o}).join(`,${r}`)}function L1(i,e){return D1(i,e)}function k1(i){return i==="ot"||i==="sf"||i==="st"}function M1(i){return typeof i=="number"?de(i):i!=null&&i!==""&&i!==!1}const $o=i=>Math.round(i),F1=(i,e)=>(e!=null&&e.baseUrl&&(i=yT(i,e.baseUrl)),encodeURIComponent(i)),Ho=i=>$o(i/100)*100,P1={br:$o,d:$o,bl:Ho,dl:Ho,mtp:Ho,nor:F1,rtp:Ho,tb:$o};function N1(i,e){const t={};if(i==null||typeof i!="object")return t;const r=Object.keys(i).sort(),n=We({},P1,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return r.forEach(o=>{if(s!=null&&s(o))return;let a=i[o];const c=n[o];c&&(a=c(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||M1(a)&&(k1(o)&&typeof a=="string"&&(a=new ag(a)),t[o]=a))}),t}function hg(i,e={}){return i?L1(N1(i,e),We({whitespace:!1},e)):""}function O1(i,e={}){const t={};if(!i)return t;const r=Object.entries(i),n=Object.entries(h1).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=r.reduce((o,a)=>{var c,l;const[u,A]=a,h=((c=n.find(d=>d[1].includes(u)))===null||c===void 0?void 0:c[0])||rs.REQUEST;return(l=o[h])!==null&&l!==void 0||(o[h]={}),o[h][u]=A,o},{});return Object.entries(s).reduce((o,[a,c])=>(o[a]=hg(c,e),o),t)}function U1(i,e,t){return We(i,O1(e,t))}const G1="CMCD";function $1(i,e={}){if(!i)return"";const t=hg(i,e);return`${G1}=${encodeURIComponent(t)}`}const dg=/CMCD=[^&#]+/;function H1(i,e,t){const r=$1(e,t);if(!r)return i;if(dg.test(i))return i.replace(dg,r);const n=i.includes("?")?"&":"?";return`${i}${n}${r}`}class Y1{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:Ot.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],c=this.getObjectType(s),l={d:(o||s).duration*1e3,ot:c};(c===Ot.VIDEO||c===Ot.AUDIO||c==Ot.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(l.nor=u.url),this.apply(n,l)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.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 r,n;this.audioBuffer=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:u1.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 r=t.ot===Ot.INIT||t.ot===Ot.VIDEO||t.ot===Ot.MUXED;this.starved&&r&&(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={}),U1(e.headers,t,s)):e.url=H1(e.url,t,s)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const n=e.sn-r.startSN;return r.fragments[n+1]}}getNextPart(e){var t,r;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(r=t.details)==null?void 0:r.partList;if(o){const{sn:a}=s;for(let c=o.length-1;c>=0;c--){const l=o[c];if(l.index===n&&l.fragment.sn===a)return o[c+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ot.TIMED_TEXT;if(e.sn==="initSegment")return Ot.INIT;if(t==="audio")return Ot.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ot.VIDEO:Ot.MUXED}getTopBandwidth(e){let t=0,r;const n=this.hls;if(e===Ot.AUDIO)r=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;r=n.levels.slice(0,o)}for(const s of r)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===Ot.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:Le.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(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,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(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 V1=3e5;class K1 extends _i{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(r=>r!==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:r}=t;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((r==null?void 0:r.action)===Dt.SendAlternateToPenaltyBox&&r.flags===si.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:c,type:l}=t.context;a&&n?o=this.getPathwayForGroupId(a,l,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==o),r.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 r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}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 r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(s=>{n-r[s]>V1&&delete r[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in r)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,c=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Cf(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).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 r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":c}=s;if(t.some(u=>u.pathwayId===o))return;const l=this.getLevelsForPathway(a).map(u=>{const A=new st(u.attrs);A["PATHWAY-ID"]=o;const h=A.AUDIO&&`${A.AUDIO}_clone_${o}`,d=A.SUBTITLES&&`${A.SUBTITLES}_clone_${o}`;h&&(r[A.AUDIO]=h,A.AUDIO=h),d&&(n[A.SUBTITLES]=d,A.SUBTITLES=d);const f=gg(u.uri,A["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),g=new Wn({attrs:A,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(...l),fg(this.audioTracks,r,c,o),fg(this.subtitleTracks,n,c,o)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(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||{},c={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,A,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,A,h,d)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${A.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${A.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 ${A.url} rate limited`);return}this.scheduleRefresh(this.uri||A.url,f)},onTimeout:(u,A,h)=>{this.log(`Timeout loading steering manifest (${A.url})`),this.scheduleRefresh(this.uri||A.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const n=(r=this.hls)==null?void 0:r.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function fg(i,e,t,r){i&&Object.keys(e).forEach(n=>{const s=i.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=gg(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=r,a});i.push(...s)})}function gg(i,e,t,r){const{HOST:n,PARAMS:s,[t]:o}=r;let a;e&&(a=o==null?void 0:o[e],a&&(i=a));const c=new self.URL(i);return n&&!a&&(c.host=n),s&&Object.keys(s).sort().forEach(l=>{l&&c.searchParams.set(l,s[l])}),c.href}class Xr extends _i{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=Xr.CDMCleanupPromise?[Xr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:r,initData:n}=t,s=`"${t.type}" event: init data type: "${r}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Lo(this.config));const a=o.map(Xl).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Jl(o);let c,l;if(r==="sinf"){if(a!==Ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${r}" for selected key-system ${a}`);return}const f=Et(new Uint8Array(n));try{const g=Wl(JSON.parse(f).sinf),p=Cd(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24)),l=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: "${r}" for selected key-system ${a}`);return}const f=zC(n),g=f.filter(v=>!!v.systemId&&jl(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=>jl(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(l=jl(p.systemId),p.version===0&&p.data)if(l===Ve.WIDEVINE){const v=p.data.length-22;c=new Uint8Array(p.data.subarray(v,v+16))}else l===Ve.PLAYREADY&&(c=nf(p.data))}if(!l||!c)return;const u=di.hexDump(c),{keyIdToKeySessionPromise:A,mediaKeySessions:h}=this;let d=A[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=di.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=A[v],p.pssh)break;delete A[v],p.pssh=new Uint8Array(n),p.keyId=c,d=A[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,r,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(l!==a){this.log(`Ignoring "${t.type}" event with ${l} init data for selected key-system ${a}`);return}d=A[u]=this.getKeySystemSelectionPromise([l]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new Jn("ISO-23001-7",u,(p=Xl(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=c,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,r,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:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ve.WIDEVINE&&r)return r}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,r=t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(o,a,c)=>!!o&&c.indexOf(o)===a,n=t.map(o=>o.audioCodec).filter(r),s=t.map(o=>o.videoCodec).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const c=l=>{const u=l.shift();this.getMediaKeysPromise(u,n,s).then(A=>o({keySystem:u,mediaKeys:A})).catch(A=>{l.length?c(l):A instanceof zt?a(A):a(new zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:A,fatal:!0},A.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${r}`;return rf===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return r(e,t)}getMediaKeysPromise(e,t,r){const n=HB(e,t,r,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(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const l=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=c.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.then(A=>A?this.setMediaKeysServerCertificate(u,e,A):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:r}){this.log(`Creating key-system session "${t}" keyId: ${di.hexDump(e.keyId||[])}`);const n=r.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,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 di.hexDump(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${di.hexDump(((r=e.decryptdata)==null?void 0:r.keyId)||[])}
2511
+ transfer tracks: ${it(n,(c,l)=>c==="initSegment"?void 0:l)}}`),!dd(n,r)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,u=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(c=>{const l=c,u=n[l];if(u){const A=u.buffer;if(A){const h=this.fragmentTracker,d=u.id;if(h.hasFragments(d)||h.hasParts(d)){const p=Le.getBuffered(A);h.detectEvictedFragments(l,p,d,null,!0)}const f=Ic(l),g=[l,A];this.sourceBuffers[f]=g,A.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,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 r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const c=s.sourceBuffers;for(let l=c.length;l--;)a&&c[l].abort(),s.removeSourceBuffer(c[l]);a&&s.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.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),r||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&og(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 r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ic(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new a1(this.tracks)}onBufferCodecs(e,t){const r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&n.some(a=>!r[a]);if(s||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(a=>{var c,l,u;const A=t[a],{id:h,codec:d,levelCodec:f,container:g,metadata:p,supplemental:v}=A;let B=r[a];const C=(c=this.transferData)==null||(l=c.tracks)==null?void 0:l[a],y=C!=null&&C.buffer?C:B,x=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),_=y==null?void 0:y.levelCodec;B||(B=r[a]={buffer:void 0,listeners:[],codec:d,supplemental:v,container:g,levelCodec:f,metadata:p,id:h});const D=Bo(x,_),F=D==null?void 0:D.replace(ng,"$1");let O=Bo(d,f);const M=(u=O)==null?void 0:u.replace(ng,"$1");O&&D&&F!==M&&(a.slice(0,5)==="audio"&&(O=Co(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 r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,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=r,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 r=e.start,n=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,Ee.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&Le.isBuffered(c.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:r}=this,{data:n,type:s,parent:o,frag:a,part:c,chunkMeta:l}=t,u=l.buffering[s],A=a.sn,h=self.performance.now();u.start=h;const d=a.stats.buffering,f=c?c.stats.buffering:null;d.start===0&&(d.start=h),f&&f.start===0&&(f.start=h);const g=r.audio;let p=!1;s==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const v=this.tracks.video,B=v==null?void 0:v.buffer;if(B&&A!=="initSegment"){const x=c||a,_=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(_){const F=_.frag.start;(D>F||D<this.lastVideoAppendEnd||Le.isBuffered(B,F))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const C=(c||a).start,y={label:`append-${s}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[s];if(x){const _=x.buffer;if(_){const D=C-_.timestampOffset;Math.abs(D)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${C} (delta: ${D}) sn: ${A})`),_.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 _={};this.sourceBuffers.forEach(([D,F])=>{D&&(_[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:c,chunkMeta:l,parent:a.type,timeRanges:_})},onError:x=>{var _;const D={type:Ie.MEDIA_ERROR,parent:a.type,details:V.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:c,chunkMeta:l,error:x,err:x,fatal:!1},F=(_=this.media)==null?void 0:_.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=qn(!0);else if(x.name===sg&&this.sourceBufferCount===0)D.errorAction=qn(!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,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:s}=t;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,s),o)})}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],o=n?n.elementaryStreams:r.elementaryStreams;o[qe.AUDIOVIDEO]?s.push("audiovideo"):(o[qe.AUDIO]&&s.push("audio"),o[qe.VIDEO]&&s.push("video"));const a=()=>{const c=self.performance.now();r.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const l=n?n.stats:r.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:r,part:n,stats:l,id:r.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(a,s).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,r;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((r=this.tracks[e])==null?void 0:r.ending))})}onBufferEos(e,t){var r;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=((r=this.overrides)==null?void 0:r.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 r;const n=(r=t.errorAction)==null?void 0:r.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:r}=this;if(!r||t===null||!this.sourceBufferCount)return;const n=e.config,s=r.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(a)&&a>=0){const c=Math.max(a,o),l=Math.floor(s/o)*o-c;this.flushBackBuffer(s,o,l)}if(de(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),l=Math.max(c,o),u=Math.floor(s/o)*o+l;this.flushFrontBuffer(s,o,u)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=Le.getBuffered(s);if(a.length>0&&r>a.start(0)){var o;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const o=Le.getBuffered(s),a=o.length;if(a<2)return;const c=o.start(a-1),l=o.end(a-1);if(r>c||e>=c&&e<=l)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&r.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),u=Math.max(l,n);return{duration:1/0,start:l,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(r.duration)?r.duration:0;return n>a&&n>o||!de(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){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&&r!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${it(r)}`),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,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,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:r}=this;if(!r)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 c=this.getTrackCodec(a,o),l=`${a.container};codecs=${c}`;a.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(o)?" Queued":""} ${it(a)}`);try{const u=r.addSourceBuffer(l),A=Ic(o),h=[o,u];t[A]=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:l,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&(t==="video"||t==="audiovideo")&&Nl(r,"video")&&(n=iB(n,r));const s=Bo(n,e.levelCodec);return s?t.slice(0,5)==="audio"?Co(s,this.appendSource):s:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,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 r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r==null?void 0:r.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 r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.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,r){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 c=de(n.duration)?n.duration:1/0,l=de(s.duration)?s.duration:1/0,u=Math.max(0,t),A=Math.min(r,c,l);A>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${A}] from the ${e} SourceBuffer`),a.remove(u,A)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=r==null?void 0:r.buffer;if(!n)throw new l1(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.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:r}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}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,r){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const o=r.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 r=t.buffer;r&&(t.listeners.forEach(n=>{r.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function og(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function A1(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Ic(i){return i==="audio"?1:0}class vc{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 r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.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 r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.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,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,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 r=t.filter((n,s)=>this.isLevelAllowed(n)&&s<=e);return this.clientRect=null,vc.getMaxLevelByMediaSize(r,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 r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,!t.width&&!t.height&&(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.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(r=>e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height)}static getMaxLevelByMediaSize(e,t,r){if(!(e!=null&&e.length))return-1;const n=(a,c)=>c?a.width!==c.width||a.height!==c.height:!0;let s=e.length-1;const o=Math.max(t,r);for(let a=0;a<e.length;a+=1){const c=e[a];if((c.width>=o||c.height>=o)&&n(c,e[a+1])){s=a;break}}return s}}const Ot={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},u1={HLS:"h"},rs={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},h1={[rs.OBJECT]:["br","d","ot","tb"],[rs.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[rs.SESSION]:["cid","pr","sf","sid","st","v"],[rs.STATUS]:["bs","rtp"]};class jr{constructor(e,t){Array.isArray(e)&&(e=e.map(r=>r instanceof jr?r:new jr(r))),this.value=e,this.params=t}}const d1="Dict";function f1(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function g1(i,e,t,r){return new Error(`failed to ${i} "${f1(e)}" as ${t}`,{cause:r})}function Ii(i,e,t){return g1("serialize",i,e,t)}class ag{constructor(e){this.description=e}}const lg="Bare Item",p1="Boolean";function m1(i){if(typeof i!="boolean")throw Ii(i,p1);return i?"?1":"?0"}const E1="Byte Sequence";function I1(i){if(ArrayBuffer.isView(i)===!1)throw Ii(i,E1);return`:${vT(i)}:`}const v1="Integer";function y1(i){return i<-999999999999999||999999999999999<i}function cg(i){if(y1(i))throw Ii(i,v1);return i.toString()}function C1(i){return`@${cg(i.getTime()/1e3)}`}const B1="Decimal";function T1(i){const e=Mf(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ii(i,B1);const t=e.toString();return t.includes(".")?t:`${t}.0`}const b1="String",S1=/[\x00-\x1f\x7f]+/;function x1(i){if(S1.test(i))throw Ii(i,b1);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Q1(i){return i.description||i.toString().slice(7,-1)}const w1="Token";function Ag(i){const e=Q1(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ii(e,w1);return e}function yc(i){switch(typeof i){case"number":if(!de(i))throw Ii(i,lg);return Number.isInteger(i)?cg(i):T1(i);case"string":return x1(i);case"symbol":return Ag(i);case"boolean":return m1(i);case"object":if(i instanceof Date)return C1(i);if(i instanceof Uint8Array)return I1(i);if(i instanceof ag)return Ag(i);default:throw Ii(i,lg)}}const _1="Key";function Cc(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw Ii(i,_1);return i}function Bc(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Cc(e)}`:`;${Cc(e)}=${yc(t)}`).join("")}function ug(i){return i instanceof jr?`${yc(i.value)}${Bc(i.params)}`:yc(i)}function R1(i){return`(${i.value.map(ug).join(" ")})${Bc(i.params)}`}function D1(i,e={whitespace:!0}){if(typeof i!="object")throw Ii(i,d1);const t=i instanceof Map?i.entries():Object.entries(i),r=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,s])=>{s instanceof jr||(s=new jr(s));let o=Cc(n);return s.value===!0?o+=Bc(s.params):(o+="=",Array.isArray(s.value)?o+=R1(s):o+=ug(s)),o}).join(`,${r}`)}function L1(i,e){return D1(i,e)}function k1(i){return i==="ot"||i==="sf"||i==="st"}function M1(i){return typeof i=="number"?de(i):i!=null&&i!==""&&i!==!1}const $o=i=>Math.round(i),F1=(i,e)=>(e!=null&&e.baseUrl&&(i=yT(i,e.baseUrl)),encodeURIComponent(i)),Ho=i=>$o(i/100)*100,P1={br:$o,d:$o,bl:Ho,dl:Ho,mtp:Ho,nor:F1,rtp:Ho,tb:$o};function N1(i,e){const t={};if(i==null||typeof i!="object")return t;const r=Object.keys(i).sort(),n=We({},P1,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return r.forEach(o=>{if(s!=null&&s(o))return;let a=i[o];const c=n[o];c&&(a=c(a,e)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||M1(a)&&(k1(o)&&typeof a=="string"&&(a=new ag(a)),t[o]=a))}),t}function hg(i,e={}){return i?L1(N1(i,e),We({whitespace:!1},e)):""}function O1(i,e={}){const t={};if(!i)return t;const r=Object.entries(i),n=Object.entries(h1).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=r.reduce((o,a)=>{var c,l;const[u,A]=a,h=((c=n.find(d=>d[1].includes(u)))===null||c===void 0?void 0:c[0])||rs.REQUEST;return(l=o[h])!==null&&l!==void 0||(o[h]={}),o[h][u]=A,o},{});return Object.entries(s).reduce((o,[a,c])=>(o[a]=hg(c,e),o),t)}function U1(i,e,t){return We(i,O1(e,t))}const G1="CMCD";function $1(i,e={}){if(!i)return"";const t=hg(i,e);return`${G1}=${encodeURIComponent(t)}`}const dg=/CMCD=[^&#]+/;function H1(i,e,t){const r=$1(e,t);if(!r)return i;if(dg.test(i))return i.replace(dg,r);const n=i.includes("?")?"&":"?";return`${i}${n}${r}`}class Y1{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:Ot.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],c=this.getObjectType(s),l={d:(o||s).duration*1e3,ot:c};(c===Ot.VIDEO||c===Ot.AUDIO||c==Ot.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(l.nor=u.url),this.apply(n,l)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.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 r,n;this.audioBuffer=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:u1.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 r=t.ot===Ot.INIT||t.ot===Ot.VIDEO||t.ot===Ot.MUXED;this.starved&&r&&(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={}),U1(e.headers,t,s)):e.url=H1(e.url,t,s)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const n=e.sn-r.startSN;return r.fragments[n+1]}}getNextPart(e){var t,r;const{index:n,fragment:s}=e,o=(t=this.hls.levels[s.level])==null||(r=t.details)==null?void 0:r.partList;if(o){const{sn:a}=s;for(let c=o.length-1;c>=0;c--){const l=o[c];if(l.index===n&&l.fragment.sn===a)return o[c+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ot.TIMED_TEXT;if(e.sn==="initSegment")return Ot.INIT;if(t==="audio")return Ot.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ot.VIDEO:Ot.MUXED}getTopBandwidth(e){let t=0,r;const n=this.hls;if(e===Ot.AUDIO)r=n.audioTracks;else{const s=n.maxAutoLevel,o=s>-1?s+1:n.levels.length;r=n.levels.slice(0,o)}for(const s of r)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===Ot.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:Le.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(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,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(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 V1=3e5;class K1 extends _i{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(r=>r!==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:r}=t;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((r==null?void 0:r.action)===Dt.SendAlternateToPenaltyBox&&r.flags===oi.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:c,type:l}=t.context;a&&n?o=this.getPathwayForGroupId(a,l,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==o),r.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 r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}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 r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(s=>{n-r[s]>V1&&delete r[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in r)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,c=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Cf(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).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 r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":c}=s;if(t.some(u=>u.pathwayId===o))return;const l=this.getLevelsForPathway(a).map(u=>{const A=new st(u.attrs);A["PATHWAY-ID"]=o;const h=A.AUDIO&&`${A.AUDIO}_clone_${o}`,d=A.SUBTITLES&&`${A.SUBTITLES}_clone_${o}`;h&&(r[A.AUDIO]=h,A.AUDIO=h),d&&(n[A.SUBTITLES]=d,A.SUBTITLES=d);const f=gg(u.uri,A["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),g=new Wn({attrs:A,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(...l),fg(this.audioTracks,r,c,o),fg(this.subtitleTracks,n,c,o)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(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||{},c={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,A,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,A,h,d)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${A.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${A.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 ${A.url} rate limited`);return}this.scheduleRefresh(this.uri||A.url,f)},onTimeout:(u,A,h)=>{this.log(`Timeout loading steering manifest (${A.url})`),this.scheduleRefresh(this.uri||A.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const n=(r=this.hls)==null?void 0:r.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function fg(i,e,t,r){i&&Object.keys(e).forEach(n=>{const s=i.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=gg(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=r,a});i.push(...s)})}function gg(i,e,t,r){const{HOST:n,PARAMS:s,[t]:o}=r;let a;e&&(a=o==null?void 0:o[e],a&&(i=a));const c=new self.URL(i);return n&&!a&&(c.host=n),s&&Object.keys(s).sort().forEach(l=>{l&&c.searchParams.set(l,s[l])}),c.href}class Xr extends _i{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=Xr.CDMCleanupPromise?[Xr.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:r,initData:n}=t,s=`"${t.type}" event: init data type: "${r}"`;if(this.debug(s),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Lo(this.config));const a=o.map(Xl).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=Jl(o);let c,l;if(r==="sinf"){if(a!==Ve.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${r}" for selected key-system ${a}`);return}const f=Et(new Uint8Array(n));try{const g=Wl(JSON.parse(f).sinf),p=Cd(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24)),l=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: "${r}" for selected key-system ${a}`);return}const f=zC(n),g=f.filter(v=>!!v.systemId&&jl(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=>jl(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(l=jl(p.systemId),p.version===0&&p.data)if(l===Ve.WIDEVINE){const v=p.data.length-22;c=new Uint8Array(p.data.subarray(v,v+16))}else l===Ve.PLAYREADY&&(c=nf(p.data))}if(!l||!c)return;const u=di.hexDump(c),{keyIdToKeySessionPromise:A,mediaKeySessions:h}=this;let d=A[u];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const v=di.hexDump(p.keyId);if(u===v||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(d=A[v],p.pssh)break;delete A[v],p.pssh=new Uint8Array(n),p.keyId=c,d=A[u]=d.then(()=>this.generateRequestWithPreferredKeySession(g,r,n,"encrypted-event-key-match")),d.catch(B=>this.handleError(B));break}}if(!d){if(l!==a){this.log(`Ignoring "${t.type}" event with ${l} init data for selected key-system ${a}`);return}d=A[u]=this.getKeySystemSelectionPromise([l]).then(({keySystem:f,mediaKeys:g})=>{var p;this.throwIfDestroyed();const v=new Jn("ISO-23001-7",u,(p=Xl(f))!=null?p:"");return v.pssh=new Uint8Array(n),v.keyId=c,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const B=this.createMediaKeySessionContext({decryptdata:v,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(B,r,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:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ve.WIDEVINE&&r)return r}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,r=t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(o,a,c)=>!!o&&c.indexOf(o)===a,n=t.map(o=>o.audioCodec).filter(r),s=t.map(o=>o.videoCodec).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const c=l=>{const u=l.shift();this.getMediaKeysPromise(u,n,s).then(A=>o({keySystem:u,mediaKeys:A})).catch(A=>{l.length?c(l):A instanceof zt?a(A):a(new zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_NO_ACCESS,error:A,fatal:!0},A.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${r}`;return rf===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return r(e,t)}getMediaKeysPromise(e,t,r){const n=HB(e,t,r,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(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const l=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=c.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.then(A=>A?this.setMediaKeysServerCertificate(u,e,A):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:r}){this.log(`Creating key-system session "${t}" keyId: ${di.hexDump(e.keyId||[])}`);const n=r.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,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 di.hexDump(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${di.hexDump(((r=e.decryptdata)==null?void 0:r.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,r)=>{const n=Lo(this.config),s=e.map(Jl).filter(o=>!!o&&n.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:o})=>{const a=Xl(o);a?t(a):r(new Error(`Unable to find format for key-system "${o}"`))}).catch(r)})}loadKey(e){const t=e.keyInfo.decryptdata,r=this.getKeyIdString(t),n=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let s=this.keyIdToKeySessionPromise[r];return s||(s=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(a,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:a,mediaKeys:c,decryptdata:t}))))),(this.keyIdToKeySessionPromise[r]=s.then(a=>{const c="cenc",l=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(a,c,l,"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 zt?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),r=this.keyIdToKeySessionPromise[t];if(!r){const n=Jl(e.keyFormat),s=n?[n]:Lo(this.config);return this.attemptKeySystemAccess(s)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Lo(this.config)),e.length===0)throw new zt({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 r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).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}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>r.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,r,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,r,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,r=f.initData?f.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(f){var c;if(this.warn(f.message),(c=this.hls)!=null&&c.config.debug)throw f}if(r===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${l} (init data type: ${t} length: ${r?r.byteLength:null})`);const u=new nc,A=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,ql("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 ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",A),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 zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new zt({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,r).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${l}`)}).catch(f=>{throw new zt({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,r)=>{if(typeof r=="string"&&typeof t=="object"){const n=r;r=t,t=n}this.log(`key status change "${t}" for keyStatuses keyId: ${di.hexDump("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${di.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,r=t.loader,n=new r(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{const c={responseType:"arraybuffer",url:s},l=t.certLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(h,d,f,g)=>{o(h.data)},onError:(h,d,f,g)=>{a(new zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:Ye({url:c.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,d,f)=>{a(new zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,d,f)=>{a(new Error("aborted"))}};n.load(c,u,A)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise((n,s)=>{e.setServerCertificate(r).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${r==null?void 0:r.byteLength}) on "${t}"`),n(e)}).catch(o=>{s(new zt({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(r=>this.updateKeySession(e,new Uint8Array(r)).catch(n=>{throw new zt({type:Ie.KEY_SYSTEM_ERROR,details:V.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(r,"application/xml"),s=n.querySelectorAll("HttpHeader");if(s.length>0){let u;for(let A=0,h=s.length;A<h;A++){var o,a;u=s[A];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 c=n.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ql(atob(l))}setupLicenseXHR(e,t,r,n){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,r,n)}).catch(o=>{if(!r.decryptdata)throw o;return e.open("POST",t,!0),s.call(this.hls,e,t,r,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=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 c=a.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,a,o,e)}catch(u){this.error(u)}n(c)}else{const c=r.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new zt({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=l-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:c,licenseChallenge:l})=>{e.keySystem==Ve.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,r.removeEventListener("encrypted",this.onMediaEncrypted),r.removeEventListener("waitingforkey",this.onWaitingForKey),r.addEventListener("encrypted",this.onMediaEncrypted),r.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 r=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Jn.clearKeyUriToKeyIdMap();const n=r.length;Xr.CDMCleanupPromise=Promise.all(r.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"),r.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 r=t.reduce((n,s)=>(n.indexOf(s.keyFormat)===-1&&n.push(s.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r}=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),r&&r.readyState!==XMLHttpRequest.DONE&&r.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(VB(s)?new Promise((a,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(a)}):Promise.resolve()).catch(a=>{var c;this.log(`Could not remove session: ${a}`),(c=this.hls)==null||c.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 c;this.log(`Could not close session: ${a}`),(c=this.hls)==null||c.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}`)})})}}}Xr.CDMCleanupPromise=void 0;class zt 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 W1{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 r=this.hls.config;if(r.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),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const s=n-this.lastTime,o=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,c=1e3*o/s,l=this.hls;if(l.trigger(I.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:r}),c>0&&o>l.config.fpsDroppedMonitoringThreshold*a){let u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=u)&&(u=u-1,l.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,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 pg(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function mg(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(r){Oe.debug(`[texttrack-utils]: ${r}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,i.addCue(n)}catch(n){Oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(i.mode=t)}function zr(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let r=i.cues.length;r--;)e&&i.cues[r].removeEventListener("enter",e),i.removeCue(i.cues[r]);t==="disabled"&&(i.mode=t)}function Tc(i,e,t,r){const n=i.mode;if(n==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const s=J1(i.cues,e,t);for(let o=0;o<s.length;o++)(!r||r(s[o]))&&i.removeCue(s[o])}n==="disabled"&&(i.mode=n)}function q1(i,e){if(e<=i[0].startTime)return 0;const t=i.length-1;if(e>i[t].endTime)return-1;let r=0,n=t,s;for(;r<=n;)if(s=Math.floor((n+r)/2),e<i[s].startTime)n=s-1;else if(e>i[s].startTime&&r<t)r=s+1;else return s;return i[r].startTime-e<e-i[n].startTime?r:n}function J1(i,e,t){const r=[],n=q1(i,e);if(n>-1)for(let s=n,o=i.length;s<o;s++){const a=i[s];if(a.startTime>=e&&a.endTime<=t)r.push(a);else if(a.startTime>t)return r}return r}function Yo(i){const e=[];for(let t=0;t<i.length;t++){const r=i[t];(r.kind==="subtitles"||r.kind==="captions")&&r.label&&e.push(i[t])}return e}class j1 extends mc{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 r=Yo(this.media.textTracks);for(let s=0;s<r.length;s++)if(r[s].mode==="hidden")t=r[s];else if(r[s].mode==="showing"){t=r[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 r=this.media;if(!r)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Yo(r.textTracks).forEach(o=>{zr(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:r,groupId:n,details:s}=t,o=this.tracksInGroup[r];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${r} 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 ${r} "${o.name}" lang:${o.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,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 r=t.subtitleGroups||null,n=this.groupIds;let s=this.currentTrack;if(!r||(n==null?void 0:n.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,A)=>{u.id=A});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;const u=pi(a,o);if(u>-1)s=o[u];else{const A=pi(a,this.tracks);s=this.tracks[A]}}let c=this.findTrackId(s);c===-1&&s&&(c=this.findTrackId(null));const l={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const s=t[n];if(!(r&&!s.default||!r&&!e)&&(!e||Br(s,e)))return n}if(e){for(let n=0;n<t.length;n++){const s=t[n];if(is(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const s=t[n];if(is(e.attrs,s.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(Ec(n,e))return r}}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 r=this.currentTrack;if(r&&Br(e,r))return r;const n=pi(e,this.tracksInGroup);if(n>-1){const s=this.tracksInGroup[n];return this.setSubtitleTrack(n),s}else{if(r)return null;{const s=pi(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 r=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 ${r} "${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:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Yo(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(s=>Ec(r,s))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.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 r=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===r&&s)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:a="",name:c,type:l,url:u}=n;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:c,type:l,url:u});const A=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(A)}}function ns(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}const Zr=.025;let Vo=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function X1(i,e,t){return`${i.identifier}-${t+1}-${ns(e)}`}class z1{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 bc(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,r=bc(t,e);return t-r<.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 bc(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)<Zr))}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"?Vo.Range:Vo.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 Z1(this)}}function bc(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Zr)?e.start:e.start+e.duration}function Eg(i,e,t){const r=new self.URL(i,t);return r.protocol!=="data:"&&r.searchParams.set("_HLS_primary_id",e),r}function Z1(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function Sc(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class eb{constructor(e,t,r,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 l=this.interstitial.playoutLimit,u=this.currentTime;this.startOffset+u>=l&&this.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=r,this.assetItem=n;let o=n.uri;try{o=Eg(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,(c,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&l.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 r=this.timelineOffset,n=Le.bufferInfo(e,r,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 r=e-t;if(Math.abs(r)>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,r=this.duration;return Math.min(Math.max(0,e-t),r)}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,r){this.hls.on(e,t)}once(e,t,r){this.hls.once(e,t)}off(e,t,r){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${Sc(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const Ig=.033;class tb extends _i{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((r,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,r+1):r,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 r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[r]||(t===void 0&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&(s=n[r])!=null&&s.event;){var s;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let s=r[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 r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const s=r[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 r;if(((r=t[n].event)==null?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let s=0;s<n;s++){const o=r[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 r=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(r){const n=r.assetList,s=n[n.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,s=this.events,o=this.parseDateRanges(n,{url:r.url},t),a=Object.keys(n),c=s?s.filter(l=>!a.includes(l.identifier)):[];o.length&&o.sort((l,u)=>{const A=l.cue.pre,h=l.cue.post,d=u.cue.pre,f=u.cue.post;if(A&&!d)return-1;if(d&&!A||h&&!f)return 1;if(f&&!h)return-1;if(!A&&!d&&!h&&!f){const g=l.startTime,p=u.startTime;if(g!==p)return g-p}return l.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[]){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,s=this.parseSchedule(r,e);(t.length||(n==null?void 0:n.length)!==s.length||s.some((a,c)=>Math.abs(a.playout.start-n[c].playout.start)>.005||Math.abs(a.playout.end-n[c].playout.end)>.005))&&(this.items=s,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,r){const n=[],s=Object.keys(e);for(let o=0;o<s.length;o++){const a=s[o],c=e[a];if(c.isInterstitial){let l=this.eventMap[a];l?l.setDateRange(c):(l=new z1(c,t),this.eventMap[a]=l,r===!1&&(l.appendInPlace=r)),n.push(l)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,s=n.live?1/0:n.edge;let o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((u,A)=>{const h=u.cue.pre,d=u.cue.post,f=e[A-1]||null,g=u.appendInPlace,p=d?s:u.startOffset,v=u.duration,B=u.timelineOccupancy===Vo.Range?v:0,C=u.resumptionOffset,y=(f==null?void 0:f.startTime)===p,x=p+u.cumulativeDuration;let _=g?x+v:p+C;if(h||!d&&p<=0){const F=l;l+=B,u.timelineStart=x;const O=o;o+=v,r.push({event:u,start:x,end:_,playout:{start:O,end:o},integrated:{start:F,end:l}})}else if(p<=s){if(!y){const M=p-c;if(M>Ig){const j=c,X=l;l+=M;const le=o;o+=M;const oe={previousEvent:e[A-1]||null,nextEvent:u,start:j,end:j+M,playout:{start:le,end:o},integrated:{start:X,end:l}};r.push(oe)}else M>0&&f&&(f.cumulativeDuration+=M,r[r.length-1].end=p)}d&&(_=x),u.timelineStart=x;const F=l;l+=B;const O=o;o+=v,r.push({event:u,start:x,end:_,playout:{start:O,end:o},integrated:{start:F,end:l}})}else return;const D=u.resumeTime;d||D>s?c=s:c=D}),c<s){var a;const u=c,A=l,h=s-c;l+=h;const d=o;o+=h,r.push({previousEvent:((a=r[r.length-1])==null?void 0:a.event)||null,nextEvent:null,start:c,end:u+h,playout:{start:d,end:o},integrated:{start:A,end:l}})}this.setDurations(s,o,l)}else r.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 r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,n=r.live?1/0:r.edge;let s=0,o=-1;e.forEach((a,c)=>{const l=a.cue.pre,u=a.cue.post,A=l?0:u?n:a.startTime;this.updateAssetDurations(a),o===A?a.cumulativeDuration=s:(s=0,o=A),!u&&a.snapOptions.in&&(a.resumeAnchor=br(null,r.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Ig&&(e[c+1].appendInPlace=!1,e[c+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 r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>Zr?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1):t?!Object.keys(t).some(o=>{const a=t[o].details,c=a.edge;if(r>=c)return this.log(`"${e.identifier}" resumption ${r} past ${o} playlist end ${c}`),!1;const l=br(null,a.fragments,r);if(!l)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const u=o==="audio"?.175:0;return Math.abs(l.start-r)<Zr+u||Math.abs(l.end-r)<Zr+u?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${o} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)}):(this.log(`"${e.identifier}" resumption ${r} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,s=!1;e.assetList.forEach((o,a)=>{const c=t+r;o.startOffset=r,o.timelineStart=c,n||(n=o.duration===null),s||(s=!!o.error);const l=o.error?0:o.duration||0;r+=l}),n&&!s?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function nr(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class ib{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=Eg(r,this.hls.sessionId,e.baseUrl)}catch(h){const d=this.assignAssetListError(e,V.ASSET_LIST_LOAD_ERROR,h,r);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),c={responseType:"json",url:n.href},l=s.interstitialAssetListLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={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(c,u,A),this.hls.trigger(I.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,r,n,s,o){return e.error=r,{type:Ie.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:o,stats:s}}}function ki(i,e,t){vi(i,e,t),i.addEventListener(e,t)}function vi(i,e,t){i.removeEventListener(e,t)}function vg(i){i==null||i.play().catch(()=>{})}class rb extends _i{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 r=this.currentTime;if(r===void 0||this.playbackDisabled)return;const n=r-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=r,this.bufferedPos=r;const a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(r,r-n)&&this.updateSchedule(),this.checkBuffer(),o&&r<a.start||r>=a.end){var c;const h=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(a)&&(c=this.media)!=null&&c.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 l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(a)){const h=a.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,h))}return}const u=l.timelineStart,A=l.duration||0;(o&&r<u||r>=u+A)&&this.setScheduleToAssetAtTime(r,l)},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(r>=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);r>=o&&this.setScheduleToAssetAtTime(r,s)},this.onScheduleUpdate=(r,n)=>{const s=this.schedule,o=this.playingItem,a=s.events||[],c=s.items||[],l=s.durations,u=r.map(d=>d.identifier),A=!!(a.length||u.length);if(A&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
2513
- Schedule: ${c.map(d=>nr(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)>Zr&&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(r.forEach(d=>{d.assetList.forEach(f=>{this.clearAssetPlayer(f.identifier,null)})}),A||n){if(this.hls.trigger(I.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:c.slice(0),durations:l,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 ib(e),this.schedule=new tb(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){vi(e,"play",this.onPlay),vi(e,"pause",this.onPause),vi(e,"seeking",this.onSeeking),vi(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;ki(r,"seeking",this.onSeeking),ki(r,"timeupdate",this.onTimeupdate),ki(r,"play",this.onPlay),ki(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(r);this.setSchedulePosition(s)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(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,r=A=>A&&e.getAssetPlayer(A.identifier),n=(A,h,d,f,g)=>{if(A){let p=A[h].start;const v=A.event;if(v){if(h==="playout"||v.timelineOccupancy!==Vo.Point){const B=r(d);(B==null?void 0:B.interstitial)===v&&(p+=B.assetItem.startOffset+B[g])}}else{const B=f==="bufferedPos"?o():e[f];p+=B-A.start}return p}return 0},s=(A,h)=>{if(A!==0&&h!=="primary"&&e.schedule.length){var d;const f=e.schedule.findItemIndexAtTime(A),g=(d=e.schedule.items)==null?void 0:d[f];if(g){const p=g[h].start-g.start;return A+p}}return A},o=()=>{const A=e.bufferedPos;return A===Number.MAX_VALUE?a("primary"):Math.max(A,0)},a=A=>{var h;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:e.schedule.durations[A]},c=(A,h)=>{var d,f;const g=e.effectivePlayingItem;if(g!=null&&(d=g.event)!=null&&d.restrictions.skip)return;e.log(`seek to ${A} "${h}"`);const p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(A,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,_=p&&e.itemsMatch(p,B);if(p&&(x||_)){const F=r(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=A-M,X=(x?M:O.currentTime)+j;if(X>=0&&(!F||x||X<=F.duration)){O.currentTime=X;return}}}if(B){let F=A;if(h!=="primary"){const M=B[h].start,j=A-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=A-(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)}}},l=()=>{const A=e.effectivePlayingItem;if(e.isInterstitial(A))return A;const h=t();return e.isInterstitial(h)?h:null},u={get currentTime(){const A=l(),h=e.effectivePlayingItem;return h&&h===A?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(A){const h=l(),d=e.effectivePlayingItem;d&&d===h&&c(A+d.playout.start,"playout")},get duration(){const A=l();return A?A.playout.end-A.playout.start:0},get assetPlayers(){var A;const h=(A=l())==null?void 0:A.event.assetList;return h?h.map(d=>e.getAssetPlayer(d.identifier)):[]},get playingIndex(){var A;const h=(A=l())==null?void 0:A.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var A,h;return((A=e.schedule)==null||(h=A.events)==null?void 0:h.slice(0))||[]},get schedule(){var A,h;return((A=e.schedule)==null||(h=A.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return l()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const A=t();return e.findItemIndex(A)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const A=e.effectivePlayingItem;return e.findItemIndex(A)},primary:{get bufferedEnd(){return o()},get currentTime(){const A=e.timelinePos;return A>0?A:0},set currentTime(A){c(A,"primary")},get duration(){return a("primary")},get seekableStart(){var A;return((A=e.primaryDetails)==null?void 0:A.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(A){c(A,"integrated")},get duration(){return a("integrated")},get seekableStart(){var A;return s(((A=e.primaryDetails)==null?void 0:A.fragmentStart)||0,"integrated")}},skip:()=>{const A=e.effectivePlayingItem,h=A==null?void 0:A.event;if(h&&!h.restrictions.skip){const d=e.findItemIndex(A);if(h.appendInPlace){const f=A.playout.start+A.event.duration;c(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,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,r;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=(r=s)==null?void 0:r.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 r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&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 r,n;if(e.media===t)return;let s=null;const o=this.hls,a=e!==o,c=a&&e.interstitial.appendInPlace,l=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(o.media)c&&(s=o.transferMedia(),this.detachedData=s),u="Primary";else if(l){const d=this.getBufferingPlayer();d?(s=d.transferMedia(),u=`${d}`):u="detached MediaSource"}else u="detached media";if(!s){if(l)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!==c){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 A=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",h=A&&s?s:t;if(this.log(`${A?"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 r=this.timelinePos,n=this.effectivePlayingItem;if(r===-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,r){const n=r+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 c=e.resumeTime;this.timelinePos<c&&(this.timelinePos=c,this.checkBuffer()),this.setSchedulePosition(o)}}}setScheduleToAssetAtTime(e,t){const r=this.schedule,n=t.parentIdentifier,s=r.getEvent(n);if(s){const o=r.findEventIndex(n),a=r.findAssetIndex(s,e);this.setSchedulePosition(o,a)}}setSchedulePosition(e,t){const r=this.schedule.items;if(!r||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const n=e>=0?r[e]:null,s=this.playingItem,o=this.playingLastItem;if(this.isInterstitial(s)){var a;const l=s.event,u=this.playingAsset,A=u==null?void 0:u.identifier,h=A?this.getAssetPlayer(A):null;if(h&&A&&(!this.eventItemsMatch(s,n)||t!==void 0&&A!==((a=l.assetList)==null?void 0:a[t].identifier))){var c;const d=l.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${d+1}/${l.assetList.length} ${Sc(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:d,event:l,schedule:r.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(A,n),h.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&h.detachMedia()}if(!this.eventItemsMatch(s,n)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${nr(s)}`),l.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:l,schedule:r.slice(0),scheduleIndex:e}),l.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,r,t,s,o)}advanceSchedule(e,t,r,n,s){const o=e>=0?t[e]:null,a=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(l=>{const u=l.interstitial,A=this.schedule.findEventIndex(u.identifier);(A<e||A>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const l=o.event;r===void 0&&(r=this.schedule.findAssetIndex(l,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(o,a)||this.setBufferingItem(o);let A=this.preloadAssets(l,r);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${nr(o)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:l,schedule:t.slice(0),scheduleIndex:e})),!l.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${l}`);return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!a){this.log(`Waiting for attachMedia to start Interstitial ${l}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const h=l.assetList[r];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(l,e,r||0);return}if(A||(A=this.getAssetPlayer(h.identifier)),A===null||A.destroyed){const d=l.assetList.length;this.warn(`asset ${r+1}/${d} player destroyed ${l}`),A=this.createAssetPlayer(l,h,r)}if(!this.eventItemsMatch(o,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(A,r,t,e,a),this.shouldPlay&&vg(A.media)}else o!==null?(this.resumePrimary(o,e,n),this.shouldPlay&&vg(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,r){var n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${nr(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(!r)return;const s=this.schedule.items;s&&(this.log(`resumed ${nr(e)}`),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(r<n.fragmentStart||r>n.edge))return this.hls.liveSyncPosition||-1}return r}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,r){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),r&&this.startLoadingPrimaryAt(e,r)),r||(this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((r=n.mainForwardBufferInfo)==null?void 0:r.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 r=this.hls.levels[t.level],n=Ye(Ye({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{audio:r});return}const s=Ye(Ye({},n),{},{audio:r});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{subtitles:r});return}const s=Ye(Ye({},n),{},{subtitles:r});this.mediaSelection=s}onAudioTrackSwitching(e,t){const r=Od(t);this.playerQueue.forEach(n=>n.hls.setAudioOption(t)||n.hls.setAudioOption(r))}onSubtitleTrackSwitch(e,t){const r=Od(t);this.playerQueue.forEach(n=>n.hls.setSubtitleOption(t)||t.id!==-1&&n.hls.setSubtitleOption(r))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){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 r;const o=this.schedule.findEventIndex(s.identifier),a=(r=this.schedule.items)==null?void 0:r[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 r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){const r=this.schedule.items;if(e&&r){const n=this.findItemIndex(e,t);return r[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 r;return!!t&&(e===t||e.event.identifier===((r=t.event)==null?void 0:r.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 r=Le.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,t,e)}updateBufferedPos(e,t,r){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 c=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u;const A=this.findItemIndex(s),h=Math.min(A+1,t.length-1),d=t[h];if((c===-1&&s&&e>=s.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=h),h-a>1&&(s==null||(u=s.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=e,c>A&&c>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 r&&o&&!this.itemsMatch(o,s)&&(c===a?this.bufferedToItem(o):c===a+1&&this.bufferedToItem(t[c]))}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,r=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:n,events:s}=r;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 c=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${nr(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),o?e.event.assetList.forEach(l=>{const u=this.getAssetPlayer(l.identifier);u&&u.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.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 r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(r!==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),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=r.assetList.length===0&&!r.assetListLoader,s=r.cue.once;if(n||!s){const o=this.preloadAssets(r,t);if(o!=null&&o.interstitial.appendInPlace){const a=r.assetList[t],c=this.primaryMedia;a&&c&&this.bufferAssetPlayer(o,c)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,o=e.cue.once;if(s){const c=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(c+.25)}let l,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-c;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${l?` live-start: ${u} start-offset: ${l}`:""}`),r)return this.createAsset(e,0,0,c,e.duration,r);const A=this.assetListLoader.loadAssetList(e,l);A&&(e.assetListLoader=A)}else if(!o&&n){for(let c=t;c<n;c++){const l=e.assetList[c],u=this.getAssetPlayerQueueIndex(l.identifier);(u===-1||this.playerQueue[u].destroyed)&&!l.error&&this.createAssetPlayer(e,l,c)}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 r=0;r<t.length;r++)if(e===t[r].assetId)return r;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 r=0;r<e.length;r++)if(e[r].media===t)return e[r]}return null}createAsset(e,t,r,n,s,o){const a={parentIdentifier:e.identifier,identifier:X1(e,o,t),duration:s,startOffset:r,timelineStart:n,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,r){this.log(`create HLSAssetPlayer for ${Sc(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 c=n.audioTracks[n.audioTrack],l=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 A=t.identifier,h=Ye(Ye({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:A,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:c||s.audioPreference,subtitlePreference:l||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:ns(t.uri)})),this.getAssetPlayer(A)&&this.warn(`Duplicate date range identifier ${e} and asset ${A}`);const f=new eb(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[r]=t;const g=C=>{if(C.live){const _=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),r,_.message);return}const y=C.edge-C.fragmentStart,x=t.duration;(x===null||y>x)&&(this.log(`Interstitial asset "${A}" 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(A);if(x&&y.tracks){x.off(I.BUFFER_CODECS,p),x.tracks=y.tracks;const _=this.primaryMedia;this.bufferingAsset===x.assetItem&&_&&!x.media&&this.bufferAssetPlayer(x,_)}};f.on(I.BUFFER_CODECS,p);const v=()=>{var C;const y=this.getAssetPlayer(A);if(this.log(`buffered to end of asset ${y}`),!y)return;const x=this.schedule.findEventIndex(e.identifier),_=e.findAssetIndex(t),D=_+1,F=(C=this.schedule.items)==null?void 0:C[x];if(this.isInterstitial(F))if(_!==-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(A))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,C)};return f.once(I.MEDIA_ENDED,B(r)),f.once(I.PLAYOUT_LIMIT_REACHED,B(1/0)),f.on(I.ERROR,(C,y)=>{const x=this.getAssetPlayer(A);if(y.details===V.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const _=x.currentTime,D=x.duration-_;_&&e.appendInPlace&&D/x.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${A} ${e} at ${x.media.currentTime}`),v()):(this.warn(`Stalled at ${_} of ${_+D} in asset ${A} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(y,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${y.error} ${e}`)}),f.on(I.DESTROYING,()=>{if(!this.getAssetPlayer(A))return;const y=new Error(`Asset player destroyed unexpectedly ${A}`),x={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:y};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),r,y.message)}),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&nr(t)}`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,s){const{interstitial:o,assetItem:a,assetId:c}=e,l=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var r,n;const{interstitial:s,assetItem:o,assetId:a}=e,c=this.schedule.findEventIndex(s.identifier),l=(r=this.schedule.items)==null?void 0:r[c];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=o;const u=this.getBufferingPlayer();if(u===e)return;const A=s.appendInPlace;if(A&&(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(A&&o!==this.playingAsset){if(!e.tracks)return;if(h&&!dd(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,c,g,d.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,r,n,s){if(e.details===V.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;let a=null;if(o){const A=this.getAssetPlayerQueueIndex(o.identifier);a=this.playerQueue[A]||null}const c=this.schedule.items,l=We({},e,{fatal:!1,errorAction:qn(!0),asset:o,assetListIndex:n,event:t,schedule:c,scheduleIndex:r,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const u=new Error(s);o&&(this.playingAsset!==o&&this.clearAssetPlayer(o.identifier,null),o.error=u),t.assetList.some(A=>!A.error)?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;if(this.updateSchedule(),r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${r?nr(r):"<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(r,n);if(this.itemsMatch(r,s))this.clearInterstitial(e,null);else{const o=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else this.checkStart()}onAssetListLoaded(e,t){var r;const n=t.event,s=n.identifier,o=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(s))return;const a=n.timelineStart,c=n.duration;let l=0;o.forEach((f,g)=>{const p=parseFloat(f.DURATION);this.createAsset(n,g,l,a+l,p,f.URI),l+=p}),n.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${c}) ${n}`);const u=this.waitingItem,A=(u==null?void 0:u.event.identifier)===s;this.updateSchedule();const h=(r=this.bufferingItem)==null?void 0:r.event;if(A){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 r=t.interstitial;r&&this.primaryFallback(r);break}case V.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const yg=500;class nb extends ic{constructor(e,t,r){super(e,t,r,"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(yg),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:r,success:n}=t;if(Ct(r)&&(this.fragPrevious=r),this.state=Z.IDLE,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let o;const a=r.start;for(let l=0;l<s.length;l++)if(a>=s[l].start&&a<=s[l].end){o=s[l];break}const c=r.start+r.duration;o?o.end=c:(o={start:a,end:c},s.push(o)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(r===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(r,s,Ee.SUBTITLE)}}onError(e,t){const r=t.frag;(r==null?void 0:r.type)===Ee.SUBTITLE&&(t.details===V.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Z.STOPPED&&(this.state=Z.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&rg(this.levels,t)){this.levels=t.map(r=>new Wn(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const n=new Wn(r);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 r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.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(yg)}onSubtitleTrackLoaded(e,t){var r;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 c=s[a];if(a>=s.length||!c)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 l=0;if(o.live||(r=c.details)!=null&&r.live){const A=this.mainDetails;if(o.deltaUpdateFailed||!A)return;const h=A.fragments[0];if(!c.details)o.hasProgramDateTime&&A.hasProgramDateTime?(Mo(o,A),l=o.fragmentStart):h&&(l=h.start,tc(o,l));else{var u;l=this.alignPlaylists(o,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),l===0&&h&&(l=h.start,tc(o,l))}}c.details=o,this.levelLastLoaded=c,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&&(br(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&Kr(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,Kl(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 c=performance.now();s.trigger(I.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:c}})}).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,r=t==null?void 0:t[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:n}=this,s=this.getLoadPosition(),o=Le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:c}=o,l=r.details,u=this.hls.maxBufferLength+l.levelTargetDuration;if(c>u)return;const A=l.fragments,h=A.length,d=l.edge;let f=null;const g=this.fragPrevious;if(a<d){const B=n.maxFragLookUpTolerance,C=a>d-B?0:B;f=br(g,A,Math.max(A[0].start,a),C),!f&&g&&g.start<A[0].start&&(f=A[0])}else f=A[h-1];if(f=this.filterReplacedPrimary(f,r.details),!f)return;const p=f.sn-l.startSN,v=A[p-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===It.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===It.NOT_LOADED){const B=this.mapToInitFragWhenRequired(f);B&&this.loadFragment(B,r,a)}}}loadFragment(e,t,r){Ct(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new sb(this.tracksBuffered[this.currentTrackId]||[])}}class sb{constructor(e){this.buffered=void 0;const t=(r,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}}const ob={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},Cg=i=>String.fromCharCode(ob[i]||i),oi=15,Mi=100,ab={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},cb={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ab={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ub=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class hb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;Oe.log(`${this.time} [${e}] ${r}`)}}}const Sr=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class Bg{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 r=0;r<t.length;r++){const n=t[r];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 db{constructor(){this.uchar=" ",this.penState=new Bg}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 fb{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Bg,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Mi;t++)this.chars.push(new db);this.logger=e}equals(e){for(let t=0;t<Mi;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Mi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Mi;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>Mi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Mi)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].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=Cg(e);if(this.pos>=Mi){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<Mi;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 r=0;r<Mi;r++){const n=this.chars[r].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 xc{constructor(e){this.rows=[],this.currRow=oi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<oi;t++)this.rows.push(new fb(e));this.logger=e}reset(){for(let e=0;e<oi;e++)this.rows[e].clear();this.currRow=oi-1}equals(e){let t=!0;for(let r=0;r<oi;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<oi;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<oi;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<oi;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[s].cueStartTime,c=this.logger.time;if(a!==null&&c!==null&&a<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(o.rows[s+l])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,o=Math.max(s-1,0);r.setCursor(e.indent),e.color=r.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 r="",n=-1;for(let s=0;s<oi;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?r="["+t.join(" | ")+"]":r=t.join(`
2514
- `)),r}getTextAndFormat(){return this.rows}}class Tg{constructor(e,t,r){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 xc(r),this.nonDisplayedMemory=new xc(r),this.lastOutputScreen=new xc(r),this.currRollUpRow=this.displayedMemory.rows[oi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[oi-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 r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);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 r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}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 bg{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=pb(),this.logger=void 0;const n=this.logger=new hb;this.channels=[null,new Tg(e,t,n),new Tg(e+1,r,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 r=0;r<t.length;r+=2){const n=t[r]&127,s=t[r+1]&127;let o=!1,a=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+Sr([t[r],t[r+1]])+"] -> ("+Sr([n,s])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(gb(n,s,c)){Ko(null,null,c),this.logger.log(3,()=>"Repeated command ("+Sr([n,s])+") is dropped");continue}Ko(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 Ko(null,null,c);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 "+Sr([n,s])+" orig: "+Sr([t[r],t[r+1]]))}}parseCmd(e,t){const r=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(r||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 r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Sr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;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?r=o===1?ab[e]:cb[e]:r=o===1?lb[e]:Ab[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(r,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,n.underline=(r&1)===1,r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((r-16)/2)*4,n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=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 '"+Cg(o)+"' in channel "+r),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Sr(n).join(",")),n}parseBackgroundAttributes(e,t){const r=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(r||n))return!1;let s;const o={};e===16||e===24?(s=Math.floor((t-32)/2),o.background=ub[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()}Ko(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function Ko(i,e,t){t.a=i,t.b=e}function gb(i,e,t){return t.a===i&&t.b===e}function pb(){return{a:null,b:null}}var Qc=function(){if(Ro!=null&&Ro.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,c){if(typeof c!="string"||!Array.isArray(a))return!1;const l=c.toLowerCase();return~a.indexOf(l)?l:!1}function r(a){return t(i,a)}function n(a){return t(e,a)}function s(a,...c){let l=1;for(;l<arguments.length;l++){const u=arguments[l];for(const A in u)a[A]=u[A]}return a}function o(a,c,l){const u=this,A={enumerable:!0};u.hasBeenReset=!1;let h="",d=!1,f=a,g=c,p=l,v=null,B="",C=!0,y="auto",x="start",_=50,D="middle",F=50,O="middle";Object.defineProperty(u,"id",s({},A,{get:function(){return h},set:function(M){h=""+M}})),Object.defineProperty(u,"pauseOnExit",s({},A,{get:function(){return d},set:function(M){d=!!M}})),Object.defineProperty(u,"startTime",s({},A,{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({},A,{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({},A,{get:function(){return p},set:function(M){p=""+M,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},A,{get:function(){return v},set:function(M){v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},A,{get:function(){return B},set:function(M){const j=r(M);if(j===!1)throw new SyntaxError("An invalid or illegal string was specified.");B=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},A,{get:function(){return C},set:function(M){C=!!M,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},A,{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({},A,{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({},A,{get:function(){return _},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");_=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},A,{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({},A,{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({},A,{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 mb{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Sg(i){function e(r,n,s,o){return(r|0)*3600+(n|0)*60+(s|0)+parseFloat(o||0)}const t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Eb{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[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 r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function xg(i,e,t,r){const n=r?i.split(r):[i];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],c=o[1];e(a,c)}}const wc=new Qc(0,0,""),Wo=wc.align==="middle"?"middle":"center";function Ib(i,e,t){const r=i;function n(){const a=Sg(i);if(a===null)throw new Error("Malformed timestamp: "+r);return i=i.replace(/^[^\sa-zA-Z-]+/,""),a}function s(a,c){const l=new Eb;xg(a,function(h,d){let f;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===d){l.set(h,t[g].region);break}break;case"vertical":l.alt(h,d,["rl","lr"]);break;case"line":f=d.split(","),l.integer(h,f[0]),l.percent(h,f[0])&&l.set("snapToLines",!1),l.alt(h,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",Wo,"end"]);break;case"position":f=d.split(","),l.percent(h,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",Wo,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,d);break;case"align":l.alt(h,d,["start",Wo,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&wc.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",Wo);let A=l.get("position","auto");A==="auto"&&wc.position===50&&(A=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=A}function o(){i=i.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);i=i.slice(3),o(),e.endTime=n(),o(),s(i,e)}function Qg(i){return i.replace(/<br(?: \/)?>/gi,`
2513
+ Schedule: ${c.map(d=>nr(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)>Zr&&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(r.forEach(d=>{d.assetList.forEach(f=>{this.clearAssetPlayer(f.identifier,null)})}),A||n){if(this.hls.trigger(I.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:c.slice(0),durations:l,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 ib(e),this.schedule=new tb(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){vi(e,"play",this.onPlay),vi(e,"pause",this.onPause),vi(e,"seeking",this.onSeeking),vi(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;ki(r,"seeking",this.onSeeking),ki(r,"timeupdate",this.onTimeupdate),ki(r,"play",this.onPlay),ki(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(r);this.setSchedulePosition(s)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(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,r=A=>A&&e.getAssetPlayer(A.identifier),n=(A,h,d,f,g)=>{if(A){let p=A[h].start;const v=A.event;if(v){if(h==="playout"||v.timelineOccupancy!==Vo.Point){const B=r(d);(B==null?void 0:B.interstitial)===v&&(p+=B.assetItem.startOffset+B[g])}}else{const B=f==="bufferedPos"?o():e[f];p+=B-A.start}return p}return 0},s=(A,h)=>{if(A!==0&&h!=="primary"&&e.schedule.length){var d;const f=e.schedule.findItemIndexAtTime(A),g=(d=e.schedule.items)==null?void 0:d[f];if(g){const p=g[h].start-g.start;return A+p}}return A},o=()=>{const A=e.bufferedPos;return A===Number.MAX_VALUE?a("primary"):Math.max(A,0)},a=A=>{var h;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:e.schedule.durations[A]},c=(A,h)=>{var d,f;const g=e.effectivePlayingItem;if(g!=null&&(d=g.event)!=null&&d.restrictions.skip)return;e.log(`seek to ${A} "${h}"`);const p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(A,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,_=p&&e.itemsMatch(p,B);if(p&&(x||_)){const F=r(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=A-M,X=(x?M:O.currentTime)+j;if(X>=0&&(!F||x||X<=F.duration)){O.currentTime=X;return}}}if(B){let F=A;if(h!=="primary"){const M=B[h].start,j=A-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=A-(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)}}},l=()=>{const A=e.effectivePlayingItem;if(e.isInterstitial(A))return A;const h=t();return e.isInterstitial(h)?h:null},u={get currentTime(){const A=l(),h=e.effectivePlayingItem;return h&&h===A?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(A){const h=l(),d=e.effectivePlayingItem;d&&d===h&&c(A+d.playout.start,"playout")},get duration(){const A=l();return A?A.playout.end-A.playout.start:0},get assetPlayers(){var A;const h=(A=l())==null?void 0:A.event.assetList;return h?h.map(d=>e.getAssetPlayer(d.identifier)):[]},get playingIndex(){var A;const h=(A=l())==null?void 0:A.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var A,h;return((A=e.schedule)==null||(h=A.events)==null?void 0:h.slice(0))||[]},get schedule(){var A,h;return((A=e.schedule)==null||(h=A.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return l()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const A=t();return e.findItemIndex(A)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const A=e.effectivePlayingItem;return e.findItemIndex(A)},primary:{get bufferedEnd(){return o()},get currentTime(){const A=e.timelinePos;return A>0?A:0},set currentTime(A){c(A,"primary")},get duration(){return a("primary")},get seekableStart(){var A;return((A=e.primaryDetails)==null?void 0:A.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(A){c(A,"integrated")},get duration(){return a("integrated")},get seekableStart(){var A;return s(((A=e.primaryDetails)==null?void 0:A.fragmentStart)||0,"integrated")}},skip:()=>{const A=e.effectivePlayingItem,h=A==null?void 0:A.event;if(h&&!h.restrictions.skip){const d=e.findItemIndex(A);if(h.appendInPlace){const f=A.playout.start+A.event.duration;c(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,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,r;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=(r=s)==null?void 0:r.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 r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&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 r,n;if(e.media===t)return;let s=null;const o=this.hls,a=e!==o,c=a&&e.interstitial.appendInPlace,l=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(o.media)c&&(s=o.transferMedia(),this.detachedData=s),u="Primary";else if(l){const d=this.getBufferingPlayer();d?(s=d.transferMedia(),u=`${d}`):u="detached MediaSource"}else u="detached media";if(!s){if(l)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!==c){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 A=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",h=A&&s?s:t;if(this.log(`${A?"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 r=this.timelinePos,n=this.effectivePlayingItem;if(r===-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,r){const n=r+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 c=e.resumeTime;this.timelinePos<c&&(this.timelinePos=c,this.checkBuffer()),this.setSchedulePosition(o)}}}setScheduleToAssetAtTime(e,t){const r=this.schedule,n=t.parentIdentifier,s=r.getEvent(n);if(s){const o=r.findEventIndex(n),a=r.findAssetIndex(s,e);this.setSchedulePosition(o,a)}}setSchedulePosition(e,t){const r=this.schedule.items;if(!r||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const n=e>=0?r[e]:null,s=this.playingItem,o=this.playingLastItem;if(this.isInterstitial(s)){var a;const l=s.event,u=this.playingAsset,A=u==null?void 0:u.identifier,h=A?this.getAssetPlayer(A):null;if(h&&A&&(!this.eventItemsMatch(s,n)||t!==void 0&&A!==((a=l.assetList)==null?void 0:a[t].identifier))){var c;const d=l.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${d+1}/${l.assetList.length} ${Sc(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:d,event:l,schedule:r.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(A,n),h.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&h.detachMedia()}if(!this.eventItemsMatch(s,n)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${nr(s)}`),l.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:l,schedule:r.slice(0),scheduleIndex:e}),l.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,r,t,s,o)}advanceSchedule(e,t,r,n,s){const o=e>=0?t[e]:null,a=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(l=>{const u=l.interstitial,A=this.schedule.findEventIndex(u.identifier);(A<e||A>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const l=o.event;r===void 0&&(r=this.schedule.findAssetIndex(l,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(o,a)||this.setBufferingItem(o);let A=this.preloadAssets(l,r);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${nr(o)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:l,schedule:t.slice(0),scheduleIndex:e})),!l.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${l}`);return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!a){this.log(`Waiting for attachMedia to start Interstitial ${l}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const h=l.assetList[r];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(l,e,r||0);return}if(A||(A=this.getAssetPlayer(h.identifier)),A===null||A.destroyed){const d=l.assetList.length;this.warn(`asset ${r+1}/${d} player destroyed ${l}`),A=this.createAssetPlayer(l,h,r)}if(!this.eventItemsMatch(o,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(A,r,t,e,a),this.shouldPlay&&vg(A.media)}else o!==null?(this.resumePrimary(o,e,n),this.shouldPlay&&vg(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,r){var n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${nr(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(!r)return;const s=this.schedule.items;s&&(this.log(`resumed ${nr(e)}`),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(r<n.fragmentStart||r>n.edge))return this.hls.liveSyncPosition||-1}return r}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,r){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),r&&this.startLoadingPrimaryAt(e,r)),r||(this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((r=n.mainForwardBufferInfo)==null?void 0:r.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 r=this.hls.levels[t.level],n=Ye(Ye({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{audio:r});return}const s=Ye(Ye({},n),{},{audio:r});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ye(Ye({},this.altSelection),{},{subtitles:r});return}const s=Ye(Ye({},n),{},{subtitles:r});this.mediaSelection=s}onAudioTrackSwitching(e,t){const r=Od(t);this.playerQueue.forEach(n=>n.hls.setAudioOption(t)||n.hls.setAudioOption(r))}onSubtitleTrackSwitch(e,t){const r=Od(t);this.playerQueue.forEach(n=>n.hls.setSubtitleOption(t)||t.id!==-1&&n.hls.setSubtitleOption(r))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){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 r;const o=this.schedule.findEventIndex(s.identifier),a=(r=this.schedule.items)==null?void 0:r[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 r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){const r=this.schedule.items;if(e&&r){const n=this.findItemIndex(e,t);return r[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 r;return!!t&&(e===t||e.event.identifier===((r=t.event)==null?void 0:r.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 r=Le.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,t,e)}updateBufferedPos(e,t,r){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 c=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u;const A=this.findItemIndex(s),h=Math.min(A+1,t.length-1),d=t[h];if((c===-1&&s&&e>=s.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=h),h-a>1&&(s==null||(u=s.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=e,c>A&&c>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 r&&o&&!this.itemsMatch(o,s)&&(c===a?this.bufferedToItem(o):c===a+1&&this.bufferedToItem(t[c]))}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,r=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:n,events:s}=r;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 c=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${nr(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),o?e.event.assetList.forEach(l=>{const u=this.getAssetPlayer(l.identifier);u&&u.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.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 r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(r!==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),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=r.assetList.length===0&&!r.assetListLoader,s=r.cue.once;if(n||!s){const o=this.preloadAssets(r,t);if(o!=null&&o.interstitial.appendInPlace){const a=r.assetList[t],c=this.primaryMedia;a&&c&&this.bufferAssetPlayer(o,c)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,o=e.cue.once;if(s){const c=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(c+.25)}let l,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-c;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${l?` live-start: ${u} start-offset: ${l}`:""}`),r)return this.createAsset(e,0,0,c,e.duration,r);const A=this.assetListLoader.loadAssetList(e,l);A&&(e.assetListLoader=A)}else if(!o&&n){for(let c=t;c<n;c++){const l=e.assetList[c],u=this.getAssetPlayerQueueIndex(l.identifier);(u===-1||this.playerQueue[u].destroyed)&&!l.error&&this.createAssetPlayer(e,l,c)}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 r=0;r<t.length;r++)if(e===t[r].assetId)return r;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 r=0;r<e.length;r++)if(e[r].media===t)return e[r]}return null}createAsset(e,t,r,n,s,o){const a={parentIdentifier:e.identifier,identifier:X1(e,o,t),duration:s,startOffset:r,timelineStart:n,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,r){this.log(`create HLSAssetPlayer for ${Sc(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 c=n.audioTracks[n.audioTrack],l=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 A=t.identifier,h=Ye(Ye({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:A,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:c||s.audioPreference,subtitlePreference:l||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:ns(t.uri)})),this.getAssetPlayer(A)&&this.warn(`Duplicate date range identifier ${e} and asset ${A}`);const f=new eb(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[r]=t;const g=C=>{if(C.live){const _=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),r,_.message);return}const y=C.edge-C.fragmentStart,x=t.duration;(x===null||y>x)&&(this.log(`Interstitial asset "${A}" 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(A);if(x&&y.tracks){x.off(I.BUFFER_CODECS,p),x.tracks=y.tracks;const _=this.primaryMedia;this.bufferingAsset===x.assetItem&&_&&!x.media&&this.bufferAssetPlayer(x,_)}};f.on(I.BUFFER_CODECS,p);const v=()=>{var C;const y=this.getAssetPlayer(A);if(this.log(`buffered to end of asset ${y}`),!y)return;const x=this.schedule.findEventIndex(e.identifier),_=e.findAssetIndex(t),D=_+1,F=(C=this.schedule.items)==null?void 0:C[x];if(this.isInterstitial(F))if(_!==-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(A))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,C)};return f.once(I.MEDIA_ENDED,B(r)),f.once(I.PLAYOUT_LIMIT_REACHED,B(1/0)),f.on(I.ERROR,(C,y)=>{const x=this.getAssetPlayer(A);if(y.details===V.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const _=x.currentTime,D=x.duration-_;_&&e.appendInPlace&&D/x.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${A} ${e} at ${x.media.currentTime}`),v()):(this.warn(`Stalled at ${_} of ${_+D} in asset ${A} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(y,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${y.error} ${e}`)}),f.on(I.DESTROYING,()=>{if(!this.getAssetPlayer(A))return;const y=new Error(`Asset player destroyed unexpectedly ${A}`),x={fatal:!0,type:Ie.OTHER_ERROR,details:V.INTERSTITIAL_ASSET_ITEM_ERROR,error:y};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),r,y.message)}),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&nr(t)}`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,s){const{interstitial:o,assetItem:a,assetId:c}=e,l=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var r,n;const{interstitial:s,assetItem:o,assetId:a}=e,c=this.schedule.findEventIndex(s.identifier),l=(r=this.schedule.items)==null?void 0:r[c];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=o;const u=this.getBufferingPlayer();if(u===e)return;const A=s.appendInPlace;if(A&&(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(A&&o!==this.playingAsset){if(!e.tracks)return;if(h&&!dd(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,c,g,d.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,r,n,s){if(e.details===V.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;let a=null;if(o){const A=this.getAssetPlayerQueueIndex(o.identifier);a=this.playerQueue[A]||null}const c=this.schedule.items,l=We({},e,{fatal:!1,errorAction:qn(!0),asset:o,assetListIndex:n,event:t,schedule:c,scheduleIndex:r,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const u=new Error(s);o&&(this.playingAsset!==o&&this.clearAssetPlayer(o.identifier,null),o.error=u),t.assetList.some(A=>!A.error)?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;if(this.updateSchedule(),r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${r?nr(r):"<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(r,n);if(this.itemsMatch(r,s))this.clearInterstitial(e,null);else{const o=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else this.checkStart()}onAssetListLoaded(e,t){var r;const n=t.event,s=n.identifier,o=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(s))return;const a=n.timelineStart,c=n.duration;let l=0;o.forEach((f,g)=>{const p=parseFloat(f.DURATION);this.createAsset(n,g,l,a+l,p,f.URI),l+=p}),n.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${c}) ${n}`);const u=this.waitingItem,A=(u==null?void 0:u.event.identifier)===s;this.updateSchedule();const h=(r=this.bufferingItem)==null?void 0:r.event;if(A){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 r=t.interstitial;r&&this.primaryFallback(r);break}case V.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const yg=500;class nb extends ic{constructor(e,t,r){super(e,t,r,"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(yg),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:r,success:n}=t;if(Ct(r)&&(this.fragPrevious=r),this.state=Z.IDLE,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let o;const a=r.start;for(let l=0;l<s.length;l++)if(a>=s[l].start&&a<=s[l].end){o=s[l];break}const c=r.start+r.duration;o?o.end=c:(o={start:a,end:c},s.push(o)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(r===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(r,s,Ee.SUBTITLE)}}onError(e,t){const r=t.frag;(r==null?void 0:r.type)===Ee.SUBTITLE&&(t.details===V.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Z.STOPPED&&(this.state=Z.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&rg(this.levels,t)){this.levels=t.map(r=>new Wn(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const n=new Wn(r);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 r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.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(yg)}onSubtitleTrackLoaded(e,t){var r;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 c=s[a];if(a>=s.length||!c)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 l=0;if(o.live||(r=c.details)!=null&&r.live){const A=this.mainDetails;if(o.deltaUpdateFailed||!A)return;const h=A.fragments[0];if(!c.details)o.hasProgramDateTime&&A.hasProgramDateTime?(Mo(o,A),l=o.fragmentStart):h&&(l=h.start,tc(o,l));else{var u;l=this.alignPlaylists(o,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),l===0&&h&&(l=h.start,tc(o,l))}}c.details=o,this.levelLastLoaded=c,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&&(br(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&Kr(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,Kl(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 c=performance.now();s.trigger(I.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:c}})}).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,r=t==null?void 0:t[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:n}=this,s=this.getLoadPosition(),o=Le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:c}=o,l=r.details,u=this.hls.maxBufferLength+l.levelTargetDuration;if(c>u)return;const A=l.fragments,h=A.length,d=l.edge;let f=null;const g=this.fragPrevious;if(a<d){const B=n.maxFragLookUpTolerance,C=a>d-B?0:B;f=br(g,A,Math.max(A[0].start,a),C),!f&&g&&g.start<A[0].start&&(f=A[0])}else f=A[h-1];if(f=this.filterReplacedPrimary(f,r.details),!f)return;const p=f.sn-l.startSN,v=A[p-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===It.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===It.NOT_LOADED){const B=this.mapToInitFragWhenRequired(f);B&&this.loadFragment(B,r,a)}}}loadFragment(e,t,r){Ct(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new sb(this.tracksBuffered[this.currentTrackId]||[])}}class sb{constructor(e){this.buffered=void 0;const t=(r,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}}const ob={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},Cg=i=>String.fromCharCode(ob[i]||i),ai=15,Mi=100,ab={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},cb={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ab={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ub=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class hb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;Oe.log(`${this.time} [${e}] ${r}`)}}}const Sr=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class Bg{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 r=0;r<t.length;r++){const n=t[r];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 db{constructor(){this.uchar=" ",this.penState=new Bg}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 fb{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Bg,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Mi;t++)this.chars.push(new db);this.logger=e}equals(e){for(let t=0;t<Mi;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Mi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Mi;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>Mi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Mi)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].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=Cg(e);if(this.pos>=Mi){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<Mi;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 r=0;r<Mi;r++){const n=this.chars[r].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 xc{constructor(e){this.rows=[],this.currRow=ai-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ai;t++)this.rows.push(new fb(e));this.logger=e}reset(){for(let e=0;e<ai;e++)this.rows[e].clear();this.currRow=ai-1}equals(e){let t=!0;for(let r=0;r<ai;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<ai;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ai;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<ai;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[s].cueStartTime,c=this.logger.time;if(a!==null&&c!==null&&a<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(o.rows[s+l])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,o=Math.max(s-1,0);r.setCursor(e.indent),e.color=r.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 r="",n=-1;for(let s=0;s<ai;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?r="["+t.join(" | ")+"]":r=t.join(`
2514
+ `)),r}getTextAndFormat(){return this.rows}}class Tg{constructor(e,t,r){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 xc(r),this.nonDisplayedMemory=new xc(r),this.lastOutputScreen=new xc(r),this.currRollUpRow=this.displayedMemory.rows[ai-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[ai-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 r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);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 r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}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 bg{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=pb(),this.logger=void 0;const n=this.logger=new hb;this.channels=[null,new Tg(e,t,n),new Tg(e+1,r,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 r=0;r<t.length;r+=2){const n=t[r]&127,s=t[r+1]&127;let o=!1,a=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+Sr([t[r],t[r+1]])+"] -> ("+Sr([n,s])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(gb(n,s,c)){Ko(null,null,c),this.logger.log(3,()=>"Repeated command ("+Sr([n,s])+") is dropped");continue}Ko(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 Ko(null,null,c);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 "+Sr([n,s])+" orig: "+Sr([t[r],t[r+1]]))}}parseCmd(e,t){const r=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(r||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 r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Sr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;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?r=o===1?ab[e]:cb[e]:r=o===1?lb[e]:Ab[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(r,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,n.underline=(r&1)===1,r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((r-16)/2)*4,n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=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 '"+Cg(o)+"' in channel "+r),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Sr(n).join(",")),n}parseBackgroundAttributes(e,t){const r=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(r||n))return!1;let s;const o={};e===16||e===24?(s=Math.floor((t-32)/2),o.background=ub[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()}Ko(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function Ko(i,e,t){t.a=i,t.b=e}function gb(i,e,t){return t.a===i&&t.b===e}function pb(){return{a:null,b:null}}var Qc=function(){if(Ro!=null&&Ro.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,c){if(typeof c!="string"||!Array.isArray(a))return!1;const l=c.toLowerCase();return~a.indexOf(l)?l:!1}function r(a){return t(i,a)}function n(a){return t(e,a)}function s(a,...c){let l=1;for(;l<arguments.length;l++){const u=arguments[l];for(const A in u)a[A]=u[A]}return a}function o(a,c,l){const u=this,A={enumerable:!0};u.hasBeenReset=!1;let h="",d=!1,f=a,g=c,p=l,v=null,B="",C=!0,y="auto",x="start",_=50,D="middle",F=50,O="middle";Object.defineProperty(u,"id",s({},A,{get:function(){return h},set:function(M){h=""+M}})),Object.defineProperty(u,"pauseOnExit",s({},A,{get:function(){return d},set:function(M){d=!!M}})),Object.defineProperty(u,"startTime",s({},A,{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({},A,{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({},A,{get:function(){return p},set:function(M){p=""+M,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},A,{get:function(){return v},set:function(M){v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},A,{get:function(){return B},set:function(M){const j=r(M);if(j===!1)throw new SyntaxError("An invalid or illegal string was specified.");B=j,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},A,{get:function(){return C},set:function(M){C=!!M,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},A,{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({},A,{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({},A,{get:function(){return _},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");_=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},A,{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({},A,{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({},A,{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 mb{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Sg(i){function e(r,n,s,o){return(r|0)*3600+(n|0)*60+(s|0)+parseFloat(o||0)}const t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Eb{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[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 r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function xg(i,e,t,r){const n=r?i.split(r):[i];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],c=o[1];e(a,c)}}const wc=new Qc(0,0,""),Wo=wc.align==="middle"?"middle":"center";function Ib(i,e,t){const r=i;function n(){const a=Sg(i);if(a===null)throw new Error("Malformed timestamp: "+r);return i=i.replace(/^[^\sa-zA-Z-]+/,""),a}function s(a,c){const l=new Eb;xg(a,function(h,d){let f;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===d){l.set(h,t[g].region);break}break;case"vertical":l.alt(h,d,["rl","lr"]);break;case"line":f=d.split(","),l.integer(h,f[0]),l.percent(h,f[0])&&l.set("snapToLines",!1),l.alt(h,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",Wo,"end"]);break;case"position":f=d.split(","),l.percent(h,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",Wo,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,d);break;case"align":l.alt(h,d,["start",Wo,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&wc.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",Wo);let A=l.get("position","auto");A==="auto"&&wc.position===50&&(A=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=A}function o(){i=i.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);i=i.slice(3),o(),e.endTime=n(),o(),s(i,e)}function Qg(i){return i.replace(/<br(?: \/)?>/gi,`
2515
2515
  `)}class vb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new mb,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function r(){let s=t.buffer,o=0;for(s=Qg(s);o<s.length&&s[o]!=="\r"&&s[o]!==`
2516
2516
  `;)++o;const a=s.slice(0,o);return s[o]==="\r"&&++o,s[o]===`
2517
2517
  `&&++o,t.buffer=s.slice(o),a}function n(s){xg(s,function(o,a){},/:/)}try{let s="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;s=r();const a=s.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:s=r(),t.state){case"HEADER":/:/.test(s)?n(s):s||(t.state="ID");continue;case"NOTE":s||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){t.state="NOTE";break}if(!s)continue;if(t.cue=new Qc(0,0,""),t.state="CUE",s.indexOf("-->")===-1){t.cue.id=s;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ib(s,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=s.indexOf("-->")!==-1;if(!s||a&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
@@ -2521,11 +2521,11 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2521
2521
  `).split(`
2522
2522
  `),l=[],u=e?qT(e.baseTime,e.timescale):0;let A="00:00.000",h=0,d=0,f,g=!0;a.oncue=function(p){const v=t[r];let B=t.ccOffset;const C=(h-u)/9e4;if(v!=null&&v.new&&(d!==void 0?B=t.ccOffset=v.start:Bb(t,r,C)),C){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}B=C-t.presentationOffset}const y=p.endTime-p.startTime,x=Xt((p.startTime+B-d)*9e4,n*9e4)/9e4;p.startTime=Math.max(x,0),p.endTime=Math.max(x+y,0);const _=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(_)),p.id||(p.id=Rc(p.startTime,p.endTime,_)),p.endTime>0&&l.push(p)},a.onparsingerror=function(p){f=p},a.onflush=function(){if(f){o(f);return}s(l)},c.forEach(p=>{if(g)if(_c(p,"X-TIMESTAMP-MAP=")){g=!1,p.slice(16).split(",").forEach(v=>{_c(v,"LOCAL:")?A=v.slice(6):_c(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{d=Cb(A)/1e3}catch(v){f=v}return}else p===""&&(g=!1);a.parse(p+`
2523
2523
  `)}),a.flush()}const Dc="stpp.ttml.im1t",wg=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,_g=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bb={left:"start",center:"center",right:"end",start:"start",end:"end"};function Rg(i,e,t,r){const n=_e(new Uint8Array(i),["mdat"]);if(n.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const s=n.map(a=>Ht(a)),o=WT(e.baseTime,1,e.timescale);try{s.forEach(a=>t(Sb(a,o)))}catch(a){r(a)}}function Sb(i,e){const n=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(s).reduce((A,h)=>(A[h]=n.getAttribute(`ttp:${h}`)||s[h],A),{}),a=n.getAttribute("xml:space")!=="preserve",c=Dg(Lc(n,"styling","style")),l=Dg(Lc(n,"layout","region")),u=Lc(n,"body","[begin]");return[].map.call(u,A=>{const h=Lg(A,a);if(!h||!A.hasAttribute("begin"))return null;const d=Mc(A.getAttribute("begin"),o),f=Mc(A.getAttribute("dur"),o);let g=Mc(A.getAttribute("end"),o);if(d===null)throw kg(A);if(g===null){if(f===null)throw kg(A);g=d+f}const p=new Qc(d-e,g-e,h);p.id=Rc(p.startTime,p.endTime,p.text);const v=l[A.getAttribute("region")],B=c[A.getAttribute("style")],C=xb(v,B,c),{textAlign:y}=C;if(y){const x=bb[y];x&&(p.lineAlign=x),p.align=y}return We(p,C),p}).filter(A=>A!==null)}function Lc(i,e,t){const r=i.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(t)):[]}function Dg(i){return i.reduce((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function Lg(i,e){return[].slice.call(i.childNodes).reduce((t,r,n)=>{var s;return r.nodeName==="br"&&n?t+`
2524
- `:(s=r.childNodes)!=null&&s.length?Lg(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}function xb(i,e,t){const r="http://www.w3.org/ns/ttml#styling";let n=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),s.reduce((a,c)=>{const l=kc(e,r,c)||kc(i,r,c)||kc(n,r,c);return l&&(a[c]=l),a},{})}function kc(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function kg(i){return new Error(`Could not parse ttml timestamp ${i}`)}function Mc(i,e){if(!i)return null;let t=Sg(i);return t===null&&(wg.test(i)?t=Qb(i,e):_g.test(i)&&(t=wb(i,e))),t}function Qb(i,e){const t=wg.exec(i),r=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+r/e.frameRate}function wb(i,e){const t=_g.exec(i),r=Number(t[1]);switch(t[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}class qo{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class _b{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pg(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(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_LOADED,this.onManifestLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){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_LOADED,this.onManifestLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new qo(this,"textTrack1"),t=new qo(this,"textTrack2"),r=new qo(this,"textTrack3"),n=new qo(this,"textTrack4");this.cea608Parser1=new bg(1,e,t),this.cea608Parser2=new bg(3,r,n)}addCues(e,t,r,n,s){let o=!1;for(let a=s.length;a--;){const c=s[a],l=Rb(c[0],c[1],t,r);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],r),o=!0,l/(r-t)>.5))return}if(o||s.push([t,r]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,r,n)}else{const a=this.Cues.newCue(null,t,r,n);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){const{unparsedVttFrags:o}=this;r===Ee.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:s}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(I.FRAG_LOADED,a)}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const s=r.textTracks[n];if(Fg(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:o}=t[e],a=this.getExistingTrack(s,o);if(a)r[e]=a,zr(r[e]),pg(r[e],n);else{const c=this.createTextTrack("captions",s,o);c&&(c[e]=!0,r[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r=t.label,n={_id:e,label:r,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(s=>{zr(n[s]),delete n[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pg(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let r=0;r<t.length;r++)zr(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(s=>s.textCodec===Dc);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(rg(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const o=this.media,a=o?Yo(o.textTracks):null;if(this.tracks.forEach((c,l)=>{let u;if(a){let A=null;for(let h=0;h<a.length;h++)if(a[h]&&Fg(a[h],c)){A=a[h],a[h]=null;break}A&&(u=A)}if(u)zr(u);else{const A=Mg(c);u=this.createTextTrack(A,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),a!=null&&a.length){const c=a.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const n=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!n)return;const s=`textTrack${n[1]}`,o=this.captionsProperties[s];o&&(o.label=r.name,r.lang&&(o.languageCode=r.lang),o.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Ee.MAIN){var r,n;const{cea608Parser1:s,cea608Parser2:o,lastSn:a}=this,{cc:c,sn:l}=t.frag,u=(r=(n=t.part)==null?void 0:n.index)!=null?r:-1;s&&o&&(l!==a+1||l===a&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(s.reset(),o.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===Ee.SUBTITLE)if(n.byteLength){const s=r.decryptdata,o="stats"in t;if(s==null||!s.encrypted||o){const a=this.tracks[r.level],c=this.vttCCs;c[r.cc]||(c[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),a&&a.textCodec===Dc?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Rg(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{r.logger.log(`Failed to parse IMSC1: ${n}`),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:o}=this,a=s.length-1;if(!s[r.cc]&&a===-1){o.push(e);return}const c=this.hls,l=(t=r.initSegment)!=null&&t.data?jt(r.initSegment.data,new Uint8Array(n)).buffer:n;Tb(l,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const A=u.message==="Missing initPTS for VTT MPEGTS";A?o.push(e):this._fallbackToIMSC1(r,n),c.logger.log(`Failed to parse VTT cue: ${u}`),!(A&&a>r.cc)&&c.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Rg(t,this.initPTS[e.cc],()=>{r.textCodec=Dc,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(s=>mg(n,s))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(I.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===Ee.SUBTITLE&&this.onFragLoaded(I.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(!(r.type===Ee.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let s=0;s<n.length;s++){const o=n[s].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(o);this.cea608Parser1.addData(n[s].pts,a[0]),this.cea608Parser2.addData(n[s].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:o}=this;if(!(!o||o.currentTime<r)){if(!s||s==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(c=>Tc(a[c],t,r))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(c=>Tc(a[c],t,n))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let n=2;for(let s=0;s<r;s++){const o=e[n++],a=127&e[n++],c=127&e[n++];if(a===0&&c===0)continue;if((4&o)!==0){const u=3&o;(u===0||u===1)&&(t[u].push(a),t[u].push(c))}}return t}}function Mg(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Fg(i,e){return!!i&&i.kind===Mg(e)&&Ec(e,i)}function Rb(i,e,t,r){return Math.min(e,r)-Math.max(i,t)}function Pg(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Db=/\s/,Lb={newCue(i,e,t,r){const n=[];let s,o,a,c,l;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(s=r.rows[h],a=!0,c=0,l="",!s.isEmpty()){var A;for(let g=0;g<s.chars.length;g++)Db.test(s.chars[g].uchar)&&a?c++:(l+=s.chars[g].uchar,a=!1);s.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const d=Qg(l.trim()),f=Rc(e,t,d);i!=null&&(A=i.cues)!=null&&A.getCueById(f)||(o=new u(e,t,d),o.id=f,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return i&&n.length&&(n.sort((h,d)=>h.line==="auto"||d.line==="auto"?0:h.line>8&&d.line>8?d.line-h.line:h.line-d.line),n.forEach(h=>mg(i,h))),n}};function kb(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Mb=/(\d+)-(\d+)\/(\d+)/;class Ng{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Ob,this.controller=new self.AbortController,this.stats=new Ll}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const s=Fb(e,this.controller.signal),o=e.responseType==="arraybuffer",a=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=c&&de(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(ts(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(A=>{var h;this.response=this.loader=A;const d=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},l-(d-n.loading.start)),!A.ok){const{status:g,statusText:p}=A;throw new Ub(p||"fetch, bad network response",g,A)}n.loading.first=d,n.total=Nb(A.headers)||n.total;const f=(h=this.callbacks)==null?void 0:h.onProgress;return f&&de(t.highWaterMark)?this.loadProgressively(A,n,e,t.highWaterMark,f):o?A.arrayBuffer():e.responseType==="json"?A.json():A.text()}).then(A=>{var h,d;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const g=A[a];g&&(n.loaded=n.total=g);const p={url:f.url,data:A,code:f.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!de(t.highWaterMark)&&v(n,e,A,f),(d=this.callbacks)==null||d.onSuccess(p,n,e,f)}).catch(A=>{var h;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const d=A&&A.code||0,f=A?A.message:null;(h=this.callbacks)==null||h.onError({code:d,text:f},e,A?A.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,s){const o=new xf,a=e.body.getReader(),c=()=>a.read().then(l=>{if(l.done)return o.dataLength&&s(t,r,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=l.value,A=u.length;return t.loaded+=A,A<n||o.dataLength?(o.push(u),o.dataLength>=n&&s(t,r,o.flush().buffer,e)):s(t,r,u.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Fb(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(We({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function Pb(i){const e=Mb.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Nb(i){const e=i.get("Content-Range");if(e){const r=Pb(e);if(de(r))return r}const t=i.get("Content-Length");if(t)return parseInt(t)}function Ob(i,e){return new self.Request(i.url,e)}class Ub extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const Gb=/^age:\s*[\d.]+\s*$/im;class Og{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ll,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return s(r,t.url)}).catch(o=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),s(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(o=>{var a;(a=this.callbacks)==null||a.onError({code:r.status,text:o.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:o}=r.loadPolicy;if(n)for(const a in n)e.setRequestHeader(a,n[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&de(s)?s:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,s=this.config;if(!r.aborted&&n>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,u=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=u??t.response;if(f!=null){var o,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=t.responseType==="arraybuffer"?f.byteLength:f.length;r.loaded=r.total=g,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const p=(o=this.callbacks)==null?void 0:o.onProgress;p&&p(r,e,f,t);const v={url:t.responseURL,data:f,code:l};(a=this.callbacks)==null||a.onSuccess(v,r,e,t);return}}const A=s.loadPolicy.errorRetry,h=r.retry,d={url:e.url,data:void 0,code:l};if(Qo(A,h,!1,d))this.retry(A);else{var c;Oe.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Qo(e,t,!0))this.retry(e);else{var r;Oe.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=$l(e,r.retry),r.retry++,Oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Gb.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const $b={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Hb=Ye(Ye({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Og,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mB,bufferController:c1,capLevelController:vc,errorController:BB,fpsController:W1,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:rf,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:$b},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Yb()),{},{subtitleStreamController:nb,subtitleTrackController:j1,timelineController:_b,audioStreamController:s1,audioTrackController:o1,emeController:Xr,cmcdController:Y1,contentSteeringController:K1,interstitialsController:rb});function Yb(){return{cueHandler:Lb,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Vb(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Fc(i),n=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const a=`${o==="level"?"playlist":o}LoadPolicy`,c=e[a]===void 0,l=[];s.forEach(u=>{const A=`${o}Loading${u}`,h=e[A];if(h!==void 0&&c){l.push(A);const d=r[a].default;switch(e[a]={default:d},u){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${it(e[a])}`)}),Ye(Ye({},r),e)}function Fc(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Fc):Object.keys(i).reduce((e,t)=>(e[t]=Fc(i[t]),e),{}):i}function Kb(i,e){const t=i.loader;t!==Ng&&t!==Og?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):kb()&&(i.loader=Ng,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Jo=2,Wb=.1,qb=.05,Jb=100;class jb extends Jd{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Jb),this.mediaSource=t.mediaSource;const r=this.media=t.media;ki(r,"playing",this.onMediaPlaying),ki(r,"waiting",this.onMediaWaiting),ki(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(vi(r,"playing",this.onMediaPlaying),vi(r,"waiting",this.onMediaWaiting),vi(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const s=(r=this.hls)==null?void 0:r.config;if(!s)return;const{media:o,stalled:a}=this;if(!o)return;const{seeking:c}=o,l=this.seeking&&!c,u=!this.seeking&&c,A=o.paused&&!c||o.ended||o.playbackRate===0;if(this.seeking=c,e!==t){t&&(this.ended=0),this.moved=!0,c||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!A&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&this.stallResolved(e);return}if(A){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1}));return}if(!Le.getBuffered(o).length){this.nudgeRetry=0;return}const h=Le.bufferInfo(o,e,0),d=h.nextStart||0,f=this.fragmentTracker;if(c&&f&&this.hls){const _=Ug(this.hls.inFlightFragments,e),D=h.len>Jo,F=!d||_||d-e>Jo&&!f.getPartialFragment(e);if(D||F)return;this.moved=!1}const g=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!d)return;const D=Math.max(d,h.start||0)-e,O=!!(g!=null&&g.live)?g.targetduration*2:Jo,M=f.getPartialFragment(e);if(D>0&&(D<=O||M)){o.paused||this._trySkipBufferHole(M);return}}const p=s.detectStallWithCurrentTimeMs,v=self.performance.now(),B=this.waiting;if(a===null){B>0&&v-B<p?this.stalled=B:this.stalled=v;return}const C=v-a;if(!c&&(C>=p||B)&&this.hls){var y;if(((y=this.mediaSource)==null?void 0:y.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const x=Le.bufferInfo(o,e,s.maxBufferHole);this._tryFixBufferStall(x,C)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(I.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&n&&n.length>1&&e>n.end(0)){const s=Le.bufferedInfo(Le.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const o=Le.timeRangesToArray(n),a=Le.bufferedInfo(o,t,0).bufferedIndex;if(a>-1&&a<o.length-1){const c=Le.bufferedInfo(o,e,0).bufferedIndex,l=o[a].end,u=o[a+1].start;if((c===-1||c>a)&&u-l<1&&e-l<2){const A=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${u} buffered index: ${c}`);this.warn(A.message),this.media.currentTime+=1e-6;const h=this.fragmentTracker.getPartialFragment(e)||void 0,d=Le.bufferInfo(this.media,e,0);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:A,reason:A.message,frag:h,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(e,t){var r,n;const{fragmentTracker:s,media:o}=this,a=(r=this.hls)==null?void 0:r.config;if(!o||!s||!a)return;const c=o.currentTime,l=(n=this.hls)==null?void 0:n.latestLevelDetails,u=s.getPartialFragment(c);if((u||l!=null&&l.live&&c<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const A=e.buffered;(A&&A.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-c<a.maxBufferHole)&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:s}=this;if(!n&&s!==null&&r&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${it(e)})`);this.warn(o.message),t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,s=(t=this.hls)==null?void 0:t.config;if(!n||!r||!s)return 0;const o=n.currentTime,a=Le.bufferInfo(n,o,0),c=o<a.start?a.start:a.nextStart;if(c&&this.hls){const u=a.len<=s.maxBufferHole,A=a.len>0&&a.len<1&&n.readyState<3,h=c-o;if(h>0&&(u||A)){if(h>s.maxBufferHole){let f=!1;if(o===0){const g=r.getAppendedFrag(0,Ee.MAIN);g&&c<g.end&&(f=!0)}if(!f){const g=e||r.getAppendedFrag(o,Ee.MAIN);if(g){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Ug(this.hls.inFlightFragments,c))return 0;let v=!1,B=g.end;for(;B<c;){const C=r.getPartialFragment(B);if(C)B+=C.duration;else{v=!0;break}}if(v)return 0}}}const d=Math.max(c+qb,o+Wb);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${d}`),this.moved=!0,n.currentTime=d,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${d}`);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return d}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,s=t==null?void 0:t.config;if(!r||!s)return 0;const o=r.currentTime;if(this.nudgeRetry++,n<s.nudgeMaxRetry){const a=o+(n+1)*s.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${o} to ${a}`);this.warn(c.message),r.currentTime=a,t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${o} after ${s.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Ug(i,e){const t=Gg(i.main);if(t&&t.start<=e)return t;const r=Gg(i.audio);return r&&r.start<=e?r:null}function Gg(i){if(!i)return null;switch(i.state){case Z.IDLE:case Z.STOPPED:case Z.ENDED:case Z.ERROR:return null}return i.frag}const Xb=.25;function Pc(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function $g(i,e,t,r,n){let s=new i(e,t,"");try{s.value=r,n&&(s.type=n)}catch{s=new i(e,t,it(n?Ye({type:n},r):r))}return s}const jo=(()=>{const i=Pc();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function zb(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Zb{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(I.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&zr(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if(r.kind==="metadata"&&r.label==="id3")return pg(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:n}}}=this;if(!r&&!n)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Pc();if(o)for(let a=0;a<s.length;a++){const c=s[a].type;if(c===Yt.emsg&&!r||!n)continue;const l=Ff(s[a].data);if(l){const u=s[a].pts;let A=u+s[a].duration;A>jo&&(A=jo),A-u<=0&&(A=u+Xb);for(let d=0;d<l.length;d++){const f=l[d];if(!Pf(f)){this.updateId3CueEnds(u,c);const g=$g(o,u,A,f,c);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var r;const n=(r=this.id3Track)==null?void 0:r.cues;if(n)for(let s=n.length;s--;){const o=n[s];o.type===t&&o.startTime<e&&o.endTime===jo&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:c}}=o;if(s&&(a||c)){let l;n==="audio"?l=u=>u.type===Yt.audioId3&&c:n==="video"?l=u=>u.type===Yt.emsg&&a:l=u=>u.type===Yt.audioId3&&c||u.type===Yt.emsg&&a,Tc(s,t,r,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:r}=this,{dateRanges:n}=e,s=Object.keys(n);let o=this.dateRangeCuesAppended;if(r&&t){var a;if((a=r.cues)!=null&&a.length){const u=Object.keys(o).filter(A=>!s.includes(A));for(let A=u.length;A--;){const h=u[A],d=o[h].cues;delete o[h],Object.keys(d).forEach(f=>{try{const g=d[f];g.removeEventListener("enter",this.onEventCueEnter),r.removeCue(g)}catch{}})}}else o=this.dateRangeCuesAppended={}}const c=e.fragments[e.fragments.length-1];if(s.length===0||!de(c==null?void 0:c.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Pc();for(let u=0;u<s.length;u++){const A=s[u],h=n[A],d=h.startTime,f=o[A],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1,v=jo;const{duration:B,endDate:C}=h;if(C&&B!==null)v=d+B,p=!0;else if(h.endOnNext&&!p){const x=s.reduce((_,D)=>{if(D!==h.id){const F=n[D];if(F.class===h.class&&F.startDate>h.startDate&&(!_||h.startDate<_.startDate))return F}return _},null);x&&(v=x.startTime,p=!0)}const y=Object.keys(h.attr);for(let x=0;x<y.length;x++){const _=y[x];if(!FB(_))continue;const D=g[_];if(D)p&&!f.durationKnown?D.endTime=v:Math.abs(D.startTime-d)>.01&&(D.startTime=d,D.endTime=v);else if(l){let F=h.attr[_];PB(_)&&(F=zb(F));const M=$g(l,d,v,{key:_,data:F},Yt.dateRange);M&&(M.id=A,this.id3Track.addCue(M),g[_]=M,this.hls.config.interstitialsController&&(_==="X-ASSET-LIST"||_==="X-ASSET-URL")&&M.addEventListener("enter",this.onEventCueEnter))}}o[A]={cues:g,dateRange:h,durationKnown:p}}}}class eS{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:o}=this.config;if(!s||o===1||!r.live)return;const a=this.targetLatency;if(a===null)return;const c=n-a,l=Math.min(this.maxLatency,a+r.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const A=Math.min(2,Math.max(1,o)),h=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,d=Math.min(A,Math.max(1,h));this.changeMediaPlaybackRate(t,d)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,c=this.hls.userConfig;let l=a&&r||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=s!==void 0?s:o*n);const u=n;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const n=r.edge,s=e-t-this.edgeStalled,o=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(o,s),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(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.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(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.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===V.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class tS extends mc{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,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_LOADED,this.onManifestLoaded,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],s={},o={};let a=!1,c=!1,l=!1;t.levels.forEach(u=>{var A;const h=u.attrs;let{audioCodec:d,videoCodec:f}=u;d&&(u.audioCodec=d=Co(d,r)||void 0),((A=f)==null?void 0:A.indexOf("avc1"))===0&&(f=u.videoCodec=rB(f));const{width:g,height:p,unknownCodecs:v}=u;let B=v?v.length:0;if(v)for(let j=B;j--;){const X=v[j];this.isAudioSupported(X)?(u.audioCodec=d=d?`${d},${X}`:X,B--,Yr.audio[d.substring(0,4)]=2):this.isVideoSupported(X)&&(u.videoCodec=f=f?`${f},${X}`:X,B--,Yr.video[f.substring(0,4)]=2)}if(a||(a=!!(g&&p)),c||(c=!!f),l||(l=!!d),B||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:C,"FRAME-RATE":y,"HDCP-LEVEL":x,"PATHWAY-ID":_,RESOLUTION:D,"VIDEO-RANGE":F}=h,M=`${`${_||"."}-`}${u.bitrate}-${D}-${y}-${C}-${F}-${x}`;if(s[M])if(s[M].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const j=o[M]+=1;u.attrs["PATHWAY-ID"]=new Array(j+1).join(".");const X=this.createLevel(u);s[M]=X,n.push(X)}else s[M].addGroupId("audio",h.AUDIO),s[M].addGroupId("text",h.SUBTITLES);else{const j=this.createLevel(u);s[M]=j,o[M]=1,n.push(j)}}),this.filterAndSortMediaOptions(n,t,a,c,l)}createLevel(e){const t=new Wn(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(n.message),t.supportedResult=Dd(n,[])}return t}isAudioSupported(e){return Nl(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Nl(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,s){let o=[],a=[],c=e;if((r||n)&&s&&(c=c.filter(({videoCodec:p,videoRange:v,width:B,height:C})=>(!!p||!!(B&&C))&&lB(v))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let p="no level with compatible codecs found in manifest",v=p;t.levels.length&&(v=`one or more CODECS in variant not supported: ${it(t.levels.map(C=>C.attrs.CODECS).filter((C,y,x)=>x.indexOf(C)===y))}`,this.warn(v),p+=` (${v})`);const B=new Error(p);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:B,reason:v})}});return}t.audioTracks&&(o=t.audioTracks.filter(p=>!p.audioCodec||this.isAudioSupported(p.audioCodec)),Hg(o)),t.subtitles&&(a=t.subtitles,Hg(a));const l=c.slice(0);c.sort((p,v)=>{if(p.attrs["HDCP-LEVEL"]!==v.attrs["HDCP-LEVEL"])return(p.attrs["HDCP-LEVEL"]||"")>(v.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&p.height!==v.height)return p.height-v.height;if(p.frameRate!==v.frameRate)return p.frameRate-v.frameRate;if(p.videoRange!==v.videoRange)return To.indexOf(p.videoRange)-To.indexOf(v.videoRange);if(p.videoCodec!==v.videoCodec){const B=Qd(p.videoCodec),C=Qd(v.videoCodec);if(B!==C)return C-B}if(p.uri===v.uri&&p.codecSet!==v.codecSet){const B=yo(p.codecSet),C=yo(v.codecSet);if(B!==C)return C-B}return p.averageBitrate!==v.averageBitrate?p.averageBitrate-v.averageBitrate:0});let u=l[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==l.length)){for(let p=0;p<l.length;p++)if(l[p].pathwayId===c[0].pathwayId){u=l[p];break}}this._levels=c;for(let p=0;p<c.length;p++)if(c[p]===u){var A;this._firstLevel=p;const v=u.bitrate,B=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${v}`),((A=this.hls.userConfig)==null?void 0:A.abrEwmaDefaultEstimate)===void 0){const C=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);C>B&&B===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=C)}break}const h=s&&!n,d=this.hls.config,f=!!(d.audioStreamController&&d.audioTrackController),g={levels:c,audioTracks:o,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:f&&!h&&o.some(p=>!!p.url)};this.hls.trigger(I.MANIFEST_PARSED,g)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),A=e<0;if(this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.LEVEL_SWITCH_ERROR,level:e,fatal:A,error:u,reason:u.message}),A)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,r===e&&n&&s===a)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,c);const l=o.details;if(!l||l.live){const u=this.switchParams(o.uri,n==null?void 0:n.details,l);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===Me.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Ee.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(s=>!!r[s]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,o=t.levelInfo;if(!o){var a;this.warn(`Invalid level index ${n}`),(a=t.deliveryDirectives)!=null&&a.skip&&(s.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(r=t.deliveryDirectives)!=null&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],o=e.details,a=o==null?void 0:o.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(I.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((s,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));Cf(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(I.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Hg(i){const e={};i.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}function Yg(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vg(){if(!er())return!1;const e=Yg();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function iS(){if(!Vg())return!1;const i=er();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(Kn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(Kn(e,"audio"))))}function rS(){var i;const e=Yg();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const nS=100;class sS extends ic{constructor(e,t,r){super(e,t,r,"stream-controller",Ee.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,s=n?n.currentTime:null;if(s===null||!de(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const o=this.getFwdBufferInfoAtPos(n,s,Ee.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(nS),this.level=-1,!this.startFragRequested){let s=n.startLevel;s===-1&&(n.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=n.firstAutoLevel),n.nextLoadLevel=s,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Z.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Z.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Z.WAITING_LEVEL:{const{levels:t,level:r}=this,n=t==null?void 0:t[r],s=n==null?void 0:n.details;if(s&&(!s.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(s))break;this.state=Z.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Z.IDLE;break}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),r=this.retryDate;if(!r||t>=r||(e=this.media)!=null&&e.seeking){const{levels:n,level:s}=this,o=n==null?void 0:n[s];this.resetStartWhenNotLoaded(o||null),this.state=Z.IDLE}}break}this.state===Z.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[s]))return;const o=r[s],a=this.getMainFwdBufferInfo();if(a===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(a,c)){const g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(I.BUFFER_EOS,g),this.state=Z.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=o.details;if(!l||this.state===Z.WAITING_LEVEL||this.waitForLive(o)){this.level=s,this.state=Z.WAITING_LEVEL,this.startFragRequested=!1;return}const u=a.len,A=this.getMaxBufferLength(o.maxBitrate);if(u>=A)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&Ct(d)&&this.fragmentTracker.getState(d)!==It.OK){var f;const p=((f=this.backtrackFragment)!=null?f:d).sn-l.startSN,v=l.fragments[p-1];v&&d.cc===v.cc&&(d=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,h)){if(!d.gap){const p=this.audioOnly&&!this.altAudio?qe.AUDIO:qe.VIDEO,v=(p===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,Ee.MAIN)}d=this.getNextFragmentLoopLoading(d,l,a,Ee.MAIN,A)}d&&(d.initSegment&&!d.initSegment.data&&!this.bitrateTest&&(d=d.initSegment),this.loadFragment(d,o,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===It.NOT_LOADED||n===It.PARTIAL?Ct(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Ee.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<s.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,c=e[a],l=this.fragLastKbps;l&&this.fragCurrent?r=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:r=0}else r=0;const o=this.getBufferedFrag(t.currentTime+r);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const c=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,u=Math.max(o.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Z.KEY_LOADING:case Z.FRAG_LOADING:case Z.FRAG_LOADING_WAITING_RETRY:case Z.PARSING:case Z.PARSED:this.state=Z.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;ki(r,"playing",this.onMediaPlaying),ki(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(vi(r,"playing",this.onMediaPlaying),vi(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;t.levels.forEach(s=>{const o=s.audioCodec;o&&(r=r||o.indexOf("mp4a.40.2")!==-1,n=n||o.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=r&&n&&!rS(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Z.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=Z.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:s}=this,o=t.level,a=t.details,c=a.totalduration;if(!n){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${c}`);const l=t.levelInfo,u=this.fragCurrent;u&&(this.state===Z.FRAG_LOADING||this.state===Z.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let A=0;if(a.live||(r=l.details)!=null&&r.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;A=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,A),this.hls.trigger(I.LEVEL_UPDATED,{details:a,level:o}),this.state===Z.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Z.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=this.getLoadPosition(),o=e.fragmentStart,a=e.edge,c=s>=o-t.maxFragLookUpTolerance&&s<=a;if(n!==null&&r.duration>n&&(s<n||!c)){const l=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!c&&r.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),r.currentTime=n))}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const a=o[r.level];if(!a){this.warn(`Level ${r.level} not found on progress`);return}const c=a.details;if(!c){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const l=a.videoCodec,u=c.PTSKnown||!c.live,A=(t=r.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new tg(this.hls,Ee.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,g=f!==-1,p=new Yl(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),v=this.initPTS[r.cc];d.push(s,A,h,l,r,n,c.totalduration,u,p,v)}onAudioTrackSwitching(e,t){const r=this.hls,n=this.altAudio===2;if(So(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.fragmentTracker.removeAllFragments(),r.once(I.BUFFER_FLUSHED,()=>{var o;(o=this.hls)==null||o.trigger(I.AUDIO_TRACK_SWITCHED,t)}),r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(I.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=So(t.url,this.hls);if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,o=!1;for(const a in r){const c=r[a];if(c.id==="main"){if(s=a,n=c,a==="video"){const l=r[a];l&&(this.videoBuffer=l.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,s=r.type===Ee.MAIN;if(s){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Z.PARSED&&(this.state=Z.IDLE);return}const a=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Ct(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const o=this.media;o&&(!this._hasEnoughToStart&&Le.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;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.MAIN,t);break;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===Me.LEVEL&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Z.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==qe.AUDIO||!this.altAudio){const r=(t===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,Ee.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&r&&(r+=n);const s=this.getLevelDetails(),o=Le.getBuffered(e),a=o.length?o.start(0):0,c=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);c>0&&(c<l||this.loadingParts&&c<2*((s==null?void 0:s.partTarget)||0))&&(this.log(`adjusting start position by ${c} to match buffer start`),r+=c,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${a}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(r=>{const{hls:n}=this,s=r==null?void 0:r.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Z.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=s.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(I.FRAG_LOADED,r),s.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const r=this.playlistType,{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:c,part:l,level:u}=a,{video:A,text:h,id3:d,initSegment:f}=s,{details:g}=u,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=Z.PARSING,f){if(f!=null&&f.tracks){const C=c.initSegment||c;this._bufferInitSegment(u,f.tracks,C,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:r,tracks:f.tracks})}const v=f.initPTS,B=f.timescale;de(v)&&(this.initPTS[c.cc]={baseTime:v,timescale:B},n.trigger(I.INIT_PTS_FOUND,{frag:c,id:r,initPTS:v,timescale:B}))}if(A&&g){p&&A.type==="audiovideo"&&this.logMuxedErr(c);const v=g.fragments[c.sn-1-g.startSN],B=c.sn===g.startSN,C=!v||c.cc>v.cc;if(s.independent!==!1){const{startPTS:y,endPTS:x,startDTS:_,endDTS:D}=A;if(l)l.elementaryStreams[A.type]={startPTS:y,endPTS:x,startDTS:_,endDTS:D};else if(A.firstKeyFrame&&A.independent&&o.id===1&&!C&&(this.couldBacktrack=!0),A.dropped&&A.independent){const F=this.getMainFwdBufferInfo(),O=(F?F.end:this.getLoadPosition())+this.config.maxBufferHole,M=A.firstKeyFramePTS?A.firstKeyFramePTS:y;if(!B&&O<M-this.config.maxBufferHole&&!C){this.backtrack(c);return}else C&&(c.gap=!0);c.setElementaryStreamInfo(A.type,c.start,x,c.start,D,!0)}else B&&y-(g.appliedTimelineOffset||0)>Jo&&(c.gap=!0);c.setElementaryStreamInfo(A.type,y,x,_,D),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(A,c,l,o,B||C)}else if(B||C)c.gap=!0;else{this.backtrack(c);return}}if(p){const{startPTS:v,endPTS:B,startDTS:C,endDTS:y}=p;l&&(l.elementaryStreams[qe.AUDIO]={startPTS:v,endPTS:B,startDTS:C,endDTS:y}),c.setElementaryStreamInfo(qe.AUDIO,v,B,C,y),this.bufferFragmentData(p,c,l,o)}if(g&&d!=null&&(t=d.samples)!=null&&t.length){const v={id:r,frag:c,details:g,samples:d.samples};n.trigger(I.FRAG_PARSING_METADATA,v)}if(g&&h){const v={id:r,frag:c,details:g,samples:h.samples};n.trigger(I.FRAG_PARSING_USERDATA,v)}}logMuxedErr(e){this.warn(`${Ct(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==Z.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:s,video:o,audiovideo:a}=t;if(s){let l=Bo(s.codec,e.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const A=s.metadata;A&&"channelCount"in A&&(A.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),s.levelCodec=l,s.id=Ee.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${s.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=Ee.MAIN;const l=o.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${o.codec!==l?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(I.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const A=t[l].initSegment;A!=null&&A.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:l,data:A,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Ee.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=e==null?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Z.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Le.isBuffered(e,r)?t=this.getAppendedFrag(r):Le.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,s=t.level;(!n||t.sn!==n.sn||n.level!==s)&&(this.fragPlaying=t,this.hls.trigger(I.FRAG_CHANGED,{frag:t}),(!n||n.level!==s)&&this.hls.trigger(I.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return de(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(de(t)){const r=this.getLevelDetails(),n=this.currentFrag||(r?br(null,r.fragments,t):null);if(n){const s=n.programDateTime;if(s!==null){const o=s+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class oS{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[r].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=V.KEY_LOAD_ERROR,r,n,s){return new Ri({type:Ie.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:n}=e;for(let s=0;s<t.length;s++){const o=t[s];if(n<=o.cc&&(r==="initSegment"||o.sn==="initSegment"||r<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,l))}const o=s.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((r=a)!=null&&r.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});if((n=a)!=null&&n.keyLoadPromise){var c;switch((c=a.mediaKeySessionContext)==null?void 0:c.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(l=>(s.key=l.keyInfo.decryptdata.key,{frag:e,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const n=this.emeController.loadKey(r);if(n)return(e.keyLoadPromise=n.then(s=>(e.mediaKeySessionContext=s,r))).catch(s=>{throw e.keyLoadPromise=null,s})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=r.loader,s=new n(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((o,a)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(h,d,f,g)=>{const{frag:p,keyInfo:v,url:B}=f;if(!p.decryptdata||v!==this.keyUriToKeyInfo[B])return a(this.createKeyLoadError(p,V.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,v.loader=null,o({frag:p,keyInfo:v})},onError:(h,d,f,g)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),f,Ye({url:c.url,data:void 0},h)))},onTimeout:(h,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(h,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};s.load(c,u,A)})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[n],s&&s.destroy()}}function Kg(i){const{type:e}=i;switch(e){case Me.AUDIO_TRACK:return Ee.AUDIO;case Me.SUBTITLE_TRACK:return Ee.SUBTITLE;default:return Ee.MAIN}}function Nc(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class aS{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=r||n,o=new s(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Me.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:s,url:o,deliveryDirectives:a,levelInfo:c}=t;this.load({id:r,level:n,pathwayId:s,responseType:"text",type:Me.LEVEL,url:o,deliveryDirectives:a,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:o,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Me.AUDIO_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:o,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Me.SUBTITLE_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[Me.LEVEL];if(r){const n=r.context;n&&!t.levels.some(s=>s===n.levelOrTrack)&&(r.abort(),delete this.loaders[Me.LEVEL])}}load(e){var t;const r=this.hls.config;let n=this.getInternalLoader(e);if(n){const l=this.hls.logger,u=n.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let s;if(e.type===Me.MANIFEST?s=r.manifestLoadPolicy.default:s=We({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),de((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Me.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Me.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Me.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const u=l.partTarget,A=l.targetduration;if(u&&A){const h=Math.max(u*3,A*.8)*1e3;s=We({},s,{maxTimeToFirstByteMs:Math.min(h,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,s.maxTimeToFirstByteMs)})}}}const o=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(l,u,A,h)=>{const d=this.getInternalLoader(A);this.resetInternalLoader(A.type);const f=l.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,A,new Error("no EXTM3U delimiter"),h||null,u);return}u.parsing.start=performance.now(),mi.isMediaPlaylist(f)||A.type!==Me.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,A,h||null,d):this.handleMasterPlaylist(l,u,A,h)},onError:(l,u,A,h)=>{this.handleNetworkError(u,A,!1,l,h)},onTimeout:(l,u,A)=>{this.handleNetworkError(u,A,!0,void 0,l)}};n.load(e,a,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const s=this.hls,o=e.data,a=Nc(e,r),c=mi.parseMasterPlaylist(o,a);if(c.playlistParsingError){this.handleManifestParsingError(e,r,c.playlistParsingError,n,t);return}const{contentSteering:l,levels:u,sessionData:A,sessionKeys:h,startTimeOffset:d,variableList:f}=c;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=mi.parseMasterPlaylistMedia(o,a,c);g.length&&!g.some(C=>!C.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new st({}),bitrate:0,url:""})),s.trigger(I.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:p,captions:v,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:A,sessionKeys:h,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const o=this.hls,{id:a,level:c,type:l}=r,u=Nc(e,r),A=de(c)?c:de(a)?a:0,h=Kg(r),d=mi.parseLevelPlaylist(e.data,u,A,h,0,this.variableList);if(l===Me.MANIFEST){const f={attrs:new st({}),bitrate:0,details:d,name:"",url:u};d.requestScheduled=t.loading.start+Ef(d,0),o.trigger(I.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=d,this.handlePlaylistLoaded(d,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.MANIFEST_PARSING_ERROR,fatal:t.type===Me.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let o=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Me.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Me.AUDIO_TRACK||e.type===Me.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=V.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case Me.MANIFEST:c=r?V.MANIFEST_LOAD_TIMEOUT:V.MANIFEST_LOAD_ERROR,l=!0;break;case Me.LEVEL:c=r?V.LEVEL_LOAD_TIMEOUT:V.LEVEL_LOAD_ERROR,l=!1;break;case Me.AUDIO_TRACK:c=r?V.AUDIO_TRACK_LOAD_TIMEOUT:V.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Me.SUBTITLE_TRACK:c=r?V.SUBTITLE_TRACK_LOAD_TIMEOUT:V.SUBTITLE_LOAD_ERROR,l=!1;break}u&&this.resetInternalLoader(e.type);const A={type:Ie.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:s};if(n){const h=(t==null?void 0:t.url)||e.url;A.response=Ye({url:h,data:void 0},n)}this.hls.trigger(I.ERROR,A)}handlePlaylistLoaded(e,t,r,n,s,o){const a=this.hls,{type:c,level:l,id:u,groupId:A,deliveryDirectives:h}=n,d=Nc(t,n),f=Kg(n),g=typeof n.level=="number"&&f===Ee.MAIN?l:void 0;if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:v,reason:v.message,response:t,context:n,level:g,parent:f,networkDetails:s,stats:r});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!a.config.ignorePlaylistParsingErrors){a.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:t,context:n,level:g,parent:f,networkDetails:s,stats:r});return}e.playlistParsingError=null}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Me.MANIFEST:case Me.LEVEL:a.trigger(I.LEVEL_LOADED,{details:e,levelInfo:n.levelOrTrack||a.levels[0],level:g||0,id:u||0,stats:r,networkDetails:s,deliveryDirectives:h,withoutMultiVariant:c===Me.MANIFEST});break;case Me.AUDIO_TRACK:a.trigger(I.AUDIO_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:u||0,groupId:A||"",stats:r,networkDetails:s,deliveryDirectives:h});break;case Me.SUBTITLE_TRACK:a.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:u||0,groupId:A||"",stats:r,networkDetails:s,deliveryDirectives:h});break}}}class ai{static get version(){return Xn}static isMSESupported(){return Vg()}static isSupported(){return iS()}static getMediaSource(){return er()}static get Events(){return I}static get MetadataSchema(){return Yt}static get ErrorTypes(){return Ie}static get ErrorDetails(){return V}static get DefaultConfig(){return ai.defaultConfig?ai.defaultConfig:Hb}static set DefaultConfig(e){ai.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new nc,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=DC(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=Vb(ai.DefaultConfig,e,t);this.userConfig=e,r.progressive&&Kb(r,t);const{abrController:n,bufferController:s,capLevelController:o,errorController:a,fpsController:c}=r,l=new a(this),u=this.abrController=new n(this),A=new TB(this),h=r.interstitialsController,d=h?this.interstitialsController=new h(this,ai):null,f=this.bufferController=new s(this,A),g=this.capLevelController=new o(this),p=new c(this),v=new aS(this),B=r.contentSteeringController,C=B?new B(this):null,y=this.levelController=new tS(this,C),x=new Zb(this),_=new oS(this.config),D=this.streamController=new sS(this,A,_),F=this.gapController=new jb(this,A);g.setStreamController(D),p.setStreamController(D);const O=[v,y,D];d&&O.splice(1,0,d),C&&O.splice(1,0,C),this.networkControllers=O;const M=[u,f,F,g,p,x,A];this.audioTrackController=this.createController(r.audioTrackController,O);const j=r.audioStreamController;j&&O.push(this.audioStreamController=new j(this,A,_)),this.subtitleTrackController=this.createController(r.subtitleTrackController,O);const X=r.subtitleStreamController;X&&O.push(this.subtititleStreamController=new X(this,A,_)),this.createController(r.timelineController,M),_.emeController=this.emeController=this.createController(r.emeController,M),this.cmcdController=this.createController(r.cmcdController,M),this.latencyController=this.createController(eS,M),this.coreComponents=M,O.push(l);const le=l.onErrorOut;typeof le=="function"&&this.on(I.ERROR,le,l),this.on(I.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const n=e===I.ERROR;this.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:n,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const s=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.ATTACH_MEDIA_ERROR,fatal:!0,error:s});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,n=t?e:{media:r};this._media=r,this.trigger(I.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(I.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,n=this._url=Dl.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(I.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Ee.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Ee.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Ee.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=CT()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){aB(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,r)for(let s=n;s--;){const o=e[s].attrs["HDCP-LEVEL"];if(o&&o<=r)return s}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const r=Nd(t);return kd(e,r,navigator.mediaCapabilities)}}ai.defaultConfig=void 0;function lS(i){return i&&i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function cS(i){return i}function AS(i,e){e=e||{};const t=e.delimiter||".",r=e.maxDepth,n=e.transformKey||cS,s={};function o(a,c,l){l=l||1,Object.keys(a).forEach(function(u){const A=a[u],h=e.safe&&Array.isArray(A),d=Object.prototype.toString.call(A),f=lS(A),g=d==="[object Object]"||d==="[object Array]",p=c?c+t+n(u):n(u);if(!h&&!f&&g&&Object.keys(A).length&&(!e.maxDepth||l<r))return o(A,p,l+1);s[p]=A})}return o(i),s}var Wg=Number.isNaN||function(e){return typeof e=="number"&&e!==e};function uS(i,e){return!!(i===e||Wg(i)&&Wg(e))}function hS(i,e){if(i.length!==e.length)return!1;for(var t=0;t<i.length;t++)if(!uS(i[t],e[t]))return!1;return!0}function dS(i,e){e===void 0&&(e=hS);var t=null;function r(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];if(t&&t.lastThis===this&&e(n,t.lastArgs))return t.lastResult;var o=i.apply(this,n);return t={lastResult:o,lastArgs:n,lastThis:this},o}return r.clear=function(){t=null},r}/**
2524
+ `:(s=r.childNodes)!=null&&s.length?Lg(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}function xb(i,e,t){const r="http://www.w3.org/ns/ttml#styling";let n=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),s.reduce((a,c)=>{const l=kc(e,r,c)||kc(i,r,c)||kc(n,r,c);return l&&(a[c]=l),a},{})}function kc(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function kg(i){return new Error(`Could not parse ttml timestamp ${i}`)}function Mc(i,e){if(!i)return null;let t=Sg(i);return t===null&&(wg.test(i)?t=Qb(i,e):_g.test(i)&&(t=wb(i,e))),t}function Qb(i,e){const t=wg.exec(i),r=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+r/e.frameRate}function wb(i,e){const t=_g.exec(i),r=Number(t[1]);switch(t[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}class qo{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class _b{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pg(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(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_LOADED,this.onManifestLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){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_LOADED,this.onManifestLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new qo(this,"textTrack1"),t=new qo(this,"textTrack2"),r=new qo(this,"textTrack3"),n=new qo(this,"textTrack4");this.cea608Parser1=new bg(1,e,t),this.cea608Parser2=new bg(3,r,n)}addCues(e,t,r,n,s){let o=!1;for(let a=s.length;a--;){const c=s[a],l=Rb(c[0],c[1],t,r);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],r),o=!0,l/(r-t)>.5))return}if(o||s.push([t,r]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,r,n)}else{const a=this.Cues.newCue(null,t,r,n);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){const{unparsedVttFrags:o}=this;r===Ee.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:s}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(I.FRAG_LOADED,a)}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const s=r.textTracks[n];if(Fg(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:o}=t[e],a=this.getExistingTrack(s,o);if(a)r[e]=a,zr(r[e]),pg(r[e],n);else{const c=this.createTextTrack("captions",s,o);c&&(c[e]=!0,r[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r=t.label,n={_id:e,label:r,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(s=>{zr(n[s]),delete n[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pg(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let r=0;r<t.length;r++)zr(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(s=>s.textCodec===Dc);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(rg(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const o=this.media,a=o?Yo(o.textTracks):null;if(this.tracks.forEach((c,l)=>{let u;if(a){let A=null;for(let h=0;h<a.length;h++)if(a[h]&&Fg(a[h],c)){A=a[h],a[h]=null;break}A&&(u=A)}if(u)zr(u);else{const A=Mg(c);u=this.createTextTrack(A,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),a!=null&&a.length){const c=a.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const n=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!n)return;const s=`textTrack${n[1]}`,o=this.captionsProperties[s];o&&(o.label=r.name,r.lang&&(o.languageCode=r.lang),o.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Ee.MAIN){var r,n;const{cea608Parser1:s,cea608Parser2:o,lastSn:a}=this,{cc:c,sn:l}=t.frag,u=(r=(n=t.part)==null?void 0:n.index)!=null?r:-1;s&&o&&(l!==a+1||l===a&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(s.reset(),o.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===Ee.SUBTITLE)if(n.byteLength){const s=r.decryptdata,o="stats"in t;if(s==null||!s.encrypted||o){const a=this.tracks[r.level],c=this.vttCCs;c[r.cc]||(c[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),a&&a.textCodec===Dc?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Rg(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{r.logger.log(`Failed to parse IMSC1: ${n}`),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:o}=this,a=s.length-1;if(!s[r.cc]&&a===-1){o.push(e);return}const c=this.hls,l=(t=r.initSegment)!=null&&t.data?jt(r.initSegment.data,new Uint8Array(n)).buffer:n;Tb(l,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const A=u.message==="Missing initPTS for VTT MPEGTS";A?o.push(e):this._fallbackToIMSC1(r,n),c.logger.log(`Failed to parse VTT cue: ${u}`),!(A&&a>r.cc)&&c.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Rg(t,this.initPTS[e.cc],()=>{r.textCodec=Dc,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(s=>mg(n,s))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(I.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===Ee.SUBTITLE&&this.onFragLoaded(I.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(!(r.type===Ee.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let s=0;s<n.length;s++){const o=n[s].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(o);this.cea608Parser1.addData(n[s].pts,a[0]),this.cea608Parser2.addData(n[s].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:o}=this;if(!(!o||o.currentTime<r)){if(!s||s==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(c=>Tc(a[c],t,r))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(c=>Tc(a[c],t,n))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let n=2;for(let s=0;s<r;s++){const o=e[n++],a=127&e[n++],c=127&e[n++];if(a===0&&c===0)continue;if((4&o)!==0){const u=3&o;(u===0||u===1)&&(t[u].push(a),t[u].push(c))}}return t}}function Mg(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Fg(i,e){return!!i&&i.kind===Mg(e)&&Ec(e,i)}function Rb(i,e,t,r){return Math.min(e,r)-Math.max(i,t)}function Pg(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Db=/\s/,Lb={newCue(i,e,t,r){const n=[];let s,o,a,c,l;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(s=r.rows[h],a=!0,c=0,l="",!s.isEmpty()){var A;for(let g=0;g<s.chars.length;g++)Db.test(s.chars[g].uchar)&&a?c++:(l+=s.chars[g].uchar,a=!1);s.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const d=Qg(l.trim()),f=Rc(e,t,d);i!=null&&(A=i.cues)!=null&&A.getCueById(f)||(o=new u(e,t,d),o.id=f,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return i&&n.length&&(n.sort((h,d)=>h.line==="auto"||d.line==="auto"?0:h.line>8&&d.line>8?d.line-h.line:h.line-d.line),n.forEach(h=>mg(i,h))),n}};function kb(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Mb=/(\d+)-(\d+)\/(\d+)/;class Ng{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Ob,this.controller=new self.AbortController,this.stats=new Ll}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const s=Fb(e,this.controller.signal),o=e.responseType==="arraybuffer",a=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=c&&de(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(ts(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(A=>{var h;this.response=this.loader=A;const d=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},l-(d-n.loading.start)),!A.ok){const{status:g,statusText:p}=A;throw new Ub(p||"fetch, bad network response",g,A)}n.loading.first=d,n.total=Nb(A.headers)||n.total;const f=(h=this.callbacks)==null?void 0:h.onProgress;return f&&de(t.highWaterMark)?this.loadProgressively(A,n,e,t.highWaterMark,f):o?A.arrayBuffer():e.responseType==="json"?A.json():A.text()}).then(A=>{var h,d;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const g=A[a];g&&(n.loaded=n.total=g);const p={url:f.url,data:A,code:f.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!de(t.highWaterMark)&&v(n,e,A,f),(d=this.callbacks)==null||d.onSuccess(p,n,e,f)}).catch(A=>{var h;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const d=A&&A.code||0,f=A?A.message:null;(h=this.callbacks)==null||h.onError({code:d,text:f},e,A?A.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,s){const o=new xf,a=e.body.getReader(),c=()=>a.read().then(l=>{if(l.done)return o.dataLength&&s(t,r,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=l.value,A=u.length;return t.loaded+=A,A<n||o.dataLength?(o.push(u),o.dataLength>=n&&s(t,r,o.flush().buffer,e)):s(t,r,u.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Fb(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(We({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function Pb(i){const e=Mb.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Nb(i){const e=i.get("Content-Range");if(e){const r=Pb(e);if(de(r))return r}const t=i.get("Content-Length");if(t)return parseInt(t)}function Ob(i,e){return new self.Request(i.url,e)}class Ub extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const Gb=/^age:\s*[\d.]+\s*$/im;class Og{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ll,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return s(r,t.url)}).catch(o=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),s(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(o=>{var a;(a=this.callbacks)==null||a.onError({code:r.status,text:o.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:o}=r.loadPolicy;if(n)for(const a in n)e.setRequestHeader(a,n[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&de(s)?s:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,s=this.config;if(!r.aborted&&n>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,u=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=u??t.response;if(f!=null){var o,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=t.responseType==="arraybuffer"?f.byteLength:f.length;r.loaded=r.total=g,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const p=(o=this.callbacks)==null?void 0:o.onProgress;p&&p(r,e,f,t);const v={url:t.responseURL,data:f,code:l};(a=this.callbacks)==null||a.onSuccess(v,r,e,t);return}}const A=s.loadPolicy.errorRetry,h=r.retry,d={url:e.url,data:void 0,code:l};if(Qo(A,h,!1,d))this.retry(A);else{var c;Oe.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Qo(e,t,!0))this.retry(e);else{var r;Oe.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=$l(e,r.retry),r.retry++,Oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Gb.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const $b={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Hb=Ye(Ye({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Og,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mB,bufferController:c1,capLevelController:vc,errorController:BB,fpsController:W1,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:rf,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:$b},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Yb()),{},{subtitleStreamController:nb,subtitleTrackController:j1,timelineController:_b,audioStreamController:s1,audioTrackController:o1,emeController:Xr,cmcdController:Y1,contentSteeringController:K1,interstitialsController:rb});function Yb(){return{cueHandler:Lb,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Vb(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Fc(i),n=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const a=`${o==="level"?"playlist":o}LoadPolicy`,c=e[a]===void 0,l=[];s.forEach(u=>{const A=`${o}Loading${u}`,h=e[A];if(h!==void 0&&c){l.push(A);const d=r[a].default;switch(e[a]={default:d},u){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${it(e[a])}`)}),Ye(Ye({},r),e)}function Fc(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Fc):Object.keys(i).reduce((e,t)=>(e[t]=Fc(i[t]),e),{}):i}function Kb(i,e){const t=i.loader;t!==Ng&&t!==Og?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):kb()&&(i.loader=Ng,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Jo=2,Wb=.1,qb=.05,Jb=100;class jb extends Jd{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Jb),this.mediaSource=t.mediaSource;const r=this.media=t.media;ki(r,"playing",this.onMediaPlaying),ki(r,"waiting",this.onMediaWaiting),ki(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(vi(r,"playing",this.onMediaPlaying),vi(r,"waiting",this.onMediaWaiting),vi(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const s=(r=this.hls)==null?void 0:r.config;if(!s)return;const{media:o,stalled:a}=this;if(!o)return;const{seeking:c}=o,l=this.seeking&&!c,u=!this.seeking&&c,A=o.paused&&!c||o.ended||o.playbackRate===0;if(this.seeking=c,e!==t){t&&(this.ended=0),this.moved=!0,c||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!A&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&this.stallResolved(e);return}if(A){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1}));return}if(!Le.getBuffered(o).length){this.nudgeRetry=0;return}const h=Le.bufferInfo(o,e,0),d=h.nextStart||0,f=this.fragmentTracker;if(c&&f&&this.hls){const _=Ug(this.hls.inFlightFragments,e),D=h.len>Jo,F=!d||_||d-e>Jo&&!f.getPartialFragment(e);if(D||F)return;this.moved=!1}const g=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!d)return;const D=Math.max(d,h.start||0)-e,O=!!(g!=null&&g.live)?g.targetduration*2:Jo,M=f.getPartialFragment(e);if(D>0&&(D<=O||M)){o.paused||this._trySkipBufferHole(M);return}}const p=s.detectStallWithCurrentTimeMs,v=self.performance.now(),B=this.waiting;if(a===null){B>0&&v-B<p?this.stalled=B:this.stalled=v;return}const C=v-a;if(!c&&(C>=p||B)&&this.hls){var y;if(((y=this.mediaSource)==null?void 0:y.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const x=Le.bufferInfo(o,e,s.maxBufferHole);this._tryFixBufferStall(x,C)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(I.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&n&&n.length>1&&e>n.end(0)){const s=Le.bufferedInfo(Le.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const o=Le.timeRangesToArray(n),a=Le.bufferedInfo(o,t,0).bufferedIndex;if(a>-1&&a<o.length-1){const c=Le.bufferedInfo(o,e,0).bufferedIndex,l=o[a].end,u=o[a+1].start;if((c===-1||c>a)&&u-l<1&&e-l<2){const A=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${u} buffered index: ${c}`);this.warn(A.message),this.media.currentTime+=1e-6;const h=this.fragmentTracker.getPartialFragment(e)||void 0,d=Le.bufferInfo(this.media,e,0);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:A,reason:A.message,frag:h,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(e,t){var r,n;const{fragmentTracker:s,media:o}=this,a=(r=this.hls)==null?void 0:r.config;if(!o||!s||!a)return;const c=o.currentTime,l=(n=this.hls)==null?void 0:n.latestLevelDetails,u=s.getPartialFragment(c);if((u||l!=null&&l.live&&c<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const A=e.buffered;(A&&A.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-c<a.maxBufferHole)&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:s}=this;if(!n&&s!==null&&r&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${it(e)})`);this.warn(o.message),t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,s=(t=this.hls)==null?void 0:t.config;if(!n||!r||!s)return 0;const o=n.currentTime,a=Le.bufferInfo(n,o,0),c=o<a.start?a.start:a.nextStart;if(c&&this.hls){const u=a.len<=s.maxBufferHole,A=a.len>0&&a.len<1&&n.readyState<3,h=c-o;if(h>0&&(u||A)){if(h>s.maxBufferHole){let f=!1;if(o===0){const g=r.getAppendedFrag(0,Ee.MAIN);g&&c<g.end&&(f=!0)}if(!f){const g=e||r.getAppendedFrag(o,Ee.MAIN);if(g){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Ug(this.hls.inFlightFragments,c))return 0;let v=!1,B=g.end;for(;B<c;){const C=r.getPartialFragment(B);if(C)B+=C.duration;else{v=!0;break}}if(v)return 0}}}const d=Math.max(c+qb,o+Wb);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${d}`),this.moved=!0,n.currentTime=d,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${d}`);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return d}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,s=t==null?void 0:t.config;if(!r||!s)return 0;const o=r.currentTime;if(this.nudgeRetry++,n<s.nudgeMaxRetry){const a=o+(n+1)*s.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${o} to ${a}`);this.warn(c.message),r.currentTime=a,t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${o} after ${s.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Ug(i,e){const t=Gg(i.main);if(t&&t.start<=e)return t;const r=Gg(i.audio);return r&&r.start<=e?r:null}function Gg(i){if(!i)return null;switch(i.state){case Z.IDLE:case Z.STOPPED:case Z.ENDED:case Z.ERROR:return null}return i.frag}const Xb=.25;function Pc(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function $g(i,e,t,r,n){let s=new i(e,t,"");try{s.value=r,n&&(s.type=n)}catch{s=new i(e,t,it(n?Ye({type:n},r):r))}return s}const jo=(()=>{const i=Pc();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function zb(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Zb{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(I.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&zr(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if(r.kind==="metadata"&&r.label==="id3")return pg(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:n}}}=this;if(!r&&!n)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Pc();if(o)for(let a=0;a<s.length;a++){const c=s[a].type;if(c===Yt.emsg&&!r||!n)continue;const l=Ff(s[a].data);if(l){const u=s[a].pts;let A=u+s[a].duration;A>jo&&(A=jo),A-u<=0&&(A=u+Xb);for(let d=0;d<l.length;d++){const f=l[d];if(!Pf(f)){this.updateId3CueEnds(u,c);const g=$g(o,u,A,f,c);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var r;const n=(r=this.id3Track)==null?void 0:r.cues;if(n)for(let s=n.length;s--;){const o=n[s];o.type===t&&o.startTime<e&&o.endTime===jo&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:c}}=o;if(s&&(a||c)){let l;n==="audio"?l=u=>u.type===Yt.audioId3&&c:n==="video"?l=u=>u.type===Yt.emsg&&a:l=u=>u.type===Yt.audioId3&&c||u.type===Yt.emsg&&a,Tc(s,t,r,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:r}=this,{dateRanges:n}=e,s=Object.keys(n);let o=this.dateRangeCuesAppended;if(r&&t){var a;if((a=r.cues)!=null&&a.length){const u=Object.keys(o).filter(A=>!s.includes(A));for(let A=u.length;A--;){const h=u[A],d=o[h].cues;delete o[h],Object.keys(d).forEach(f=>{try{const g=d[f];g.removeEventListener("enter",this.onEventCueEnter),r.removeCue(g)}catch{}})}}else o=this.dateRangeCuesAppended={}}const c=e.fragments[e.fragments.length-1];if(s.length===0||!de(c==null?void 0:c.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Pc();for(let u=0;u<s.length;u++){const A=s[u],h=n[A],d=h.startTime,f=o[A],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1,v=jo;const{duration:B,endDate:C}=h;if(C&&B!==null)v=d+B,p=!0;else if(h.endOnNext&&!p){const x=s.reduce((_,D)=>{if(D!==h.id){const F=n[D];if(F.class===h.class&&F.startDate>h.startDate&&(!_||h.startDate<_.startDate))return F}return _},null);x&&(v=x.startTime,p=!0)}const y=Object.keys(h.attr);for(let x=0;x<y.length;x++){const _=y[x];if(!FB(_))continue;const D=g[_];if(D)p&&!f.durationKnown?D.endTime=v:Math.abs(D.startTime-d)>.01&&(D.startTime=d,D.endTime=v);else if(l){let F=h.attr[_];PB(_)&&(F=zb(F));const M=$g(l,d,v,{key:_,data:F},Yt.dateRange);M&&(M.id=A,this.id3Track.addCue(M),g[_]=M,this.hls.config.interstitialsController&&(_==="X-ASSET-LIST"||_==="X-ASSET-URL")&&M.addEventListener("enter",this.onEventCueEnter))}}o[A]={cues:g,dateRange:h,durationKnown:p}}}}class eS{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:o}=this.config;if(!s||o===1||!r.live)return;const a=this.targetLatency;if(a===null)return;const c=n-a,l=Math.min(this.maxLatency,a+r.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const A=Math.min(2,Math.max(1,o)),h=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,d=Math.min(A,Math.max(1,h));this.changeMediaPlaybackRate(t,d)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,c=this.hls.userConfig;let l=a&&r||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=s!==void 0?s:o*n);const u=n;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const n=r.edge,s=e-t-this.edgeStalled,o=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(o,s),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(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.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(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.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===V.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class tS extends mc{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,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_LOADED,this.onManifestLoaded,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],s={},o={};let a=!1,c=!1,l=!1;t.levels.forEach(u=>{var A;const h=u.attrs;let{audioCodec:d,videoCodec:f}=u;d&&(u.audioCodec=d=Co(d,r)||void 0),((A=f)==null?void 0:A.indexOf("avc1"))===0&&(f=u.videoCodec=rB(f));const{width:g,height:p,unknownCodecs:v}=u;let B=v?v.length:0;if(v)for(let j=B;j--;){const X=v[j];this.isAudioSupported(X)?(u.audioCodec=d=d?`${d},${X}`:X,B--,Yr.audio[d.substring(0,4)]=2):this.isVideoSupported(X)&&(u.videoCodec=f=f?`${f},${X}`:X,B--,Yr.video[f.substring(0,4)]=2)}if(a||(a=!!(g&&p)),c||(c=!!f),l||(l=!!d),B||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:C,"FRAME-RATE":y,"HDCP-LEVEL":x,"PATHWAY-ID":_,RESOLUTION:D,"VIDEO-RANGE":F}=h,M=`${`${_||"."}-`}${u.bitrate}-${D}-${y}-${C}-${F}-${x}`;if(s[M])if(s[M].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const j=o[M]+=1;u.attrs["PATHWAY-ID"]=new Array(j+1).join(".");const X=this.createLevel(u);s[M]=X,n.push(X)}else s[M].addGroupId("audio",h.AUDIO),s[M].addGroupId("text",h.SUBTITLES);else{const j=this.createLevel(u);s[M]=j,o[M]=1,n.push(j)}}),this.filterAndSortMediaOptions(n,t,a,c,l)}createLevel(e){const t=new Wn(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(n.message),t.supportedResult=Dd(n,[])}return t}isAudioSupported(e){return Nl(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Nl(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,s){let o=[],a=[],c=e;if((r||n)&&s&&(c=c.filter(({videoCodec:p,videoRange:v,width:B,height:C})=>(!!p||!!(B&&C))&&lB(v))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let p="no level with compatible codecs found in manifest",v=p;t.levels.length&&(v=`one or more CODECS in variant not supported: ${it(t.levels.map(C=>C.attrs.CODECS).filter((C,y,x)=>x.indexOf(C)===y))}`,this.warn(v),p+=` (${v})`);const B=new Error(p);this.hls.trigger(I.ERROR,{type:Ie.MEDIA_ERROR,details:V.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:B,reason:v})}});return}t.audioTracks&&(o=t.audioTracks.filter(p=>!p.audioCodec||this.isAudioSupported(p.audioCodec)),Hg(o)),t.subtitles&&(a=t.subtitles,Hg(a));const l=c.slice(0);c.sort((p,v)=>{if(p.attrs["HDCP-LEVEL"]!==v.attrs["HDCP-LEVEL"])return(p.attrs["HDCP-LEVEL"]||"")>(v.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&p.height!==v.height)return p.height-v.height;if(p.frameRate!==v.frameRate)return p.frameRate-v.frameRate;if(p.videoRange!==v.videoRange)return To.indexOf(p.videoRange)-To.indexOf(v.videoRange);if(p.videoCodec!==v.videoCodec){const B=Qd(p.videoCodec),C=Qd(v.videoCodec);if(B!==C)return C-B}if(p.uri===v.uri&&p.codecSet!==v.codecSet){const B=yo(p.codecSet),C=yo(v.codecSet);if(B!==C)return C-B}return p.averageBitrate!==v.averageBitrate?p.averageBitrate-v.averageBitrate:0});let u=l[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==l.length)){for(let p=0;p<l.length;p++)if(l[p].pathwayId===c[0].pathwayId){u=l[p];break}}this._levels=c;for(let p=0;p<c.length;p++)if(c[p]===u){var A;this._firstLevel=p;const v=u.bitrate,B=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${v}`),((A=this.hls.userConfig)==null?void 0:A.abrEwmaDefaultEstimate)===void 0){const C=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);C>B&&B===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=C)}break}const h=s&&!n,d=this.hls.config,f=!!(d.audioStreamController&&d.audioTrackController),g={levels:c,audioTracks:o,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:f&&!h&&o.some(p=>!!p.url)};this.hls.trigger(I.MANIFEST_PARSED,g)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),A=e<0;if(this.hls.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.LEVEL_SWITCH_ERROR,level:e,fatal:A,error:u,reason:u.message}),A)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,r===e&&n&&s===a)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,c);const l=o.details;if(!l||l.live){const u=this.switchParams(o.uri,n==null?void 0:n.details,l);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===Me.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Ee.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(s=>!!r[s]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,o=t.levelInfo;if(!o){var a;this.warn(`Invalid level index ${n}`),(a=t.deliveryDirectives)!=null&&a.skip&&(s.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(r=t.deliveryDirectives)!=null&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],o=e.details,a=o==null?void 0:o.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(I.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((s,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));Cf(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(I.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Hg(i){const e={};i.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}function Yg(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vg(){if(!er())return!1;const e=Yg();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function iS(){if(!Vg())return!1;const i=er();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(Kn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(Kn(e,"audio"))))}function rS(){var i;const e=Yg();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const nS=100;class sS extends ic{constructor(e,t,r){super(e,t,r,"stream-controller",Ee.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,s=n?n.currentTime:null;if(s===null||!de(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const o=this.getFwdBufferInfoAtPos(n,s,Ee.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(nS),this.level=-1,!this.startFragRequested){let s=n.startLevel;s===-1&&(n.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=n.firstAutoLevel),n.nextLoadLevel=s,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Z.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Z.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Z.WAITING_LEVEL:{const{levels:t,level:r}=this,n=t==null?void 0:t[r],s=n==null?void 0:n.details;if(s&&(!s.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(s))break;this.state=Z.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Z.IDLE;break}break}case Z.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),r=this.retryDate;if(!r||t>=r||(e=this.media)!=null&&e.seeking){const{levels:n,level:s}=this,o=n==null?void 0:n[s];this.resetStartWhenNotLoaded(o||null),this.state=Z.IDLE}}break}this.state===Z.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[s]))return;const o=r[s],a=this.getMainFwdBufferInfo();if(a===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(a,c)){const g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(I.BUFFER_EOS,g),this.state=Z.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=o.details;if(!l||this.state===Z.WAITING_LEVEL||this.waitForLive(o)){this.level=s,this.state=Z.WAITING_LEVEL,this.startFragRequested=!1;return}const u=a.len,A=this.getMaxBufferLength(o.maxBitrate);if(u>=A)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&Ct(d)&&this.fragmentTracker.getState(d)!==It.OK){var f;const p=((f=this.backtrackFragment)!=null?f:d).sn-l.startSN,v=l.fragments[p-1];v&&d.cc===v.cc&&(d=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,h)){if(!d.gap){const p=this.audioOnly&&!this.altAudio?qe.AUDIO:qe.VIDEO,v=(p===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,Ee.MAIN)}d=this.getNextFragmentLoopLoading(d,l,a,Ee.MAIN,A)}d&&(d.initSegment&&!d.initSegment.data&&!this.bitrateTest&&(d=d.initSegment),this.loadFragment(d,o,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===It.NOT_LOADED||n===It.PARTIAL?Ct(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Ee.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<s.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,c=e[a],l=this.fragLastKbps;l&&this.fragCurrent?r=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:r=0}else r=0;const o=this.getBufferedFrag(t.currentTime+r);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const c=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,u=Math.max(o.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Z.KEY_LOADING:case Z.FRAG_LOADING:case Z.FRAG_LOADING_WAITING_RETRY:case Z.PARSING:case Z.PARSED:this.state=Z.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;ki(r,"playing",this.onMediaPlaying),ki(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(vi(r,"playing",this.onMediaPlaying),vi(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;t.levels.forEach(s=>{const o=s.audioCodec;o&&(r=r||o.indexOf("mp4a.40.2")!==-1,n=n||o.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=r&&n&&!rS(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Z.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=Z.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:s}=this,o=t.level,a=t.details,c=a.totalduration;if(!n){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${c}`);const l=t.levelInfo,u=this.fragCurrent;u&&(this.state===Z.FRAG_LOADING||this.state===Z.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let A=0;if(a.live||(r=l.details)!=null&&r.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;A=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,A),this.hls.trigger(I.LEVEL_UPDATED,{details:a,level:o}),this.state===Z.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Z.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=this.getLoadPosition(),o=e.fragmentStart,a=e.edge,c=s>=o-t.maxFragLookUpTolerance&&s<=a;if(n!==null&&r.duration>n&&(s<n||!c)){const l=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!c&&r.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),r.currentTime=n))}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const a=o[r.level];if(!a){this.warn(`Level ${r.level} not found on progress`);return}const c=a.details;if(!c){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const l=a.videoCodec,u=c.PTSKnown||!c.live,A=(t=r.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new tg(this.hls,Ee.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,g=f!==-1,p=new Yl(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),v=this.initPTS[r.cc];d.push(s,A,h,l,r,n,c.totalduration,u,p,v)}onAudioTrackSwitching(e,t){const r=this.hls,n=this.altAudio===2;if(So(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.fragmentTracker.removeAllFragments(),r.once(I.BUFFER_FLUSHED,()=>{var o;(o=this.hls)==null||o.trigger(I.AUDIO_TRACK_SWITCHED,t)}),r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(I.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=So(t.url,this.hls);if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,o=!1;for(const a in r){const c=r[a];if(c.id==="main"){if(s=a,n=c,a==="video"){const l=r[a];l&&(this.videoBuffer=l.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,s=r.type===Ee.MAIN;if(s){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Z.PARSED&&(this.state=Z.IDLE);return}const a=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Ct(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const o=this.media;o&&(!this._hasEnoughToStart&&Le.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;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.MAIN,t);break;case V.LEVEL_LOAD_ERROR:case V.LEVEL_LOAD_TIMEOUT:case V.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===Me.LEVEL&&(this.state=Z.IDLE);break;case V.BUFFER_ADD_CODEC_ERROR:case V.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case V.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case V.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Z.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==qe.AUDIO||!this.altAudio){const r=(t===qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,Ee.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&r&&(r+=n);const s=this.getLevelDetails(),o=Le.getBuffered(e),a=o.length?o.start(0):0,c=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);c>0&&(c<l||this.loadingParts&&c<2*((s==null?void 0:s.partTarget)||0))&&(this.log(`adjusting start position by ${c} to match buffer start`),r+=c,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${a}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(r=>{const{hls:n}=this,s=r==null?void 0:r.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Z.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=s.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(I.FRAG_LOADED,r),s.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const r=this.playlistType,{hls:n}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:c,part:l,level:u}=a,{video:A,text:h,id3:d,initSegment:f}=s,{details:g}=u,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=Z.PARSING,f){if(f!=null&&f.tracks){const C=c.initSegment||c;this._bufferInitSegment(u,f.tracks,C,o),n.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:r,tracks:f.tracks})}const v=f.initPTS,B=f.timescale;de(v)&&(this.initPTS[c.cc]={baseTime:v,timescale:B},n.trigger(I.INIT_PTS_FOUND,{frag:c,id:r,initPTS:v,timescale:B}))}if(A&&g){p&&A.type==="audiovideo"&&this.logMuxedErr(c);const v=g.fragments[c.sn-1-g.startSN],B=c.sn===g.startSN,C=!v||c.cc>v.cc;if(s.independent!==!1){const{startPTS:y,endPTS:x,startDTS:_,endDTS:D}=A;if(l)l.elementaryStreams[A.type]={startPTS:y,endPTS:x,startDTS:_,endDTS:D};else if(A.firstKeyFrame&&A.independent&&o.id===1&&!C&&(this.couldBacktrack=!0),A.dropped&&A.independent){const F=this.getMainFwdBufferInfo(),O=(F?F.end:this.getLoadPosition())+this.config.maxBufferHole,M=A.firstKeyFramePTS?A.firstKeyFramePTS:y;if(!B&&O<M-this.config.maxBufferHole&&!C){this.backtrack(c);return}else C&&(c.gap=!0);c.setElementaryStreamInfo(A.type,c.start,x,c.start,D,!0)}else B&&y-(g.appliedTimelineOffset||0)>Jo&&(c.gap=!0);c.setElementaryStreamInfo(A.type,y,x,_,D),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(A,c,l,o,B||C)}else if(B||C)c.gap=!0;else{this.backtrack(c);return}}if(p){const{startPTS:v,endPTS:B,startDTS:C,endDTS:y}=p;l&&(l.elementaryStreams[qe.AUDIO]={startPTS:v,endPTS:B,startDTS:C,endDTS:y}),c.setElementaryStreamInfo(qe.AUDIO,v,B,C,y),this.bufferFragmentData(p,c,l,o)}if(g&&d!=null&&(t=d.samples)!=null&&t.length){const v={id:r,frag:c,details:g,samples:d.samples};n.trigger(I.FRAG_PARSING_METADATA,v)}if(g&&h){const v={id:r,frag:c,details:g,samples:h.samples};n.trigger(I.FRAG_PARSING_USERDATA,v)}}logMuxedErr(e){this.warn(`${Ct(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==Z.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:s,video:o,audiovideo:a}=t;if(s){let l=Bo(s.codec,e.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const A=s.metadata;A&&"channelCount"in A&&(A.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),s.levelCodec=l,s.id=Ee.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${s.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=Ee.MAIN;const l=o.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${o.codec!==l?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(I.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const A=t[l].initSegment;A!=null&&A.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:l,data:A,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Ee.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=e==null?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Z.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Le.isBuffered(e,r)?t=this.getAppendedFrag(r):Le.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,s=t.level;(!n||t.sn!==n.sn||n.level!==s)&&(this.fragPlaying=t,this.hls.trigger(I.FRAG_CHANGED,{frag:t}),(!n||n.level!==s)&&this.hls.trigger(I.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return de(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(de(t)){const r=this.getLevelDetails(),n=this.currentFrag||(r?br(null,r.fragments,t):null);if(n){const s=n.programDateTime;if(s!==null){const o=s+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class oS{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[r].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=V.KEY_LOAD_ERROR,r,n,s){return new Ri({type:Ie.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:n}=e;for(let s=0;s<t.length;s++){const o=t[s];if(n<=o.cc&&(r==="initSegment"||o.sn==="initSegment"||r<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,l))}const o=s.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((r=a)!=null&&r.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});if((n=a)!=null&&n.keyLoadPromise){var c;switch((c=a.mediaKeySessionContext)==null?void 0:c.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(l=>(s.key=l.keyInfo.decryptdata.key,{frag:e,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,V.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const n=this.emeController.loadKey(r);if(n)return(e.keyLoadPromise=n.then(s=>(e.mediaKeySessionContext=s,r))).catch(s=>{throw e.keyLoadPromise=null,s})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=r.loader,s=new n(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((o,a)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(h,d,f,g)=>{const{frag:p,keyInfo:v,url:B}=f;if(!p.decryptdata||v!==this.keyUriToKeyInfo[B])return a(this.createKeyLoadError(p,V.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,v.loader=null,o({frag:p,keyInfo:v})},onError:(h,d,f,g)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),f,Ye({url:c.url,data:void 0},h)))},onTimeout:(h,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(h,d,f)=>{this.resetLoader(d),a(this.createKeyLoadError(t,V.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};s.load(c,u,A)})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[n],s&&s.destroy()}}function Kg(i){const{type:e}=i;switch(e){case Me.AUDIO_TRACK:return Ee.AUDIO;case Me.SUBTITLE_TRACK:return Ee.SUBTITLE;default:return Ee.MAIN}}function Nc(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class aS{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=r||n,o=new s(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Me.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:s,url:o,deliveryDirectives:a,levelInfo:c}=t;this.load({id:r,level:n,pathwayId:s,responseType:"text",type:Me.LEVEL,url:o,deliveryDirectives:a,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:o,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Me.AUDIO_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:o,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Me.SUBTITLE_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[Me.LEVEL];if(r){const n=r.context;n&&!t.levels.some(s=>s===n.levelOrTrack)&&(r.abort(),delete this.loaders[Me.LEVEL])}}load(e){var t;const r=this.hls.config;let n=this.getInternalLoader(e);if(n){const l=this.hls.logger,u=n.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let s;if(e.type===Me.MANIFEST?s=r.manifestLoadPolicy.default:s=We({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),de((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Me.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Me.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Me.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const u=l.partTarget,A=l.targetduration;if(u&&A){const h=Math.max(u*3,A*.8)*1e3;s=We({},s,{maxTimeToFirstByteMs:Math.min(h,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,s.maxTimeToFirstByteMs)})}}}const o=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(l,u,A,h)=>{const d=this.getInternalLoader(A);this.resetInternalLoader(A.type);const f=l.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,A,new Error("no EXTM3U delimiter"),h||null,u);return}u.parsing.start=performance.now(),mi.isMediaPlaylist(f)||A.type!==Me.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,A,h||null,d):this.handleMasterPlaylist(l,u,A,h)},onError:(l,u,A,h)=>{this.handleNetworkError(u,A,!1,l,h)},onTimeout:(l,u,A)=>{this.handleNetworkError(u,A,!0,void 0,l)}};n.load(e,a,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const s=this.hls,o=e.data,a=Nc(e,r),c=mi.parseMasterPlaylist(o,a);if(c.playlistParsingError){this.handleManifestParsingError(e,r,c.playlistParsingError,n,t);return}const{contentSteering:l,levels:u,sessionData:A,sessionKeys:h,startTimeOffset:d,variableList:f}=c;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=mi.parseMasterPlaylistMedia(o,a,c);g.length&&!g.some(C=>!C.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new st({}),bitrate:0,url:""})),s.trigger(I.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:p,captions:v,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:A,sessionKeys:h,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const o=this.hls,{id:a,level:c,type:l}=r,u=Nc(e,r),A=de(c)?c:de(a)?a:0,h=Kg(r),d=mi.parseLevelPlaylist(e.data,u,A,h,0,this.variableList);if(l===Me.MANIFEST){const f={attrs:new st({}),bitrate:0,details:d,name:"",url:u};d.requestScheduled=t.loading.start+Ef(d,0),o.trigger(I.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=d,this.handlePlaylistLoaded(d,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.MANIFEST_PARSING_ERROR,fatal:t.type===Me.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let o=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Me.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Me.AUDIO_TRACK||e.type===Me.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=V.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case Me.MANIFEST:c=r?V.MANIFEST_LOAD_TIMEOUT:V.MANIFEST_LOAD_ERROR,l=!0;break;case Me.LEVEL:c=r?V.LEVEL_LOAD_TIMEOUT:V.LEVEL_LOAD_ERROR,l=!1;break;case Me.AUDIO_TRACK:c=r?V.AUDIO_TRACK_LOAD_TIMEOUT:V.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Me.SUBTITLE_TRACK:c=r?V.SUBTITLE_TRACK_LOAD_TIMEOUT:V.SUBTITLE_LOAD_ERROR,l=!1;break}u&&this.resetInternalLoader(e.type);const A={type:Ie.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:s};if(n){const h=(t==null?void 0:t.url)||e.url;A.response=Ye({url:h,data:void 0},n)}this.hls.trigger(I.ERROR,A)}handlePlaylistLoaded(e,t,r,n,s,o){const a=this.hls,{type:c,level:l,id:u,groupId:A,deliveryDirectives:h}=n,d=Nc(t,n),f=Kg(n),g=typeof n.level=="number"&&f===Ee.MAIN?l:void 0;if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:v,reason:v.message,response:t,context:n,level:g,parent:f,networkDetails:s,stats:r});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!a.config.ignorePlaylistParsingErrors){a.trigger(I.ERROR,{type:Ie.NETWORK_ERROR,details:V.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:t,context:n,level:g,parent:f,networkDetails:s,stats:r});return}e.playlistParsingError=null}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Me.MANIFEST:case Me.LEVEL:a.trigger(I.LEVEL_LOADED,{details:e,levelInfo:n.levelOrTrack||a.levels[0],level:g||0,id:u||0,stats:r,networkDetails:s,deliveryDirectives:h,withoutMultiVariant:c===Me.MANIFEST});break;case Me.AUDIO_TRACK:a.trigger(I.AUDIO_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:u||0,groupId:A||"",stats:r,networkDetails:s,deliveryDirectives:h});break;case Me.SUBTITLE_TRACK:a.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,track:n.levelOrTrack,id:u||0,groupId:A||"",stats:r,networkDetails:s,deliveryDirectives:h});break}}}class Zt{static get version(){return Xn}static isMSESupported(){return Vg()}static isSupported(){return iS()}static getMediaSource(){return er()}static get Events(){return I}static get MetadataSchema(){return Yt}static get ErrorTypes(){return Ie}static get ErrorDetails(){return V}static get DefaultConfig(){return Zt.defaultConfig?Zt.defaultConfig:Hb}static set DefaultConfig(e){Zt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new nc,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=DC(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=Vb(Zt.DefaultConfig,e,t);this.userConfig=e,r.progressive&&Kb(r,t);const{abrController:n,bufferController:s,capLevelController:o,errorController:a,fpsController:c}=r,l=new a(this),u=this.abrController=new n(this),A=new TB(this),h=r.interstitialsController,d=h?this.interstitialsController=new h(this,Zt):null,f=this.bufferController=new s(this,A),g=this.capLevelController=new o(this),p=new c(this),v=new aS(this),B=r.contentSteeringController,C=B?new B(this):null,y=this.levelController=new tS(this,C),x=new Zb(this),_=new oS(this.config),D=this.streamController=new sS(this,A,_),F=this.gapController=new jb(this,A);g.setStreamController(D),p.setStreamController(D);const O=[v,y,D];d&&O.splice(1,0,d),C&&O.splice(1,0,C),this.networkControllers=O;const M=[u,f,F,g,p,x,A];this.audioTrackController=this.createController(r.audioTrackController,O);const j=r.audioStreamController;j&&O.push(this.audioStreamController=new j(this,A,_)),this.subtitleTrackController=this.createController(r.subtitleTrackController,O);const X=r.subtitleStreamController;X&&O.push(this.subtititleStreamController=new X(this,A,_)),this.createController(r.timelineController,M),_.emeController=this.emeController=this.createController(r.emeController,M),this.cmcdController=this.createController(r.cmcdController,M),this.latencyController=this.createController(eS,M),this.coreComponents=M,O.push(l);const le=l.onErrorOut;typeof le=="function"&&this.on(I.ERROR,le,l),this.on(I.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const n=e===I.ERROR;this.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.INTERNAL_EXCEPTION,fatal:n,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const s=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(I.ERROR,{type:Ie.OTHER_ERROR,details:V.ATTACH_MEDIA_ERROR,fatal:!0,error:s});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,n=t?e:{media:r};this._media=r,this.trigger(I.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(I.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,n=this._url=Dl.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(I.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Ee.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Ee.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Ee.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=CT()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){aB(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,r)for(let s=n;s--;){const o=e[s].attrs["HDCP-LEVEL"];if(o&&o<=r)return s}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const r=Nd(t);return kd(e,r,navigator.mediaCapabilities)}}Zt.defaultConfig=void 0;function lS(i){return i&&i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function cS(i){return i}function AS(i,e){e=e||{};const t=e.delimiter||".",r=e.maxDepth,n=e.transformKey||cS,s={};function o(a,c,l){l=l||1,Object.keys(a).forEach(function(u){const A=a[u],h=e.safe&&Array.isArray(A),d=Object.prototype.toString.call(A),f=lS(A),g=d==="[object Object]"||d==="[object Array]",p=c?c+t+n(u):n(u);if(!h&&!f&&g&&Object.keys(A).length&&(!e.maxDepth||l<r))return o(A,p,l+1);s[p]=A})}return o(i),s}var Wg=Number.isNaN||function(e){return typeof e=="number"&&e!==e};function uS(i,e){return!!(i===e||Wg(i)&&Wg(e))}function hS(i,e){if(i.length!==e.length)return!1;for(var t=0;t<i.length;t++)if(!uS(i[t],e[t]))return!1;return!0}function dS(i,e){e===void 0&&(e=hS);var t=null;function r(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];if(t&&t.lastThis===this&&e(n,t.lastArgs))return t.lastResult;var o=i.apply(this,n);return t={lastResult:o,lastArgs:n,lastThis:this},o}return r.clear=function(){t=null},r}/**
2525
2525
  * @license
2526
2526
  * Copyright 2017 Google LLC
2527
2527
  * SPDX-License-Identifier: BSD-3-Clause
2528
- */const qg=(i,e,t)=>{const r=new Map;for(let n=e;n<=t;n++)r.set(i[n],n);return r},Jg=Or(class extends xn{constructor(i){if(super(i),i.type!==Nr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(i,e,t){let r;t===void 0?t=e:e!==void 0&&(r=e);const n=[],s=[];let o=0;for(const a of i)n[o]=r?r(a,o):o,s[o]=t(a,o),o++;return{values:s,keys:n}}render(i,e,t){return this.dt(i,e,t).values}update(i,[e,t,r]){const n=Hp(i),{values:s,keys:o}=this.dt(e,t,r);if(!Array.isArray(n))return this.ut=o,s;const a=this.ut??(this.ut=[]),c=[];let l,u,A=0,h=n.length-1,d=0,f=s.length-1;for(;A<=h&&d<=f;)if(n[A]===null)A++;else if(n[h]===null)h--;else if(a[A]===o[d])c[d]=mr(n[A],s[d]),A++,d++;else if(a[h]===o[f])c[f]=mr(n[h],s[f]),h--,f--;else if(a[A]===o[f])c[f]=mr(n[A],s[f]),Sn(i,c[f+1],n[A]),A++,f--;else if(a[h]===o[d])c[d]=mr(n[h],s[d]),Sn(i,n[A],n[h]),h--,d++;else if(l===void 0&&(l=qg(o,d,f),u=qg(a,A,h)),l.has(a[A]))if(l.has(a[h])){const g=u.get(o[d]),p=g!==void 0?n[g]:null;if(p===null){const v=Sn(i,n[A]);mr(v,s[d]),c[d]=v}else c[d]=mr(p,s[d]),Sn(i,n[A],p),n[g]=null;d++}else wa(n[h]),h--;else wa(n[A]),A++;for(;d<=f;){const g=Sn(i,c[f+1]);mr(g,s[d]),c[d++]=g}for(;A<=h;){const g=n[A++];g!==null&&wa(g)}return this.ut=o,$p(i,c),$i}});var Ut="top",Zt="bottom",ei="right",Gt="left",Oc="auto",ss=[Ut,Zt,ei,Gt],en="start",os="end",fS="clippingParents",jg="viewport",as="popper",gS="reference",Xg=ss.reduce(function(i,e){return i.concat([e+"-"+en,e+"-"+os])},[]),zg=[].concat(ss,[Oc]).reduce(function(i,e){return i.concat([e,e+"-"+en,e+"-"+os])},[]),pS="beforeRead",mS="read",ES="afterRead",IS="beforeMain",vS="main",yS="afterMain",CS="beforeWrite",BS="write",TS="afterWrite",bS=[pS,mS,ES,IS,vS,yS,CS,BS,TS];function yi(i){return i?(i.nodeName||"").toLowerCase():null}function Vt(i){if(i==null)return window;if(i.toString()!=="[object Window]"){var e=i.ownerDocument;return e&&e.defaultView||window}return i}function xr(i){var e=Vt(i).Element;return i instanceof e||i instanceof Element}function ti(i){var e=Vt(i).HTMLElement;return i instanceof e||i instanceof HTMLElement}function Uc(i){if(typeof ShadowRoot>"u")return!1;var e=Vt(i).ShadowRoot;return i instanceof e||i instanceof ShadowRoot}function SS(i){var e=i.state;Object.keys(e.elements).forEach(function(t){var r=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];!ti(s)||!yi(s)||(Object.assign(s.style,r),Object.keys(n).forEach(function(o){var a=n[o];a===!1?s.removeAttribute(o):s.setAttribute(o,a===!0?"":a)}))})}function xS(i){var e=i.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(r){var n=e.elements[r],s=e.attributes[r]||{},o=Object.keys(e.styles.hasOwnProperty(r)?e.styles[r]:t[r]),a=o.reduce(function(c,l){return c[l]="",c},{});!ti(n)||!yi(n)||(Object.assign(n.style,a),Object.keys(s).forEach(function(c){n.removeAttribute(c)}))})}}const Zg={name:"applyStyles",enabled:!0,phase:"write",fn:SS,effect:xS,requires:["computeStyles"]};function Ci(i){return i.split("-")[0]}var Qr=Math.max,Xo=Math.min,tn=Math.round;function Gc(){var i=navigator.userAgentData;return i!=null&&i.brands&&Array.isArray(i.brands)?i.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function e0(){return!/^((?!chrome|android).)*safari/i.test(Gc())}function rn(i,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var r=i.getBoundingClientRect(),n=1,s=1;e&&ti(i)&&(n=i.offsetWidth>0&&tn(r.width)/i.offsetWidth||1,s=i.offsetHeight>0&&tn(r.height)/i.offsetHeight||1);var o=xr(i)?Vt(i):window,a=o.visualViewport,c=!e0()&&t,l=(r.left+(c&&a?a.offsetLeft:0))/n,u=(r.top+(c&&a?a.offsetTop:0))/s,A=r.width/n,h=r.height/s;return{width:A,height:h,top:u,right:l+A,bottom:u+h,left:l,x:l,y:u}}function $c(i){var e=rn(i),t=i.offsetWidth,r=i.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-r)<=1&&(r=e.height),{x:i.offsetLeft,y:i.offsetTop,width:t,height:r}}function t0(i,e){var t=e.getRootNode&&e.getRootNode();if(i.contains(e))return!0;if(t&&Uc(t)){var r=e;do{if(r&&i.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function Fi(i){return Vt(i).getComputedStyle(i)}function QS(i){return["table","td","th"].indexOf(yi(i))>=0}function sr(i){return((xr(i)?i.ownerDocument:i.document)||window.document).documentElement}function zo(i){return yi(i)==="html"?i:i.assignedSlot||i.parentNode||(Uc(i)?i.host:null)||sr(i)}function i0(i){return!ti(i)||Fi(i).position==="fixed"?null:i.offsetParent}function wS(i){var e=/firefox/i.test(Gc()),t=/Trident/i.test(Gc());if(t&&ti(i)){var r=Fi(i);if(r.position==="fixed")return null}var n=zo(i);for(Uc(n)&&(n=n.host);ti(n)&&["html","body"].indexOf(yi(n))<0;){var s=Fi(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 ls(i){for(var e=Vt(i),t=i0(i);t&&QS(t)&&Fi(t).position==="static";)t=i0(t);return t&&(yi(t)==="html"||yi(t)==="body"&&Fi(t).position==="static")?e:t||wS(i)||e}function Hc(i){return["top","bottom"].indexOf(i)>=0?"x":"y"}function cs(i,e,t){return Qr(i,Xo(e,t))}function _S(i,e,t){var r=cs(i,e,t);return r>t?t:r}function r0(){return{top:0,right:0,bottom:0,left:0}}function n0(i){return Object.assign({},r0(),i)}function s0(i,e){return e.reduce(function(t,r){return t[r]=i,t},{})}var RS=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,n0(typeof e!="number"?e:s0(e,ss))};function DS(i){var e,t=i.state,r=i.name,n=i.options,s=t.elements.arrow,o=t.modifiersData.popperOffsets,a=Ci(t.placement),c=Hc(a),l=[Gt,ei].indexOf(a)>=0,u=l?"height":"width";if(!(!s||!o)){var A=RS(n.padding,t),h=$c(s),d=c==="y"?Ut:Gt,f=c==="y"?Zt:ei,g=t.rects.reference[u]+t.rects.reference[c]-o[c]-t.rects.popper[u],p=o[c]-t.rects.reference[c],v=ls(s),B=v?c==="y"?v.clientHeight||0:v.clientWidth||0:0,C=g/2-p/2,y=A[d],x=B-h[u]-A[f],_=B/2-h[u]/2+C,D=cs(y,_,x),F=c;t.modifiersData[r]=(e={},e[F]=D,e.centerOffset=D-_,e)}}function LS(i){var e=i.state,t=i.options,r=t.element,n=r===void 0?"[data-popper-arrow]":r;n!=null&&(typeof n=="string"&&(n=e.elements.popper.querySelector(n),!n)||t0(e.elements.popper,n)&&(e.elements.arrow=n))}const kS={name:"arrow",enabled:!0,phase:"main",fn:DS,effect:LS,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function nn(i){return i.split("-")[1]}var MS={top:"auto",right:"auto",bottom:"auto",left:"auto"};function FS(i,e){var t=i.x,r=i.y,n=e.devicePixelRatio||1;return{x:tn(t*n)/n||0,y:tn(r*n)/n||0}}function o0(i){var e,t=i.popper,r=i.popperRect,n=i.placement,s=i.variation,o=i.offsets,a=i.position,c=i.gpuAcceleration,l=i.adaptive,u=i.roundOffsets,A=i.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=Gt,y=Ut,x=window;if(l){var _=ls(t),D="clientHeight",F="clientWidth";if(_===Vt(t)&&(_=sr(t),Fi(_).position!=="static"&&a==="absolute"&&(D="scrollHeight",F="scrollWidth")),_=_,n===Ut||(n===Gt||n===ei)&&s===os){y=Zt;var O=A&&_===x&&x.visualViewport?x.visualViewport.height:_[D];g-=O-r.height,g*=c?1:-1}if(n===Gt||(n===Ut||n===Zt)&&s===os){C=ei;var M=A&&_===x&&x.visualViewport?x.visualViewport.width:_[F];d-=M-r.width,d*=c?1:-1}}var j=Object.assign({position:a},l&&MS),X=u===!0?FS({x:d,y:g},Vt(t)):{x:d,y:g};if(d=X.x,g=X.y,c){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 PS(i){var e=i.state,t=i.options,r=t.gpuAcceleration,n=r===void 0?!0:r,s=t.adaptive,o=s===void 0?!0:s,a=t.roundOffsets,c=a===void 0?!0:a,l={placement:Ci(e.placement),variation:nn(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,o0(Object.assign({},l,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:c})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,o0(Object.assign({},l,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:c})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const NS={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:PS,data:{}};var Zo={passive:!0};function OS(i){var e=i.state,t=i.instance,r=i.options,n=r.scroll,s=n===void 0?!0:n,o=r.resize,a=o===void 0?!0:o,c=Vt(e.elements.popper),l=[].concat(e.scrollParents.reference,e.scrollParents.popper);return s&&l.forEach(function(u){u.addEventListener("scroll",t.update,Zo)}),a&&c.addEventListener("resize",t.update,Zo),function(){s&&l.forEach(function(u){u.removeEventListener("scroll",t.update,Zo)}),a&&c.removeEventListener("resize",t.update,Zo)}}const US={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:OS,data:{}};var GS={left:"right",right:"left",bottom:"top",top:"bottom"};function ea(i){return i.replace(/left|right|bottom|top/g,function(e){return GS[e]})}var $S={start:"end",end:"start"};function a0(i){return i.replace(/start|end/g,function(e){return $S[e]})}function Yc(i){var e=Vt(i),t=e.pageXOffset,r=e.pageYOffset;return{scrollLeft:t,scrollTop:r}}function Vc(i){return rn(sr(i)).left+Yc(i).scrollLeft}function HS(i,e){var t=Vt(i),r=sr(i),n=t.visualViewport,s=r.clientWidth,o=r.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;var l=e0();(l||!l&&e==="fixed")&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a+Vc(i),y:c}}function YS(i){var e,t=sr(i),r=Yc(i),n=(e=i.ownerDocument)==null?void 0:e.body,s=Qr(t.scrollWidth,t.clientWidth,n?n.scrollWidth:0,n?n.clientWidth:0),o=Qr(t.scrollHeight,t.clientHeight,n?n.scrollHeight:0,n?n.clientHeight:0),a=-r.scrollLeft+Vc(i),c=-r.scrollTop;return Fi(n||t).direction==="rtl"&&(a+=Qr(t.clientWidth,n?n.clientWidth:0)-s),{width:s,height:o,x:a,y:c}}function Kc(i){var e=Fi(i),t=e.overflow,r=e.overflowX,n=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+n+r)}function l0(i){return["html","body","#document"].indexOf(yi(i))>=0?i.ownerDocument.body:ti(i)&&Kc(i)?i:l0(zo(i))}function As(i,e){var t;e===void 0&&(e=[]);var r=l0(i),n=r===((t=i.ownerDocument)==null?void 0:t.body),s=Vt(r),o=n?[s].concat(s.visualViewport||[],Kc(r)?r:[]):r,a=e.concat(o);return n?a:a.concat(As(zo(o)))}function Wc(i){return Object.assign({},i,{left:i.x,top:i.y,right:i.x+i.width,bottom:i.y+i.height})}function VS(i,e){var t=rn(i,!1,e==="fixed");return t.top=t.top+i.clientTop,t.left=t.left+i.clientLeft,t.bottom=t.top+i.clientHeight,t.right=t.left+i.clientWidth,t.width=i.clientWidth,t.height=i.clientHeight,t.x=t.left,t.y=t.top,t}function c0(i,e,t){return e===jg?Wc(HS(i,t)):xr(e)?VS(e,t):Wc(YS(sr(i)))}function KS(i){var e=As(zo(i)),t=["absolute","fixed"].indexOf(Fi(i).position)>=0,r=t&&ti(i)?ls(i):i;return xr(r)?e.filter(function(n){return xr(n)&&t0(n,r)&&yi(n)!=="body"}):[]}function WS(i,e,t,r){var n=e==="clippingParents"?KS(i):[].concat(e),s=[].concat(n,[t]),o=s[0],a=s.reduce(function(c,l){var u=c0(i,l,r);return c.top=Qr(u.top,c.top),c.right=Xo(u.right,c.right),c.bottom=Xo(u.bottom,c.bottom),c.left=Qr(u.left,c.left),c},c0(i,o,r));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function A0(i){var e=i.reference,t=i.element,r=i.placement,n=r?Ci(r):null,s=r?nn(r):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,c;switch(n){case Ut:c={x:o,y:e.y-t.height};break;case Zt:c={x:o,y:e.y+e.height};break;case ei:c={x:e.x+e.width,y:a};break;case Gt:c={x:e.x-t.width,y:a};break;default:c={x:e.x,y:e.y}}var l=n?Hc(n):null;if(l!=null){var u=l==="y"?"height":"width";switch(s){case en:c[l]=c[l]-(e[u]/2-t[u]/2);break;case os:c[l]=c[l]+(e[u]/2-t[u]/2);break}}return c}function us(i,e){e===void 0&&(e={});var t=e,r=t.placement,n=r===void 0?i.placement:r,s=t.strategy,o=s===void 0?i.strategy:s,a=t.boundary,c=a===void 0?fS:a,l=t.rootBoundary,u=l===void 0?jg:l,A=t.elementContext,h=A===void 0?as:A,d=t.altBoundary,f=d===void 0?!1:d,g=t.padding,p=g===void 0?0:g,v=n0(typeof p!="number"?p:s0(p,ss)),B=h===as?gS:as,C=i.rects.popper,y=i.elements[f?B:h],x=WS(xr(y)?y:y.contextElement||sr(i.elements.popper),c,u,o),_=rn(i.elements.reference),D=A0({reference:_,element:C,placement:n}),F=Wc(Object.assign({},C,D)),O=h===as?F:_,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=i.modifiersData.offset;if(h===as&&j){var X=j[n];Object.keys(M).forEach(function(le){var oe=[ei,Zt].indexOf(le)>=0?1:-1,L=[Ut,Zt].indexOf(le)>=0?"y":"x";M[le]+=X[L]*oe})}return M}function qS(i,e){e===void 0&&(e={});var t=e,r=t.placement,n=t.boundary,s=t.rootBoundary,o=t.padding,a=t.flipVariations,c=t.allowedAutoPlacements,l=c===void 0?zg:c,u=nn(r),A=u?a?Xg:Xg.filter(function(f){return nn(f)===u}):ss,h=A.filter(function(f){return l.indexOf(f)>=0});h.length===0&&(h=A);var d=h.reduce(function(f,g){return f[g]=us(i,{placement:g,boundary:n,rootBoundary:s,padding:o})[Ci(g)],f},{});return Object.keys(d).sort(function(f,g){return d[f]-d[g]})}function JS(i){if(Ci(i)===Oc)return[];var e=ea(i);return[a0(i),e,a0(e)]}function jS(i){var e=i.state,t=i.options,r=i.name;if(!e.modifiersData[r]._skip){for(var n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!0:o,c=t.fallbackPlacements,l=t.padding,u=t.boundary,A=t.rootBoundary,h=t.altBoundary,d=t.flipVariations,f=d===void 0?!0:d,g=t.allowedAutoPlacements,p=e.options.placement,v=Ci(p),B=v===p,C=c||(B||!f?[ea(p)]:JS(p)),y=[p].concat(C).reduce(function(re,he){return re.concat(Ci(he)===Oc?qS(e,{placement:he,boundary:u,rootBoundary:A,padding:l,flipVariations:f,allowedAutoPlacements:g}):he)},[]),x=e.rects.reference,_=e.rects.popper,D=new Map,F=!0,O=y[0],M=0;M<y.length;M++){var j=y[M],X=Ci(j),le=nn(j)===en,oe=[Ut,Zt].indexOf(X)>=0,L=oe?"width":"height",U=us(e,{placement:j,boundary:u,rootBoundary:A,altBoundary:h,padding:l}),q=oe?le?ei:Gt:le?Zt:Ut;x[L]>_[L]&&(q=ea(q));var R=ea(q),w=[];if(s&&w.push(U[X]<=0),a&&w.push(U[q]<=0,U[R]<=0),w.every(function(re){return re})){O=j,F=!1;break}D.set(j,w)}if(F)for(var k=f?3:1,K=function(he){var fe=y.find(function(we){var be=D.get(we);if(be)return be.slice(0,he).every(function(Fe){return Fe})});if(fe)return O=fe,"break"},Y=k;Y>0;Y--){var ie=K(Y);if(ie==="break")break}e.placement!==O&&(e.modifiersData[r]._skip=!0,e.placement=O,e.reset=!0)}}const XS={name:"flip",enabled:!0,phase:"main",fn:jS,requiresIfExists:["offset"],data:{_skip:!1}};function u0(i,e,t){return t===void 0&&(t={x:0,y:0}),{top:i.top-e.height-t.y,right:i.right-e.width+t.x,bottom:i.bottom-e.height+t.y,left:i.left-e.width-t.x}}function h0(i){return[Ut,ei,Zt,Gt].some(function(e){return i[e]>=0})}function zS(i){var e=i.state,t=i.name,r=e.rects.reference,n=e.rects.popper,s=e.modifiersData.preventOverflow,o=us(e,{elementContext:"reference"}),a=us(e,{altBoundary:!0}),c=u0(o,r),l=u0(a,n,s),u=h0(c),A=h0(l);e.modifiersData[t]={referenceClippingOffsets:c,popperEscapeOffsets:l,isReferenceHidden:u,hasPopperEscaped:A},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":A})}const ZS={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:zS};function ex(i,e,t){var r=Ci(i),n=[Gt,Ut].indexOf(r)>=0?-1:1,s=typeof t=="function"?t(Object.assign({},e,{placement:i})):t,o=s[0],a=s[1];return o=o||0,a=(a||0)*n,[Gt,ei].indexOf(r)>=0?{x:a,y:o}:{x:o,y:a}}function tx(i){var e=i.state,t=i.options,r=i.name,n=t.offset,s=n===void 0?[0,0]:n,o=zg.reduce(function(u,A){return u[A]=ex(A,e.rects,s),u},{}),a=o[e.placement],c=a.x,l=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=c,e.modifiersData.popperOffsets.y+=l),e.modifiersData[r]=o}const ix={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:tx};function rx(i){var e=i.state,t=i.name;e.modifiersData[t]=A0({reference:e.rects.reference,element:e.rects.popper,placement:e.placement})}const nx={name:"popperOffsets",enabled:!0,phase:"read",fn:rx,data:{}};function sx(i){return i==="x"?"y":"x"}function ox(i){var e=i.state,t=i.options,r=i.name,n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!1:o,c=t.boundary,l=t.rootBoundary,u=t.altBoundary,A=t.padding,h=t.tether,d=h===void 0?!0:h,f=t.tetherOffset,g=f===void 0?0:f,p=us(e,{boundary:c,rootBoundary:l,padding:A,altBoundary:u}),v=Ci(e.placement),B=nn(e.placement),C=!B,y=Hc(v),x=sx(y),_=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(_){if(s){var le,oe=y==="y"?Ut:Gt,L=y==="y"?Zt:ei,U=y==="y"?"height":"width",q=_[y],R=q+p[oe],w=q-p[L],k=d?-F[U]/2:0,K=B===en?D[U]:F[U],Y=B===en?-F[U]:-D[U],ie=e.elements.arrow,re=d&&ie?$c(ie):{width:0,height:0},he=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:r0(),fe=he[oe],we=he[L],be=cs(0,D[U],re[U]),Fe=C?D[U]/2-k-be-fe-M.mainAxis:K-be-fe-M.mainAxis,pe=C?-D[U]/2+k+be+we+M.mainAxis:Y+be+we+M.mainAxis,Qe=e.elements.arrow&&ls(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=cs(d?Xo(R,Ke):R,q,d?Qr(w,Se):w);_[y]=ye,X[y]=ye-q}if(a){var ke,Ue=y==="x"?Ut:Gt,Xe=y==="x"?Zt:ei,Ge=_[x],$e=x==="y"?"height":"width",Ce=Ge+p[Ue],tt=Ge-p[Xe],ot=[Ut,Gt].indexOf(v)!==-1,et=(ke=j==null?void 0:j[x])!=null?ke:0,ze=ot?Ce:Ge-D[$e]-F[$e]-et+M.altAxis,T=ot?Ge+D[$e]+F[$e]-et-M.altAxis:tt,m=d&&ot?_S(ze,Ge,T):cs(d?ze:Ce,Ge,d?T:tt);_[x]=m,X[x]=m-Ge}e.modifiersData[r]=X}}const ax={name:"preventOverflow",enabled:!0,phase:"main",fn:ox,requiresIfExists:["offset"]};function lx(i){return{scrollLeft:i.scrollLeft,scrollTop:i.scrollTop}}function cx(i){return i===Vt(i)||!ti(i)?Yc(i):lx(i)}function Ax(i){var e=i.getBoundingClientRect(),t=tn(e.width)/i.offsetWidth||1,r=tn(e.height)/i.offsetHeight||1;return t!==1||r!==1}function ux(i,e,t){t===void 0&&(t=!1);var r=ti(e),n=ti(e)&&Ax(e),s=sr(e),o=rn(i,n,t),a={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(r||!r&&!t)&&((yi(e)!=="body"||Kc(s))&&(a=cx(e)),ti(e)?(c=rn(e,!0),c.x+=e.clientLeft,c.y+=e.clientTop):s&&(c.x=Vc(s))),{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function hx(i){var e=new Map,t=new Set,r=[];i.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 c=e.get(a);c&&n(c)}}),r.push(s)}return i.forEach(function(s){t.has(s.name)||n(s)}),r}function dx(i){var e=hx(i);return bS.reduce(function(t,r){return t.concat(e.filter(function(n){return n.phase===r}))},[])}function fx(i){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(i())})})),e}}function gx(i){var e=i.reduce(function(t,r){var n=t[r.name];return t[r.name]=n?Object.assign({},n,r,{options:Object.assign({},n.options,r.options),data:Object.assign({},n.data,r.data)}):r,t},{});return Object.keys(e).map(function(t){return e[t]})}var d0={placement:"bottom",modifiers:[],strategy:"absolute"};function f0(){for(var i=arguments.length,e=new Array(i),t=0;t<i;t++)e[t]=arguments[t];return!e.some(function(r){return!(r&&typeof r.getBoundingClientRect=="function")})}function px(i){i===void 0&&(i={});var e=i,t=e.defaultModifiers,r=t===void 0?[]:t,n=e.defaultOptions,s=n===void 0?d0:n;return function(a,c,l){l===void 0&&(l=s);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},d0,s),modifiersData:{},elements:{reference:a,popper:c},attributes:{},styles:{}},A=[],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:xr(a)?As(a):a.contextElement?As(a.contextElement):[],popper:As(c)};var C=dx(gx([].concat(r,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(f0(B,C)){u.rects={reference:ux(B,ls(C),u.options.strategy==="fixed"),popper:$c(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],_=x.fn,D=x.options,F=D===void 0?{}:D,O=x.name;typeof _=="function"&&(u=_({state:u,options:F,name:O,instance:d})||u)}}}},update:fx(function(){return new Promise(function(p){d.forceUpdate(),p(u)})}),destroy:function(){g(),h=!0}};if(!f0(a,c))return d;d.setOptions(l).then(function(p){!h&&l.onFirstUpdate&&l.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}),_=function(){};A.push(x||_)}})}function g(){A.forEach(function(p){return p()}),A=[]}return d}}var mx=[US,nx,NS,Zg,ix,XS,ax,kS,ZS],Ex=px({defaultModifiers:mx}),Ix="tippy-box",g0="tippy-content",vx="tippy-backdrop",p0="tippy-arrow",m0="tippy-svg-arrow",wr={passive:!0,capture:!0},E0=function(){return document.body};function qc(i,e,t){if(Array.isArray(i)){var r=i[e];return r??(Array.isArray(t)?t[e]:t)}return i}function Jc(i,e){var t={}.toString.call(i);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function I0(i,e){return typeof i=="function"?i.apply(void 0,e):i}function v0(i,e){if(e===0)return i;var t;return function(r){clearTimeout(t),t=setTimeout(function(){i(r)},e)}}function yx(i){return i.split(/\s+/).filter(Boolean)}function sn(i){return[].concat(i)}function y0(i,e){i.indexOf(e)===-1&&i.push(e)}function Cx(i){return i.filter(function(e,t){return i.indexOf(e)===t})}function Bx(i){return i.split("-")[0]}function ta(i){return[].slice.call(i)}function C0(i){return Object.keys(i).reduce(function(e,t){return i[t]!==void 0&&(e[t]=i[t]),e},{})}function hs(){return document.createElement("div")}function ia(i){return["Element","Fragment"].some(function(e){return Jc(i,e)})}function Tx(i){return Jc(i,"NodeList")}function bx(i){return Jc(i,"MouseEvent")}function Sx(i){return!!(i&&i._tippy&&i._tippy.reference===i)}function xx(i){return ia(i)?[i]:Tx(i)?ta(i):Array.isArray(i)?i:ta(document.querySelectorAll(i))}function jc(i,e){i.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function B0(i,e){i.forEach(function(t){t&&t.setAttribute("data-state",e)})}function Qx(i){var e,t=sn(i),r=t[0];return r!=null&&(e=r.ownerDocument)!=null&&e.body?r.ownerDocument:document}function wx(i,e){var t=e.clientX,r=e.clientY;return i.every(function(n){var s=n.popperRect,o=n.popperState,a=n.props,c=a.interactiveBorder,l=Bx(o.placement),u=o.modifiersData.offset;if(!u)return!0;var A=l==="bottom"?u.top.y:0,h=l==="top"?u.bottom.y:0,d=l==="right"?u.left.x:0,f=l==="left"?u.right.x:0,g=s.top-r+A>c,p=r-s.bottom-h>c,v=s.left-t+d>c,B=t-s.right-f>c;return g||p||v||B})}function Xc(i,e,t){var r=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(n){i[r](n,t)})}function T0(i,e){for(var t=e;t;){var r;if(i.contains(t))return!0;t=t.getRootNode==null||(r=t.getRootNode())==null?void 0:r.host}return!1}var Bi={isTouch:!1},b0=0;function _x(){Bi.isTouch||(Bi.isTouch=!0,window.performance&&document.addEventListener("mousemove",S0))}function S0(){var i=performance.now();i-b0<20&&(Bi.isTouch=!1,document.removeEventListener("mousemove",S0)),b0=i}function Rx(){var i=document.activeElement;if(Sx(i)){var e=i._tippy;i.blur&&!e.state.isVisible&&i.blur()}}function Dx(){document.addEventListener("touchstart",_x,wr),window.addEventListener("blur",Rx)}var Lx=typeof window<"u"&&typeof document<"u",kx=Lx?!!window.msCrypto:!1,Mx={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Fx={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},li=Object.assign({appendTo:E0,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},Mx,Fx),Px=Object.keys(li),Nx=function(e){var t=Object.keys(e);t.forEach(function(r){li[r]=e[r]})};function x0(i){var e=i.plugins||[],t=e.reduce(function(r,n){var s=n.name,o=n.defaultValue;if(s){var a;r[s]=i[s]!==void 0?i[s]:(a=li[s])!=null?a:o}return r},{});return Object.assign({},i,t)}function Ox(i,e){var t=e?Object.keys(x0(Object.assign({},li,{plugins:e}))):Px,r=t.reduce(function(n,s){var o=(i.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 r}function Q0(i,e){var t=Object.assign({},e,{content:I0(e.content,[i])},e.ignoreAttributes?{}:Ox(i,e.plugins));return t.aria=Object.assign({},li.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 Ux=function(){return"innerHTML"};function zc(i,e){i[Ux()]=e}function w0(i){var e=hs();return i===!0?e.className=p0:(e.className=m0,ia(i)?e.appendChild(i):zc(e,i)),e}function _0(i,e){ia(e.content)?(zc(i,""),i.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?zc(i,e.content):i.textContent=e.content)}function Zc(i){var e=i.firstElementChild,t=ta(e.children);return{box:e,content:t.find(function(r){return r.classList.contains(g0)}),arrow:t.find(function(r){return r.classList.contains(p0)||r.classList.contains(m0)}),backdrop:t.find(function(r){return r.classList.contains(vx)})}}function R0(i){var e=hs(),t=hs();t.className=Ix,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var r=hs();r.className=g0,r.setAttribute("data-state","hidden"),_0(r,i.props),e.appendChild(t),t.appendChild(r),n(i.props,i.props);function n(s,o){var a=Zc(e),c=a.box,l=a.content,u=a.arrow;o.theme?c.setAttribute("data-theme",o.theme):c.removeAttribute("data-theme"),typeof o.animation=="string"?c.setAttribute("data-animation",o.animation):c.removeAttribute("data-animation"),o.inertia?c.setAttribute("data-inertia",""):c.removeAttribute("data-inertia"),c.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?c.setAttribute("role",o.role):c.removeAttribute("role"),(s.content!==o.content||s.allowHTML!==o.allowHTML)&&_0(l,i.props),o.arrow?u?s.arrow!==o.arrow&&(c.removeChild(u),c.appendChild(w0(o.arrow))):c.appendChild(w0(o.arrow)):u&&c.removeChild(u)}return{popper:e,onUpdate:n}}R0.$$tippy=!0;var Gx=1,ra=[],eA=[];function $x(i,e){var t=Q0(i,Object.assign({},li,x0(C0(e)))),r,n,s,o=!1,a=!1,c=!1,l=!1,u,A,h,d=[],f=v0(Ke,t.interactiveDebounce),g,p=Gx++,v=null,B=Cx(t.plugins),C={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:p,reference:i,popper:hs(),popperInstance:v,props:t,state:C,plugins:B,clearDelayTimeouts:ze,setProps:T,setContent:m,show:E,hide:Q,hideWithInteractivity:N,enable:ot,disable:et,unmount:J,destroy:z};if(!t.render)return y;var x=t.render(y),_=x.popper,D=x.onUpdate;_.setAttribute("data-tippy-root",""),_.id="tippy-"+y.id,y.popper=_,i._tippy=y,_._tippy=y;var F=B.map(function($){return $.fn(y)}),O=i.hasAttribute("aria-expanded");return Qe(),k(),q(),R("onCreate",[y]),t.showOnCreate&&Ce(),_.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),_.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||i}function oe(){var $=le().parentNode;return $?Qx($):document}function L(){return Zc(_)}function U($){return y.state.isMounted&&!y.state.isVisible||Bi.isTouch||u&&u.type==="focus"?0:qc(y.props.delay,$?0:1,li.delay)}function q($){$===void 0&&($=!1),_.style.pointerEvents=y.props.interactive&&!$?"":"none",_.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 w(){var $=y.props.aria;if($.content){var ae="aria-"+$.content,ue=_.id,ve=sn(y.props.triggerTarget||i);ve.forEach(function(me){var nt=me.getAttribute(ae);if(y.state.isVisible)me.setAttribute(ae,nt?nt+" "+ue:ue);else{var Lt=nt&&nt.replace(ue,"").trim();Lt?me.setAttribute(ae,Lt):me.removeAttribute(ae)}})}}function k(){if(!(O||!y.props.aria.expanded)){var $=sn(y.props.triggerTarget||i);$.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),ra=ra.filter(function($){return $!==f})}function Y($){if(!(Bi.isTouch&&(c||$.type==="mousedown"))){var ae=$.composedPath&&$.composedPath()[0]||$.target;if(!(y.props.interactive&&T0(_,ae))){if(sn(y.props.triggerTarget||i).some(function(ue){return T0(ue,ae)})){if(Bi.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 ie(){c=!0}function re(){c=!1}function he(){var $=oe();$.addEventListener("mousedown",Y,!0),$.addEventListener("touchend",Y,wr),$.addEventListener("touchstart",re,wr),$.addEventListener("touchmove",ie,wr)}function fe(){var $=oe();$.removeEventListener("mousedown",Y,!0),$.removeEventListener("touchend",Y,wr),$.removeEventListener("touchstart",re,wr),$.removeEventListener("touchmove",ie,wr)}function we($,ae){Fe($,function(){!y.state.isVisible&&_.parentNode&&_.parentNode.contains(_)&&ae()})}function be($,ae){Fe($,ae)}function Fe($,ae){var ue=L().box;function ve(me){me.target===ue&&(Xc(ue,"remove",ve),ae())}if($===0)return ae();Xc(ue,"remove",A),Xc(ue,"add",ve),A=ve}function pe($,ae,ue){ue===void 0&&(ue=!1);var ve=sn(y.props.triggerTarget||i);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})),yx(y.props.trigger).forEach(function($){if($!=="manual")switch(pe($,Re),$){case"mouseenter":pe("mouseleave",Se);break;case"focus":pe(kx?"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&&bx($)&&ra.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&&tt($)}}function Ke($){var ae=$.target,ue=le().contains(ae)||_.contains(ae);if(!($.type==="mousemove"&&ue)){var ve=$e().concat(_).map(function(me){var nt,Lt=me._tippy,kt=(nt=Lt.popperInstance)==null?void 0:nt.state;return kt?{popperRect:me.getBoundingClientRect(),popperState:kt,props:t}:null}).filter(Boolean);wx(ve,$)&&(K(),tt($))}}function Se($){var ae=ke($)||y.props.trigger.indexOf("click")>=0&&o;if(!ae){if(y.props.interactive){y.hideWithInteractivity($);return}tt($)}}function ye($){y.props.trigger.indexOf("focusin")<0&&$.target!==le()||y.props.interactive&&$.relatedTarget&&_.contains($.relatedTarget)||tt($)}function ke($){return Bi.isTouch?j()!==$.type.indexOf("touch")>=0:!1}function Ue(){Xe();var $=y.props,ae=$.popperOptions,ue=$.placement,ve=$.offset,me=$.getReferenceClientRect,nt=$.moveTransition,Lt=X()?Zc(_).arrow:null,kt=me?{getBoundingClientRect:me,contextElement:me.contextElement||le()}:i,An={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(un){var cr=un.state;if(X()){var Is=L(),vs=Is.box;["placement","reference-hidden","escaped"].forEach(function(hn){hn==="placement"?vs.setAttribute("data-placement",cr.placement):cr.attributes.popper["data-popper-"+hn]?vs.setAttribute("data-"+hn,""):vs.removeAttribute("data-"+hn)}),cr.attributes.popper={}}}},Mt=[{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}},An];X()&&Lt&&Mt.push({name:"arrow",options:{element:Lt,padding:3}}),Mt.push.apply(Mt,(ae==null?void 0:ae.modifiers)||[]),y.popperInstance=Ex(kt,_,Object.assign({},ae,{placement:ue,onFirstUpdate:h,modifiers:Mt}))}function Xe(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Ge(){var $=y.props.appendTo,ae,ue=le();y.props.interactive&&$===E0||$==="parent"?ae=ue.parentNode:ae=I0($,[ue]),ae.contains(_)||ae.appendChild(_),y.state.isMounted=!0,Ue()}function $e(){return ta(_.querySelectorAll("[data-tippy-root]"))}function Ce($){y.clearDelayTimeouts(),$&&R("onTrigger",[y,$]),he();var ae=U(!0),ue=M(),ve=ue[0],me=ue[1];Bi.isTouch&&ve==="hold"&&me&&(ae=me),ae?r=setTimeout(function(){y.show()},ae):y.show()}function tt($){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 et(){y.hide(),y.state.isEnabled=!1}function ze(){clearTimeout(r),clearTimeout(n),cancelAnimationFrame(s)}function T($){if(!y.state.isDestroyed){R("onBeforeUpdate",[y,$]),Ne();var ae=y.props,ue=Q0(i,Object.assign({},ae,C0($),{ignoreAttributes:!0}));y.props=ue,Qe(),ae.interactiveDebounce!==ue.interactiveDebounce&&(K(),f=v0(Ke,ue.interactiveDebounce)),ae.triggerTarget&&!ue.triggerTarget?sn(ae.triggerTarget).forEach(function(ve){ve.removeAttribute("aria-expanded")}):ue.triggerTarget&&i.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=Bi.isTouch&&!y.props.touch,me=qc(y.props.duration,0,li.duration);if(!($||ae||ue||ve)&&!le().hasAttribute("disabled")&&(R("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,X()&&(_.style.visibility="visible"),q(),he(),y.state.isMounted||(_.style.transition="none"),X()){var nt=L(),Lt=nt.box,kt=nt.content;jc([Lt,kt],0)}h=function(){var Mt;if(!(!y.state.isVisible||l)){if(l=!0,_.offsetHeight,_.style.transition=y.props.moveTransition,X()&&y.props.animation){var kr=L(),un=kr.box,cr=kr.content;jc([un,cr],me),B0([un,cr],"visible")}w(),k(),y0(eA,y),(Mt=y.popperInstance)==null||Mt.forceUpdate(),R("onMount",[y]),y.props.animation&&X()&&be(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=qc(y.props.duration,1,li.duration);if(!($||ae||ue)&&(R("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,l=!1,o=!1,X()&&(_.style.visibility="hidden"),K(),fe(),q(!0),X()){var me=L(),nt=me.box,Lt=me.content;y.props.animation&&(jc([nt,Lt],ve),B0([nt,Lt],"hidden"))}w(),k(),y.props.animation?X()&&we(ve,y.unmount):y.unmount()}}function N($){oe().addEventListener("mousemove",f),y0(ra,f),f($)}function J(){y.state.isVisible&&y.hide(),y.state.isMounted&&(Xe(),$e().forEach(function($){$._tippy.unmount()}),_.parentNode&&_.parentNode.removeChild(_),eA=eA.filter(function($){return $!==y}),y.state.isMounted=!1,R("onHidden",[y]))}function z(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Ne(),delete i._tippy,y.state.isDestroyed=!0,R("onDestroy",[y]))}}function _r(i,e){e===void 0&&(e={});var t=li.plugins.concat(e.plugins||[]);Dx();var r=Object.assign({},e,{plugins:t}),n=xx(i),s=n.reduce(function(o,a){var c=a&&$x(a,r);return c&&o.push(c),o},[]);return ia(i)?s[0]:s}_r.defaultProps=li,_r.setDefaultProps=Nx,_r.currentInput=Bi,Object.assign({},Zg,{effect:function(e){var t=e.state,r={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,r.popper),t.styles=r,t.elements.arrow&&Object.assign(t.elements.arrow.style,r.arrow)}}),_r.setDefaultProps({render:R0});function ii(i,e){return`${i}-${e}`}function Ti(i){var e,t;const r=[];return(((e=i.renderer)==null?void 0:e.type)==="video"||((t=i.renderer)==null?void 0:t.type)==="audio")&&r.push({...i.config,...i.options}),r.push(...i.childNodes.flatMap(Ti).filter(Boolean)),r}class na extends Error{constructor(e,t=new Error,r=!1){super(),this.fatal=!1,this.fatal=r,this.stack=t.stack,this.message=[e,t.message].filter(Boolean).join(" - ")}}function or(i,e,t){return Math.min(Math.max(e,i),t)}const Hx=5;function Yx(i,e){return i.length!==e.length||i.some((t,r)=>t!==e[r])}class Vx{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._canvas=xt(),this._controls=xt(),this.host=e}set activeScenes(e){Yx(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,r,n;const s=or(0,e,this.host.duration);this.activeScenes=((t=this.host.composition)==null?void 0:t.tracks.reduce((a,c)=>a.concat(c.scenes.filter(({start:l,duration:u})=>s>=l&&s<l+u)),[]))??[];const o=s!==this.currentTime;this._currentTime=s,this._upcomingScenes=((r=this.host.composition)==null?void 0:r.tracks.reduce((a,c)=>a.concat(c.scenes.filter(({start:l})=>s>=l-Hx&&s<l)),[]))??[],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=>{Ti(e.layout.node).forEach(({key:r})=>{var n,s,o;const{id:a,start:c,duration:l}=e,u=this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused,A=ii(a,r);if(this.host.media[A]){const h=this.host.media[A],{speed:d,volume:f,hls:g,node:p,start:v,duration:B}=h,C=this.host.mediaState[A];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=or(0,this.host.volume*(f??1),1),p.playbackRate=or(.1,this.host.playbackRate*(d??1),4)))}else if(u){const h=`${c}-${l}`,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,c/this.host.duration*100),end:Math.min((c+l)/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(r=>Ti(r.layout.node).map(async({key:s})=>{const o=ii(r.id,s);if(this.host.media[o]){const a=this.host.media[o],{node:c}=a,l=this.host.mediaState[o];if(!this.activeScenes.includes(r))c.paused||c.pause();else if(l&&!this.host.waiting&&!this.host.loading&&!this.host.paused&&c.paused&&l.initialised)try{await c.play()}catch(A){throw new na("Video play error",A,!0)}}}))))??[])}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 Kx=Ir(async function(e){const{weight:t,family:r}=e,{client:n,server:s}=r.weights.find(a=>a.weight===t)??{};return!n&&!s?null:new FontFace(e.family.name,`url(${n??s})`,{weight:t,style:"normal"}).load()},{cacheKey:([i])=>JSON.stringify(i)}),Wx=Ir(async({options:i})=>{const e=await Kx(i.font);return e&&document.fonts.add(e),{font:i.font}}),qx=Ir(async({config:i})=>i.src?new Promise((e,t)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{e({image:r})},r.onerror=n=>{t(n)},r.src=i.src}):{image:null},{cacheKey:([{config:i}])=>JSON.stringify(i)});async function tA(i){return i.duration===1/0?new Promise(e=>{i.currentTime=Number.MAX_SAFE_INTEGER,i.ontimeupdate=()=>{i.ontimeupdate=null,e(i.duration),i.currentTime=0}}):i.duration}function Jx(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function jx(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function Xx({config:i,elementSize:e}){return new Promise(async t=>{let r=null;const{type:n,key:s,src:o,duration:a}=i;n==="video"?(r=document.createElement("video"),r.playsInline=!0,e&&(r.width=e.width,r.height=e.height)):r=document.createElement("audio"),r.muted=!0,r.loop=!1,r.crossOrigin="anonymous",r.src=o;let c=!1;if(r.startLoadOnce=()=>{c||(r.preload="auto",r.load(),c=!0)},n==="video"&&a&&i.aspectRatio)r.preload="none",t({key:s,hls:null,node:r,aspectRatio:i.aspectRatio,totalDuration:a});else{r.preload="metadata";const l=async()=>{const u=await tA(r),A=r instanceof HTMLVideoElement&&r.videoHeight>0?r.videoWidth/r.videoHeight:null;t({key:s,hls:null,node:r,totalDuration:u,aspectRatio:A}),r.removeEventListener("loadedmetadata",l)};r.addEventListener("loadedmetadata",l)}})}function zx({key:i,playlist:e,duration:t,elementSize:r}){return new Promise(n=>{const s=document.createElement("video");s instanceof HTMLVideoElement&&(r&&(s.width=r.width,s.height=r.height),s.playsInline=!0),s.muted=!0,s.loop=!1,s.crossOrigin="anonymous";let o=!1,a=!1,c=!1;const l=new ai({autoStartLoad:!0,capLevelToPlayerSize:!0,xhrSetup:u=>{const{open:A}=u,h=e.split("?")[1];u.open=function(d,f,g){if(h&&!f.toString().includes("?")&&(f+="?"+h),!o&&f.toString().includes(".ts")){if(a)return;a=!0}A.apply(this,[d,f,g])}}});l.on(ai.Events.BUFFER_CODECS,async(u,A)=>{var h,d;if(c)return;const f=A.video,g=(h=f==null?void 0:f.metadata)==null?void 0:h.width,p=(d=f==null?void 0:f.metadata)==null?void 0:d.height;if(g&&p){c=!0,o||l==null||l.stopLoad();const v=t??await tA(s);n({key:i,hls:l,node:s,aspectRatio:g/p,totalDuration:v})}}),l.on(ai.Events.LEVEL_LOADED,async()=>{setTimeout(async()=>{if(c)return;c=!0,o||l==null||l.stopLoad();const u=t??await tA(s),A=l.levels[l.levels.length-1];n({key:i,hls:l,node:s,aspectRatio:A.width/A.height,totalDuration:u})},2e3)}),l.loadSource(e),l.attachMedia(s),l.startLoadOnce=(u=-1,A)=>{if(l&&!o){const h=l.levels.findIndex(d=>Math.min(d.height,d.width)===A);o=!0,l.startLoad(u),h!==-1&&(l.currentLevel=h)}}})}function Zx({config:i,elementSize:e}){const{playlist:t}=i;return t&&!Jx()&&ai.isSupported()?zx({key:i.key,playlist:t,duration:i.duration??0,elementSize:e}):Xx({config:i,elementSize:e})}let eQ=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 r=new AbortController,n=setTimeout(()=>{r.signal.aborted||(this.host._processing=!0)},t);return r.signal.addEventListener("abort",()=>{clearTimeout(n)}),r},this._mediaFactory=Ir(async(t,r)=>{var n,s,o,a;const{key:c}=r,l=((s=(n=this.host.shadowRoot)==null?void 0:n.host)==null?void 0:s.clientWidth)??0,u=((a=(o=this.host.shadowRoot)==null?void 0:o.host)==null?void 0:a.clientHeight)??0,A=await Zx({config:r,elementSize:{width:l,height:u}}),h={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},d=Object.keys(h).reduce((f,g)=>{const p=g,v=h[p]({id:t,key:c,node:A.node});return f[p]=v,A.node.addEventListener(g,v),f},{});return{media:A,listeners:d,aspectRatio:A.aspectRatio,source:()=>A.node}},{cacheKey:([t,{key:r,src:n,playlist:s}])=>JSON.stringify({id:t,key:r,src:n==null?void 0:n.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._handleLoadedData=({id:t,key:r,node:n})=>()=>{const s=ii(t,r),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:r,node:n}})))},this._handleWaiting=({id:t,key:r,node:n})=>()=>{const s=ii(t,r),o=this.mediaState[s];o!=null&&o.initialised&&!(o!=null&&o.waiting)&&(this.mediaState={...this.mediaState,[s]:{...o,waiting:!0}},this.host.dispatchEvent(new CustomEvent("video:waiting",{detail:{id:t,key:r,node:n}})))},this._handleCanPlay=({id:t,key:r})=>()=>{const n=ii(t,r),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:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:seeking",{detail:{id:t,key:r,node:n}}))},this._handleSeeked=({id:t,key:r,node:n})=>()=>{const s=ii(t,r),o=this.mediaState[s];o!=null&&o.initialised&&(this.host.draw(),this.host.activeScenes.flatMap(a=>Ti(a.layout.node).map(({id:l})=>l)).includes(t)&&this.host.dispatchEvent(new CustomEvent("seeked",{detail:this.host.currentTime})),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:t,key:r,node:n}})))},this._handlePlay=({id:t,key:r,node:n})=>()=>{this.hasPlayed=!0,this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:t,key:r,node:n}}))},this._handlePlaying=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:t,key:r,node:n}}))},this._handlePause=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:t,key:r,node:n}}))},this._handleStalled=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:t,key:r,node:n}}))},this._handleTimeUpdate=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:t,key:r,node:n}}))},this._handleEnded=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:t,key:r,node:n}}))},this._handleError=({id:t,key:r,node:n})=>()=>{const s=new na(`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:r,node:n}}))},this._cleanupMedia=t=>{var r;const n=this.media[t];n&&(n.node.pause(),n.node.src="",(r=n.hls)==null||r.destroy(),Object.keys(n.listeners??{}).forEach(s=>{var o,a;if((o=this.media)!=null&&o[t]){const c=(a=n.listeners)==null?void 0:a[s];c&&n.node.removeEventListener(s,c)}}),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 ks(this.host,async([e,t,r,n])=>{var s,o;this._compositionController.abort(),this._compositionController=new AbortController;const a=this._compositionController,c=this._delayProcessing();try{if(this.host._errors=[],(!t||!this.host._languages.find(({value:l})=>t===l))&&(this.host._language=(s=this.host._languages[0])==null?void 0:s.value),e){const{width:l,height:u}=yl({aspectRatio:r,resolution:1080});try{(o=this.composition)==null||o.cleanup();const f=await od({debug:n,config:e,resolvers:{text:Wx,image:qx,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:l,rootHeight:u});if(a.signal.aborted)return;this.composition=f}catch(f){throw new na("Fatal composition error",f,!0)}this.duration=this.composition.duration;const A={...this.media},h={...this.mediaState},d=[];for(const f of this.composition.tracks)for(const g of f.scenes){const p=Ti(g.layout.node);for(const v of p){const{media:B,listeners:C}=await this._mediaFactory(g.id,v),y=ii(g.id,B.key);d.push(y);const x=(v.startOffset??0)*B.totalDuration,_=(1-(v.endOffset??0))*B.totalDuration;A[y]={...B,listeners:C,start:x,duration:_-x,speed:v.speed??1,volume:v.volume??1},h[y]={initialised:!B,waiting:!!B,...this.mediaState[y]}}}this.media=A,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(l){this.composition=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",{composed:!0,bubbles:!0,error:l,message:l.message}))}finally{c.abort(),this.host._processing=!1}},()=>[this.host.config,this.host.language,this.host.aspectRatio,this.host.debug])}_setMediaCurrentTime({time:e,scene:t}){const{id:r,layout:n,start:s}=t;Ti(n.node).forEach(({key:a})=>{const c=ii(r,a);if(this.media[c]){const l=this.media[c],u=(e-s)*l.speed;l.node.currentTime=or(l.start,u+l.start,l.start+l.duration)}})}setMediaCurrentTime(e){var t;(t=this.composition)==null||t.tracks.forEach(r=>{r.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 tQ(i){i.requestFullscreen?i.requestFullscreen():i.mozRequestFullScreen?i.mozRequestFullScreen():i.webkitRequestFullscreen?i.webkitRequestFullscreen():i.msRequestFullscreen&&i.msRequestFullscreen()}function iQ(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const iA=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen","preview"],rQ={id:"captions",event:"captions:click",label:"Closed Captions"},nQ={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},D0={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}]},sQ={id:"playbackRate",label:"Playback playbackRate",subItems:D0};class oQ extends jA{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==Nr.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)),Vi}}const rA=Or(oQ),aQ=dS(()=>{const i=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"}),r=new FontFace("Roobert Captions","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),n=Zh.map(s=>({load:!1,font:new FontFace(s.family,`url(${s.url})`,{style:s.style})}));return[{load:!0,font:i},{load:!0,font:e},{load:!0,font:t},{load:!0,font:r},...n]}),bi={"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"},lQ={colors:bi,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 ${bi["dark-100"]}`,medium:`0 .125rem .625rem ${bi["dark-100"]}`,large:`0 .25rem 1rem ${bi["dark-50"]}`,xl:`.25rem .25rem 1rem ${bi["dark-250"]}`,xxl:`0 .25rem 2rem ${bi["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${bi["dark-250"]}`,toolbar:`0 -.625rem .625rem ${bi["dark-50"]}`,text:`0 0 .25rem ${bi["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:bi["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},L0=AS(lQ,{delimiter:"-"}),cQ=Object.keys(L0).map(i=>En(`:host { --${i}: ${L0[i]}; }`)),Je=(i=>{const e=class extends i{firstUpdated(){aQ().forEach(({load:s,font:o})=>{document.fonts.add(o),s&&o.load()})}};return e.styles=[(i==null?void 0:i.styles)??[],cQ,pt`
2528
+ */const qg=(i,e,t)=>{const r=new Map;for(let n=e;n<=t;n++)r.set(i[n],n);return r},Jg=Or(class extends xn{constructor(i){if(super(i),i.type!==Nr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(i,e,t){let r;t===void 0?t=e:e!==void 0&&(r=e);const n=[],s=[];let o=0;for(const a of i)n[o]=r?r(a,o):o,s[o]=t(a,o),o++;return{values:s,keys:n}}render(i,e,t){return this.dt(i,e,t).values}update(i,[e,t,r]){const n=Hp(i),{values:s,keys:o}=this.dt(e,t,r);if(!Array.isArray(n))return this.ut=o,s;const a=this.ut??(this.ut=[]),c=[];let l,u,A=0,h=n.length-1,d=0,f=s.length-1;for(;A<=h&&d<=f;)if(n[A]===null)A++;else if(n[h]===null)h--;else if(a[A]===o[d])c[d]=mr(n[A],s[d]),A++,d++;else if(a[h]===o[f])c[f]=mr(n[h],s[f]),h--,f--;else if(a[A]===o[f])c[f]=mr(n[A],s[f]),Sn(i,c[f+1],n[A]),A++,f--;else if(a[h]===o[d])c[d]=mr(n[h],s[d]),Sn(i,n[A],n[h]),h--,d++;else if(l===void 0&&(l=qg(o,d,f),u=qg(a,A,h)),l.has(a[A]))if(l.has(a[h])){const g=u.get(o[d]),p=g!==void 0?n[g]:null;if(p===null){const v=Sn(i,n[A]);mr(v,s[d]),c[d]=v}else c[d]=mr(p,s[d]),Sn(i,n[A],p),n[g]=null;d++}else wa(n[h]),h--;else wa(n[A]),A++;for(;d<=f;){const g=Sn(i,c[f+1]);mr(g,s[d]),c[d++]=g}for(;A<=h;){const g=n[A++];g!==null&&wa(g)}return this.ut=o,$p(i,c),$i}});var Ut="top",ei="bottom",ti="right",Gt="left",Oc="auto",ss=[Ut,ei,ti,Gt],en="start",os="end",fS="clippingParents",jg="viewport",as="popper",gS="reference",Xg=ss.reduce(function(i,e){return i.concat([e+"-"+en,e+"-"+os])},[]),zg=[].concat(ss,[Oc]).reduce(function(i,e){return i.concat([e,e+"-"+en,e+"-"+os])},[]),pS="beforeRead",mS="read",ES="afterRead",IS="beforeMain",vS="main",yS="afterMain",CS="beforeWrite",BS="write",TS="afterWrite",bS=[pS,mS,ES,IS,vS,yS,CS,BS,TS];function yi(i){return i?(i.nodeName||"").toLowerCase():null}function Vt(i){if(i==null)return window;if(i.toString()!=="[object Window]"){var e=i.ownerDocument;return e&&e.defaultView||window}return i}function xr(i){var e=Vt(i).Element;return i instanceof e||i instanceof Element}function ii(i){var e=Vt(i).HTMLElement;return i instanceof e||i instanceof HTMLElement}function Uc(i){if(typeof ShadowRoot>"u")return!1;var e=Vt(i).ShadowRoot;return i instanceof e||i instanceof ShadowRoot}function SS(i){var e=i.state;Object.keys(e.elements).forEach(function(t){var r=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];!ii(s)||!yi(s)||(Object.assign(s.style,r),Object.keys(n).forEach(function(o){var a=n[o];a===!1?s.removeAttribute(o):s.setAttribute(o,a===!0?"":a)}))})}function xS(i){var e=i.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(r){var n=e.elements[r],s=e.attributes[r]||{},o=Object.keys(e.styles.hasOwnProperty(r)?e.styles[r]:t[r]),a=o.reduce(function(c,l){return c[l]="",c},{});!ii(n)||!yi(n)||(Object.assign(n.style,a),Object.keys(s).forEach(function(c){n.removeAttribute(c)}))})}}const Zg={name:"applyStyles",enabled:!0,phase:"write",fn:SS,effect:xS,requires:["computeStyles"]};function Ci(i){return i.split("-")[0]}var Qr=Math.max,Xo=Math.min,tn=Math.round;function Gc(){var i=navigator.userAgentData;return i!=null&&i.brands&&Array.isArray(i.brands)?i.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function e0(){return!/^((?!chrome|android).)*safari/i.test(Gc())}function rn(i,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var r=i.getBoundingClientRect(),n=1,s=1;e&&ii(i)&&(n=i.offsetWidth>0&&tn(r.width)/i.offsetWidth||1,s=i.offsetHeight>0&&tn(r.height)/i.offsetHeight||1);var o=xr(i)?Vt(i):window,a=o.visualViewport,c=!e0()&&t,l=(r.left+(c&&a?a.offsetLeft:0))/n,u=(r.top+(c&&a?a.offsetTop:0))/s,A=r.width/n,h=r.height/s;return{width:A,height:h,top:u,right:l+A,bottom:u+h,left:l,x:l,y:u}}function $c(i){var e=rn(i),t=i.offsetWidth,r=i.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-r)<=1&&(r=e.height),{x:i.offsetLeft,y:i.offsetTop,width:t,height:r}}function t0(i,e){var t=e.getRootNode&&e.getRootNode();if(i.contains(e))return!0;if(t&&Uc(t)){var r=e;do{if(r&&i.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function Fi(i){return Vt(i).getComputedStyle(i)}function QS(i){return["table","td","th"].indexOf(yi(i))>=0}function sr(i){return((xr(i)?i.ownerDocument:i.document)||window.document).documentElement}function zo(i){return yi(i)==="html"?i:i.assignedSlot||i.parentNode||(Uc(i)?i.host:null)||sr(i)}function i0(i){return!ii(i)||Fi(i).position==="fixed"?null:i.offsetParent}function wS(i){var e=/firefox/i.test(Gc()),t=/Trident/i.test(Gc());if(t&&ii(i)){var r=Fi(i);if(r.position==="fixed")return null}var n=zo(i);for(Uc(n)&&(n=n.host);ii(n)&&["html","body"].indexOf(yi(n))<0;){var s=Fi(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 ls(i){for(var e=Vt(i),t=i0(i);t&&QS(t)&&Fi(t).position==="static";)t=i0(t);return t&&(yi(t)==="html"||yi(t)==="body"&&Fi(t).position==="static")?e:t||wS(i)||e}function Hc(i){return["top","bottom"].indexOf(i)>=0?"x":"y"}function cs(i,e,t){return Qr(i,Xo(e,t))}function _S(i,e,t){var r=cs(i,e,t);return r>t?t:r}function r0(){return{top:0,right:0,bottom:0,left:0}}function n0(i){return Object.assign({},r0(),i)}function s0(i,e){return e.reduce(function(t,r){return t[r]=i,t},{})}var RS=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,n0(typeof e!="number"?e:s0(e,ss))};function DS(i){var e,t=i.state,r=i.name,n=i.options,s=t.elements.arrow,o=t.modifiersData.popperOffsets,a=Ci(t.placement),c=Hc(a),l=[Gt,ti].indexOf(a)>=0,u=l?"height":"width";if(!(!s||!o)){var A=RS(n.padding,t),h=$c(s),d=c==="y"?Ut:Gt,f=c==="y"?ei:ti,g=t.rects.reference[u]+t.rects.reference[c]-o[c]-t.rects.popper[u],p=o[c]-t.rects.reference[c],v=ls(s),B=v?c==="y"?v.clientHeight||0:v.clientWidth||0:0,C=g/2-p/2,y=A[d],x=B-h[u]-A[f],_=B/2-h[u]/2+C,D=cs(y,_,x),F=c;t.modifiersData[r]=(e={},e[F]=D,e.centerOffset=D-_,e)}}function LS(i){var e=i.state,t=i.options,r=t.element,n=r===void 0?"[data-popper-arrow]":r;n!=null&&(typeof n=="string"&&(n=e.elements.popper.querySelector(n),!n)||t0(e.elements.popper,n)&&(e.elements.arrow=n))}const kS={name:"arrow",enabled:!0,phase:"main",fn:DS,effect:LS,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function nn(i){return i.split("-")[1]}var MS={top:"auto",right:"auto",bottom:"auto",left:"auto"};function FS(i,e){var t=i.x,r=i.y,n=e.devicePixelRatio||1;return{x:tn(t*n)/n||0,y:tn(r*n)/n||0}}function o0(i){var e,t=i.popper,r=i.popperRect,n=i.placement,s=i.variation,o=i.offsets,a=i.position,c=i.gpuAcceleration,l=i.adaptive,u=i.roundOffsets,A=i.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=Gt,y=Ut,x=window;if(l){var _=ls(t),D="clientHeight",F="clientWidth";if(_===Vt(t)&&(_=sr(t),Fi(_).position!=="static"&&a==="absolute"&&(D="scrollHeight",F="scrollWidth")),_=_,n===Ut||(n===Gt||n===ti)&&s===os){y=ei;var O=A&&_===x&&x.visualViewport?x.visualViewport.height:_[D];g-=O-r.height,g*=c?1:-1}if(n===Gt||(n===Ut||n===ei)&&s===os){C=ti;var M=A&&_===x&&x.visualViewport?x.visualViewport.width:_[F];d-=M-r.width,d*=c?1:-1}}var j=Object.assign({position:a},l&&MS),X=u===!0?FS({x:d,y:g},Vt(t)):{x:d,y:g};if(d=X.x,g=X.y,c){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 PS(i){var e=i.state,t=i.options,r=t.gpuAcceleration,n=r===void 0?!0:r,s=t.adaptive,o=s===void 0?!0:s,a=t.roundOffsets,c=a===void 0?!0:a,l={placement:Ci(e.placement),variation:nn(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,o0(Object.assign({},l,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:o,roundOffsets:c})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,o0(Object.assign({},l,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:c})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}const NS={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:PS,data:{}};var Zo={passive:!0};function OS(i){var e=i.state,t=i.instance,r=i.options,n=r.scroll,s=n===void 0?!0:n,o=r.resize,a=o===void 0?!0:o,c=Vt(e.elements.popper),l=[].concat(e.scrollParents.reference,e.scrollParents.popper);return s&&l.forEach(function(u){u.addEventListener("scroll",t.update,Zo)}),a&&c.addEventListener("resize",t.update,Zo),function(){s&&l.forEach(function(u){u.removeEventListener("scroll",t.update,Zo)}),a&&c.removeEventListener("resize",t.update,Zo)}}const US={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:OS,data:{}};var GS={left:"right",right:"left",bottom:"top",top:"bottom"};function ea(i){return i.replace(/left|right|bottom|top/g,function(e){return GS[e]})}var $S={start:"end",end:"start"};function a0(i){return i.replace(/start|end/g,function(e){return $S[e]})}function Yc(i){var e=Vt(i),t=e.pageXOffset,r=e.pageYOffset;return{scrollLeft:t,scrollTop:r}}function Vc(i){return rn(sr(i)).left+Yc(i).scrollLeft}function HS(i,e){var t=Vt(i),r=sr(i),n=t.visualViewport,s=r.clientWidth,o=r.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;var l=e0();(l||!l&&e==="fixed")&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a+Vc(i),y:c}}function YS(i){var e,t=sr(i),r=Yc(i),n=(e=i.ownerDocument)==null?void 0:e.body,s=Qr(t.scrollWidth,t.clientWidth,n?n.scrollWidth:0,n?n.clientWidth:0),o=Qr(t.scrollHeight,t.clientHeight,n?n.scrollHeight:0,n?n.clientHeight:0),a=-r.scrollLeft+Vc(i),c=-r.scrollTop;return Fi(n||t).direction==="rtl"&&(a+=Qr(t.clientWidth,n?n.clientWidth:0)-s),{width:s,height:o,x:a,y:c}}function Kc(i){var e=Fi(i),t=e.overflow,r=e.overflowX,n=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+n+r)}function l0(i){return["html","body","#document"].indexOf(yi(i))>=0?i.ownerDocument.body:ii(i)&&Kc(i)?i:l0(zo(i))}function As(i,e){var t;e===void 0&&(e=[]);var r=l0(i),n=r===((t=i.ownerDocument)==null?void 0:t.body),s=Vt(r),o=n?[s].concat(s.visualViewport||[],Kc(r)?r:[]):r,a=e.concat(o);return n?a:a.concat(As(zo(o)))}function Wc(i){return Object.assign({},i,{left:i.x,top:i.y,right:i.x+i.width,bottom:i.y+i.height})}function VS(i,e){var t=rn(i,!1,e==="fixed");return t.top=t.top+i.clientTop,t.left=t.left+i.clientLeft,t.bottom=t.top+i.clientHeight,t.right=t.left+i.clientWidth,t.width=i.clientWidth,t.height=i.clientHeight,t.x=t.left,t.y=t.top,t}function c0(i,e,t){return e===jg?Wc(HS(i,t)):xr(e)?VS(e,t):Wc(YS(sr(i)))}function KS(i){var e=As(zo(i)),t=["absolute","fixed"].indexOf(Fi(i).position)>=0,r=t&&ii(i)?ls(i):i;return xr(r)?e.filter(function(n){return xr(n)&&t0(n,r)&&yi(n)!=="body"}):[]}function WS(i,e,t,r){var n=e==="clippingParents"?KS(i):[].concat(e),s=[].concat(n,[t]),o=s[0],a=s.reduce(function(c,l){var u=c0(i,l,r);return c.top=Qr(u.top,c.top),c.right=Xo(u.right,c.right),c.bottom=Xo(u.bottom,c.bottom),c.left=Qr(u.left,c.left),c},c0(i,o,r));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function A0(i){var e=i.reference,t=i.element,r=i.placement,n=r?Ci(r):null,s=r?nn(r):null,o=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,c;switch(n){case Ut:c={x:o,y:e.y-t.height};break;case ei:c={x:o,y:e.y+e.height};break;case ti:c={x:e.x+e.width,y:a};break;case Gt:c={x:e.x-t.width,y:a};break;default:c={x:e.x,y:e.y}}var l=n?Hc(n):null;if(l!=null){var u=l==="y"?"height":"width";switch(s){case en:c[l]=c[l]-(e[u]/2-t[u]/2);break;case os:c[l]=c[l]+(e[u]/2-t[u]/2);break}}return c}function us(i,e){e===void 0&&(e={});var t=e,r=t.placement,n=r===void 0?i.placement:r,s=t.strategy,o=s===void 0?i.strategy:s,a=t.boundary,c=a===void 0?fS:a,l=t.rootBoundary,u=l===void 0?jg:l,A=t.elementContext,h=A===void 0?as:A,d=t.altBoundary,f=d===void 0?!1:d,g=t.padding,p=g===void 0?0:g,v=n0(typeof p!="number"?p:s0(p,ss)),B=h===as?gS:as,C=i.rects.popper,y=i.elements[f?B:h],x=WS(xr(y)?y:y.contextElement||sr(i.elements.popper),c,u,o),_=rn(i.elements.reference),D=A0({reference:_,element:C,placement:n}),F=Wc(Object.assign({},C,D)),O=h===as?F:_,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=i.modifiersData.offset;if(h===as&&j){var X=j[n];Object.keys(M).forEach(function(le){var oe=[ti,ei].indexOf(le)>=0?1:-1,L=[Ut,ei].indexOf(le)>=0?"y":"x";M[le]+=X[L]*oe})}return M}function qS(i,e){e===void 0&&(e={});var t=e,r=t.placement,n=t.boundary,s=t.rootBoundary,o=t.padding,a=t.flipVariations,c=t.allowedAutoPlacements,l=c===void 0?zg:c,u=nn(r),A=u?a?Xg:Xg.filter(function(f){return nn(f)===u}):ss,h=A.filter(function(f){return l.indexOf(f)>=0});h.length===0&&(h=A);var d=h.reduce(function(f,g){return f[g]=us(i,{placement:g,boundary:n,rootBoundary:s,padding:o})[Ci(g)],f},{});return Object.keys(d).sort(function(f,g){return d[f]-d[g]})}function JS(i){if(Ci(i)===Oc)return[];var e=ea(i);return[a0(i),e,a0(e)]}function jS(i){var e=i.state,t=i.options,r=i.name;if(!e.modifiersData[r]._skip){for(var n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!0:o,c=t.fallbackPlacements,l=t.padding,u=t.boundary,A=t.rootBoundary,h=t.altBoundary,d=t.flipVariations,f=d===void 0?!0:d,g=t.allowedAutoPlacements,p=e.options.placement,v=Ci(p),B=v===p,C=c||(B||!f?[ea(p)]:JS(p)),y=[p].concat(C).reduce(function(re,he){return re.concat(Ci(he)===Oc?qS(e,{placement:he,boundary:u,rootBoundary:A,padding:l,flipVariations:f,allowedAutoPlacements:g}):he)},[]),x=e.rects.reference,_=e.rects.popper,D=new Map,F=!0,O=y[0],M=0;M<y.length;M++){var j=y[M],X=Ci(j),le=nn(j)===en,oe=[Ut,ei].indexOf(X)>=0,L=oe?"width":"height",U=us(e,{placement:j,boundary:u,rootBoundary:A,altBoundary:h,padding:l}),q=oe?le?ti:Gt:le?ei:Ut;x[L]>_[L]&&(q=ea(q));var R=ea(q),w=[];if(s&&w.push(U[X]<=0),a&&w.push(U[q]<=0,U[R]<=0),w.every(function(re){return re})){O=j,F=!1;break}D.set(j,w)}if(F)for(var k=f?3:1,K=function(he){var fe=y.find(function(we){var be=D.get(we);if(be)return be.slice(0,he).every(function(Fe){return Fe})});if(fe)return O=fe,"break"},Y=k;Y>0;Y--){var ie=K(Y);if(ie==="break")break}e.placement!==O&&(e.modifiersData[r]._skip=!0,e.placement=O,e.reset=!0)}}const XS={name:"flip",enabled:!0,phase:"main",fn:jS,requiresIfExists:["offset"],data:{_skip:!1}};function u0(i,e,t){return t===void 0&&(t={x:0,y:0}),{top:i.top-e.height-t.y,right:i.right-e.width+t.x,bottom:i.bottom-e.height+t.y,left:i.left-e.width-t.x}}function h0(i){return[Ut,ti,ei,Gt].some(function(e){return i[e]>=0})}function zS(i){var e=i.state,t=i.name,r=e.rects.reference,n=e.rects.popper,s=e.modifiersData.preventOverflow,o=us(e,{elementContext:"reference"}),a=us(e,{altBoundary:!0}),c=u0(o,r),l=u0(a,n,s),u=h0(c),A=h0(l);e.modifiersData[t]={referenceClippingOffsets:c,popperEscapeOffsets:l,isReferenceHidden:u,hasPopperEscaped:A},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":A})}const ZS={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:zS};function ex(i,e,t){var r=Ci(i),n=[Gt,Ut].indexOf(r)>=0?-1:1,s=typeof t=="function"?t(Object.assign({},e,{placement:i})):t,o=s[0],a=s[1];return o=o||0,a=(a||0)*n,[Gt,ti].indexOf(r)>=0?{x:a,y:o}:{x:o,y:a}}function tx(i){var e=i.state,t=i.options,r=i.name,n=t.offset,s=n===void 0?[0,0]:n,o=zg.reduce(function(u,A){return u[A]=ex(A,e.rects,s),u},{}),a=o[e.placement],c=a.x,l=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=c,e.modifiersData.popperOffsets.y+=l),e.modifiersData[r]=o}const ix={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:tx};function rx(i){var e=i.state,t=i.name;e.modifiersData[t]=A0({reference:e.rects.reference,element:e.rects.popper,placement:e.placement})}const nx={name:"popperOffsets",enabled:!0,phase:"read",fn:rx,data:{}};function sx(i){return i==="x"?"y":"x"}function ox(i){var e=i.state,t=i.options,r=i.name,n=t.mainAxis,s=n===void 0?!0:n,o=t.altAxis,a=o===void 0?!1:o,c=t.boundary,l=t.rootBoundary,u=t.altBoundary,A=t.padding,h=t.tether,d=h===void 0?!0:h,f=t.tetherOffset,g=f===void 0?0:f,p=us(e,{boundary:c,rootBoundary:l,padding:A,altBoundary:u}),v=Ci(e.placement),B=nn(e.placement),C=!B,y=Hc(v),x=sx(y),_=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(_){if(s){var le,oe=y==="y"?Ut:Gt,L=y==="y"?ei:ti,U=y==="y"?"height":"width",q=_[y],R=q+p[oe],w=q-p[L],k=d?-F[U]/2:0,K=B===en?D[U]:F[U],Y=B===en?-F[U]:-D[U],ie=e.elements.arrow,re=d&&ie?$c(ie):{width:0,height:0},he=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:r0(),fe=he[oe],we=he[L],be=cs(0,D[U],re[U]),Fe=C?D[U]/2-k-be-fe-M.mainAxis:K-be-fe-M.mainAxis,pe=C?-D[U]/2+k+be+we+M.mainAxis:Y+be+we+M.mainAxis,Qe=e.elements.arrow&&ls(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=cs(d?Xo(R,Ke):R,q,d?Qr(w,Se):w);_[y]=ye,X[y]=ye-q}if(a){var ke,Ue=y==="x"?Ut:Gt,Xe=y==="x"?ei:ti,Ge=_[x],$e=x==="y"?"height":"width",Ce=Ge+p[Ue],tt=Ge-p[Xe],ot=[Ut,Gt].indexOf(v)!==-1,et=(ke=j==null?void 0:j[x])!=null?ke:0,ze=ot?Ce:Ge-D[$e]-F[$e]-et+M.altAxis,T=ot?Ge+D[$e]+F[$e]-et-M.altAxis:tt,m=d&&ot?_S(ze,Ge,T):cs(d?ze:Ce,Ge,d?T:tt);_[x]=m,X[x]=m-Ge}e.modifiersData[r]=X}}const ax={name:"preventOverflow",enabled:!0,phase:"main",fn:ox,requiresIfExists:["offset"]};function lx(i){return{scrollLeft:i.scrollLeft,scrollTop:i.scrollTop}}function cx(i){return i===Vt(i)||!ii(i)?Yc(i):lx(i)}function Ax(i){var e=i.getBoundingClientRect(),t=tn(e.width)/i.offsetWidth||1,r=tn(e.height)/i.offsetHeight||1;return t!==1||r!==1}function ux(i,e,t){t===void 0&&(t=!1);var r=ii(e),n=ii(e)&&Ax(e),s=sr(e),o=rn(i,n,t),a={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(r||!r&&!t)&&((yi(e)!=="body"||Kc(s))&&(a=cx(e)),ii(e)?(c=rn(e,!0),c.x+=e.clientLeft,c.y+=e.clientTop):s&&(c.x=Vc(s))),{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function hx(i){var e=new Map,t=new Set,r=[];i.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 c=e.get(a);c&&n(c)}}),r.push(s)}return i.forEach(function(s){t.has(s.name)||n(s)}),r}function dx(i){var e=hx(i);return bS.reduce(function(t,r){return t.concat(e.filter(function(n){return n.phase===r}))},[])}function fx(i){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(i())})})),e}}function gx(i){var e=i.reduce(function(t,r){var n=t[r.name];return t[r.name]=n?Object.assign({},n,r,{options:Object.assign({},n.options,r.options),data:Object.assign({},n.data,r.data)}):r,t},{});return Object.keys(e).map(function(t){return e[t]})}var d0={placement:"bottom",modifiers:[],strategy:"absolute"};function f0(){for(var i=arguments.length,e=new Array(i),t=0;t<i;t++)e[t]=arguments[t];return!e.some(function(r){return!(r&&typeof r.getBoundingClientRect=="function")})}function px(i){i===void 0&&(i={});var e=i,t=e.defaultModifiers,r=t===void 0?[]:t,n=e.defaultOptions,s=n===void 0?d0:n;return function(a,c,l){l===void 0&&(l=s);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},d0,s),modifiersData:{},elements:{reference:a,popper:c},attributes:{},styles:{}},A=[],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:xr(a)?As(a):a.contextElement?As(a.contextElement):[],popper:As(c)};var C=dx(gx([].concat(r,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(f0(B,C)){u.rects={reference:ux(B,ls(C),u.options.strategy==="fixed"),popper:$c(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],_=x.fn,D=x.options,F=D===void 0?{}:D,O=x.name;typeof _=="function"&&(u=_({state:u,options:F,name:O,instance:d})||u)}}}},update:fx(function(){return new Promise(function(p){d.forceUpdate(),p(u)})}),destroy:function(){g(),h=!0}};if(!f0(a,c))return d;d.setOptions(l).then(function(p){!h&&l.onFirstUpdate&&l.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}),_=function(){};A.push(x||_)}})}function g(){A.forEach(function(p){return p()}),A=[]}return d}}var mx=[US,nx,NS,Zg,ix,XS,ax,kS,ZS],Ex=px({defaultModifiers:mx}),Ix="tippy-box",g0="tippy-content",vx="tippy-backdrop",p0="tippy-arrow",m0="tippy-svg-arrow",wr={passive:!0,capture:!0},E0=function(){return document.body};function qc(i,e,t){if(Array.isArray(i)){var r=i[e];return r??(Array.isArray(t)?t[e]:t)}return i}function Jc(i,e){var t={}.toString.call(i);return t.indexOf("[object")===0&&t.indexOf(e+"]")>-1}function I0(i,e){return typeof i=="function"?i.apply(void 0,e):i}function v0(i,e){if(e===0)return i;var t;return function(r){clearTimeout(t),t=setTimeout(function(){i(r)},e)}}function yx(i){return i.split(/\s+/).filter(Boolean)}function sn(i){return[].concat(i)}function y0(i,e){i.indexOf(e)===-1&&i.push(e)}function Cx(i){return i.filter(function(e,t){return i.indexOf(e)===t})}function Bx(i){return i.split("-")[0]}function ta(i){return[].slice.call(i)}function C0(i){return Object.keys(i).reduce(function(e,t){return i[t]!==void 0&&(e[t]=i[t]),e},{})}function hs(){return document.createElement("div")}function ia(i){return["Element","Fragment"].some(function(e){return Jc(i,e)})}function Tx(i){return Jc(i,"NodeList")}function bx(i){return Jc(i,"MouseEvent")}function Sx(i){return!!(i&&i._tippy&&i._tippy.reference===i)}function xx(i){return ia(i)?[i]:Tx(i)?ta(i):Array.isArray(i)?i:ta(document.querySelectorAll(i))}function jc(i,e){i.forEach(function(t){t&&(t.style.transitionDuration=e+"ms")})}function B0(i,e){i.forEach(function(t){t&&t.setAttribute("data-state",e)})}function Qx(i){var e,t=sn(i),r=t[0];return r!=null&&(e=r.ownerDocument)!=null&&e.body?r.ownerDocument:document}function wx(i,e){var t=e.clientX,r=e.clientY;return i.every(function(n){var s=n.popperRect,o=n.popperState,a=n.props,c=a.interactiveBorder,l=Bx(o.placement),u=o.modifiersData.offset;if(!u)return!0;var A=l==="bottom"?u.top.y:0,h=l==="top"?u.bottom.y:0,d=l==="right"?u.left.x:0,f=l==="left"?u.right.x:0,g=s.top-r+A>c,p=r-s.bottom-h>c,v=s.left-t+d>c,B=t-s.right-f>c;return g||p||v||B})}function Xc(i,e,t){var r=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(n){i[r](n,t)})}function T0(i,e){for(var t=e;t;){var r;if(i.contains(t))return!0;t=t.getRootNode==null||(r=t.getRootNode())==null?void 0:r.host}return!1}var Bi={isTouch:!1},b0=0;function _x(){Bi.isTouch||(Bi.isTouch=!0,window.performance&&document.addEventListener("mousemove",S0))}function S0(){var i=performance.now();i-b0<20&&(Bi.isTouch=!1,document.removeEventListener("mousemove",S0)),b0=i}function Rx(){var i=document.activeElement;if(Sx(i)){var e=i._tippy;i.blur&&!e.state.isVisible&&i.blur()}}function Dx(){document.addEventListener("touchstart",_x,wr),window.addEventListener("blur",Rx)}var Lx=typeof window<"u"&&typeof document<"u",kx=Lx?!!window.msCrypto:!1,Mx={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Fx={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},li=Object.assign({appendTo:E0,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},Mx,Fx),Px=Object.keys(li),Nx=function(e){var t=Object.keys(e);t.forEach(function(r){li[r]=e[r]})};function x0(i){var e=i.plugins||[],t=e.reduce(function(r,n){var s=n.name,o=n.defaultValue;if(s){var a;r[s]=i[s]!==void 0?i[s]:(a=li[s])!=null?a:o}return r},{});return Object.assign({},i,t)}function Ox(i,e){var t=e?Object.keys(x0(Object.assign({},li,{plugins:e}))):Px,r=t.reduce(function(n,s){var o=(i.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 r}function Q0(i,e){var t=Object.assign({},e,{content:I0(e.content,[i])},e.ignoreAttributes?{}:Ox(i,e.plugins));return t.aria=Object.assign({},li.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 Ux=function(){return"innerHTML"};function zc(i,e){i[Ux()]=e}function w0(i){var e=hs();return i===!0?e.className=p0:(e.className=m0,ia(i)?e.appendChild(i):zc(e,i)),e}function _0(i,e){ia(e.content)?(zc(i,""),i.appendChild(e.content)):typeof e.content!="function"&&(e.allowHTML?zc(i,e.content):i.textContent=e.content)}function Zc(i){var e=i.firstElementChild,t=ta(e.children);return{box:e,content:t.find(function(r){return r.classList.contains(g0)}),arrow:t.find(function(r){return r.classList.contains(p0)||r.classList.contains(m0)}),backdrop:t.find(function(r){return r.classList.contains(vx)})}}function R0(i){var e=hs(),t=hs();t.className=Ix,t.setAttribute("data-state","hidden"),t.setAttribute("tabindex","-1");var r=hs();r.className=g0,r.setAttribute("data-state","hidden"),_0(r,i.props),e.appendChild(t),t.appendChild(r),n(i.props,i.props);function n(s,o){var a=Zc(e),c=a.box,l=a.content,u=a.arrow;o.theme?c.setAttribute("data-theme",o.theme):c.removeAttribute("data-theme"),typeof o.animation=="string"?c.setAttribute("data-animation",o.animation):c.removeAttribute("data-animation"),o.inertia?c.setAttribute("data-inertia",""):c.removeAttribute("data-inertia"),c.style.maxWidth=typeof o.maxWidth=="number"?o.maxWidth+"px":o.maxWidth,o.role?c.setAttribute("role",o.role):c.removeAttribute("role"),(s.content!==o.content||s.allowHTML!==o.allowHTML)&&_0(l,i.props),o.arrow?u?s.arrow!==o.arrow&&(c.removeChild(u),c.appendChild(w0(o.arrow))):c.appendChild(w0(o.arrow)):u&&c.removeChild(u)}return{popper:e,onUpdate:n}}R0.$$tippy=!0;var Gx=1,ra=[],eA=[];function $x(i,e){var t=Q0(i,Object.assign({},li,x0(C0(e)))),r,n,s,o=!1,a=!1,c=!1,l=!1,u,A,h,d=[],f=v0(Ke,t.interactiveDebounce),g,p=Gx++,v=null,B=Cx(t.plugins),C={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:p,reference:i,popper:hs(),popperInstance:v,props:t,state:C,plugins:B,clearDelayTimeouts:ze,setProps:T,setContent:m,show:E,hide:Q,hideWithInteractivity:N,enable:ot,disable:et,unmount:J,destroy:z};if(!t.render)return y;var x=t.render(y),_=x.popper,D=x.onUpdate;_.setAttribute("data-tippy-root",""),_.id="tippy-"+y.id,y.popper=_,i._tippy=y,_._tippy=y;var F=B.map(function($){return $.fn(y)}),O=i.hasAttribute("aria-expanded");return Qe(),k(),q(),R("onCreate",[y]),t.showOnCreate&&Ce(),_.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),_.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||i}function oe(){var $=le().parentNode;return $?Qx($):document}function L(){return Zc(_)}function U($){return y.state.isMounted&&!y.state.isVisible||Bi.isTouch||u&&u.type==="focus"?0:qc(y.props.delay,$?0:1,li.delay)}function q($){$===void 0&&($=!1),_.style.pointerEvents=y.props.interactive&&!$?"":"none",_.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 w(){var $=y.props.aria;if($.content){var ae="aria-"+$.content,ue=_.id,ve=sn(y.props.triggerTarget||i);ve.forEach(function(me){var nt=me.getAttribute(ae);if(y.state.isVisible)me.setAttribute(ae,nt?nt+" "+ue:ue);else{var Lt=nt&&nt.replace(ue,"").trim();Lt?me.setAttribute(ae,Lt):me.removeAttribute(ae)}})}}function k(){if(!(O||!y.props.aria.expanded)){var $=sn(y.props.triggerTarget||i);$.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),ra=ra.filter(function($){return $!==f})}function Y($){if(!(Bi.isTouch&&(c||$.type==="mousedown"))){var ae=$.composedPath&&$.composedPath()[0]||$.target;if(!(y.props.interactive&&T0(_,ae))){if(sn(y.props.triggerTarget||i).some(function(ue){return T0(ue,ae)})){if(Bi.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 ie(){c=!0}function re(){c=!1}function he(){var $=oe();$.addEventListener("mousedown",Y,!0),$.addEventListener("touchend",Y,wr),$.addEventListener("touchstart",re,wr),$.addEventListener("touchmove",ie,wr)}function fe(){var $=oe();$.removeEventListener("mousedown",Y,!0),$.removeEventListener("touchend",Y,wr),$.removeEventListener("touchstart",re,wr),$.removeEventListener("touchmove",ie,wr)}function we($,ae){Fe($,function(){!y.state.isVisible&&_.parentNode&&_.parentNode.contains(_)&&ae()})}function be($,ae){Fe($,ae)}function Fe($,ae){var ue=L().box;function ve(me){me.target===ue&&(Xc(ue,"remove",ve),ae())}if($===0)return ae();Xc(ue,"remove",A),Xc(ue,"add",ve),A=ve}function pe($,ae,ue){ue===void 0&&(ue=!1);var ve=sn(y.props.triggerTarget||i);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})),yx(y.props.trigger).forEach(function($){if($!=="manual")switch(pe($,Re),$){case"mouseenter":pe("mouseleave",Se);break;case"focus":pe(kx?"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&&bx($)&&ra.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&&tt($)}}function Ke($){var ae=$.target,ue=le().contains(ae)||_.contains(ae);if(!($.type==="mousemove"&&ue)){var ve=$e().concat(_).map(function(me){var nt,Lt=me._tippy,kt=(nt=Lt.popperInstance)==null?void 0:nt.state;return kt?{popperRect:me.getBoundingClientRect(),popperState:kt,props:t}:null}).filter(Boolean);wx(ve,$)&&(K(),tt($))}}function Se($){var ae=ke($)||y.props.trigger.indexOf("click")>=0&&o;if(!ae){if(y.props.interactive){y.hideWithInteractivity($);return}tt($)}}function ye($){y.props.trigger.indexOf("focusin")<0&&$.target!==le()||y.props.interactive&&$.relatedTarget&&_.contains($.relatedTarget)||tt($)}function ke($){return Bi.isTouch?j()!==$.type.indexOf("touch")>=0:!1}function Ue(){Xe();var $=y.props,ae=$.popperOptions,ue=$.placement,ve=$.offset,me=$.getReferenceClientRect,nt=$.moveTransition,Lt=X()?Zc(_).arrow:null,kt=me?{getBoundingClientRect:me,contextElement:me.contextElement||le()}:i,An={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(un){var cr=un.state;if(X()){var Is=L(),vs=Is.box;["placement","reference-hidden","escaped"].forEach(function(hn){hn==="placement"?vs.setAttribute("data-placement",cr.placement):cr.attributes.popper["data-popper-"+hn]?vs.setAttribute("data-"+hn,""):vs.removeAttribute("data-"+hn)}),cr.attributes.popper={}}}},Mt=[{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}},An];X()&&Lt&&Mt.push({name:"arrow",options:{element:Lt,padding:3}}),Mt.push.apply(Mt,(ae==null?void 0:ae.modifiers)||[]),y.popperInstance=Ex(kt,_,Object.assign({},ae,{placement:ue,onFirstUpdate:h,modifiers:Mt}))}function Xe(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Ge(){var $=y.props.appendTo,ae,ue=le();y.props.interactive&&$===E0||$==="parent"?ae=ue.parentNode:ae=I0($,[ue]),ae.contains(_)||ae.appendChild(_),y.state.isMounted=!0,Ue()}function $e(){return ta(_.querySelectorAll("[data-tippy-root]"))}function Ce($){y.clearDelayTimeouts(),$&&R("onTrigger",[y,$]),he();var ae=U(!0),ue=M(),ve=ue[0],me=ue[1];Bi.isTouch&&ve==="hold"&&me&&(ae=me),ae?r=setTimeout(function(){y.show()},ae):y.show()}function tt($){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 et(){y.hide(),y.state.isEnabled=!1}function ze(){clearTimeout(r),clearTimeout(n),cancelAnimationFrame(s)}function T($){if(!y.state.isDestroyed){R("onBeforeUpdate",[y,$]),Ne();var ae=y.props,ue=Q0(i,Object.assign({},ae,C0($),{ignoreAttributes:!0}));y.props=ue,Qe(),ae.interactiveDebounce!==ue.interactiveDebounce&&(K(),f=v0(Ke,ue.interactiveDebounce)),ae.triggerTarget&&!ue.triggerTarget?sn(ae.triggerTarget).forEach(function(ve){ve.removeAttribute("aria-expanded")}):ue.triggerTarget&&i.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=Bi.isTouch&&!y.props.touch,me=qc(y.props.duration,0,li.duration);if(!($||ae||ue||ve)&&!le().hasAttribute("disabled")&&(R("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,X()&&(_.style.visibility="visible"),q(),he(),y.state.isMounted||(_.style.transition="none"),X()){var nt=L(),Lt=nt.box,kt=nt.content;jc([Lt,kt],0)}h=function(){var Mt;if(!(!y.state.isVisible||l)){if(l=!0,_.offsetHeight,_.style.transition=y.props.moveTransition,X()&&y.props.animation){var kr=L(),un=kr.box,cr=kr.content;jc([un,cr],me),B0([un,cr],"visible")}w(),k(),y0(eA,y),(Mt=y.popperInstance)==null||Mt.forceUpdate(),R("onMount",[y]),y.props.animation&&X()&&be(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=qc(y.props.duration,1,li.duration);if(!($||ae||ue)&&(R("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,l=!1,o=!1,X()&&(_.style.visibility="hidden"),K(),fe(),q(!0),X()){var me=L(),nt=me.box,Lt=me.content;y.props.animation&&(jc([nt,Lt],ve),B0([nt,Lt],"hidden"))}w(),k(),y.props.animation?X()&&we(ve,y.unmount):y.unmount()}}function N($){oe().addEventListener("mousemove",f),y0(ra,f),f($)}function J(){y.state.isVisible&&y.hide(),y.state.isMounted&&(Xe(),$e().forEach(function($){$._tippy.unmount()}),_.parentNode&&_.parentNode.removeChild(_),eA=eA.filter(function($){return $!==y}),y.state.isMounted=!1,R("onHidden",[y]))}function z(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Ne(),delete i._tippy,y.state.isDestroyed=!0,R("onDestroy",[y]))}}function _r(i,e){e===void 0&&(e={});var t=li.plugins.concat(e.plugins||[]);Dx();var r=Object.assign({},e,{plugins:t}),n=xx(i),s=n.reduce(function(o,a){var c=a&&$x(a,r);return c&&o.push(c),o},[]);return ia(i)?s[0]:s}_r.defaultProps=li,_r.setDefaultProps=Nx,_r.currentInput=Bi,Object.assign({},Zg,{effect:function(e){var t=e.state,r={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(t.elements.popper.style,r.popper),t.styles=r,t.elements.arrow&&Object.assign(t.elements.arrow.style,r.arrow)}}),_r.setDefaultProps({render:R0});function ri(i,e){return`${i}-${e}`}function Ti(i){var e,t;const r=[];return(((e=i.renderer)==null?void 0:e.type)==="video"||((t=i.renderer)==null?void 0:t.type)==="audio")&&r.push({...i.config,...i.options}),r.push(...i.childNodes.flatMap(Ti).filter(Boolean)),r}class na extends Error{constructor(e,t=new Error,r=!1){super(),this.fatal=!1,this.fatal=r,this.stack=t.stack,this.message=[e,t.message].filter(Boolean).join(" - ")}}function or(i,e,t){return Math.min(Math.max(e,i),t)}const Hx=5;function Yx(i,e){return i.length!==e.length||i.some((t,r)=>t!==e[r])}class Vx{constructor(e){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._canvas=xt(),this._controls=xt(),this.host=e}set activeScenes(e){Yx(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,r,n;const s=or(0,e,this.host.duration);this.activeScenes=((t=this.host.composition)==null?void 0:t.tracks.reduce((a,c)=>a.concat(c.scenes.filter(({start:l,duration:u})=>s>=l&&s<l+u)),[]))??[];const o=s!==this.currentTime;this._currentTime=s,this._upcomingScenes=((r=this.host.composition)==null?void 0:r.tracks.reduce((a,c)=>a.concat(c.scenes.filter(({start:l})=>s>=l-Hx&&s<l)),[]))??[],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=>{Ti(e.layout.node).forEach(({key:r})=>{var n,s,o;const{id:a,start:c,duration:l}=e,u=this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused,A=ri(a,r);if(this.host.media[A]){const h=this.host.media[A],{speed:d,volume:f,hls:g,node:p,start:v,duration:B}=h,C=this.host.mediaState[A];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=or(0,this.host.volume*(f??1),1),p.playbackRate=or(.1,this.host.playbackRate*(d??1),4)))}else if(u){const h=`${c}-${l}`,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,c/this.host.duration*100),end:Math.min((c+l)/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(r=>Ti(r.layout.node).map(async({key:s})=>{const o=ri(r.id,s);if(this.host.media[o]){const a=this.host.media[o],{node:c}=a,l=this.host.mediaState[o];if(!this.activeScenes.includes(r))c.paused||c.pause();else if(l&&!this.host.waiting&&!this.host.loading&&!this.host.paused&&c.paused&&l.initialised)try{await c.play()}catch(A){throw new na("Video play error",A,!0)}}}))))??[])}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 Kx=Ir(async function(e){const{weight:t,family:r}=e,{client:n,server:s}=r.weights.find(a=>a.weight===t)??{};return!n&&!s?null:new FontFace(e.family.name,`url(${n??s})`,{weight:t,style:"normal"}).load()},{cacheKey:([i])=>JSON.stringify(i)}),Wx=Ir(async({options:i})=>{const e=await Kx(i.font);return e&&document.fonts.add(e),{font:i.font}}),qx=Ir(async({config:i})=>i.src?new Promise((e,t)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{e({image:r})},r.onerror=n=>{t(n)},r.src=i.src}):{image:null},{cacheKey:([{config:i}])=>JSON.stringify(i)});async function tA(i){return i.duration===1/0?new Promise(e=>{i.currentTime=Number.MAX_SAFE_INTEGER,i.ontimeupdate=()=>{i.ontimeupdate=null,e(i.duration),i.currentTime=0}}):i.duration}function Jx(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function jx(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function Xx({config:i,elementSize:e}){return new Promise(async t=>{let r=null;const{type:n,key:s,src:o,duration:a}=i;n==="video"?(r=document.createElement("video"),r.playsInline=!0,e&&(r.width=e.width,r.height=e.height)):r=document.createElement("audio"),r.muted=!0,r.loop=!1,r.crossOrigin="anonymous",r.src=o;let c=!1;if(r.startLoadOnce=()=>{c||(r.preload="auto",r.load(),c=!0)},n==="video"&&a&&i.aspectRatio)r.preload="none",t({key:s,hls:null,node:r,aspectRatio:i.aspectRatio,totalDuration:a});else{r.preload="metadata";const l=async()=>{const u=await tA(r),A=r instanceof HTMLVideoElement&&r.videoHeight>0?r.videoWidth/r.videoHeight:null;t({key:s,hls:null,node:r,totalDuration:u,aspectRatio:A}),r.removeEventListener("loadedmetadata",l)};r.addEventListener("loadedmetadata",l)}})}function zx({key:i,playlist:e,duration:t,elementSize:r}){return new Promise(n=>{const s=document.createElement("video");s instanceof HTMLVideoElement&&(r&&(s.width=r.width,s.height=r.height),s.playsInline=!0),s.muted=!0,s.loop=!1,s.crossOrigin="anonymous";let o=!1,a=!1,c=!1;const l=new Zt({autoStartLoad:!0,capLevelToPlayerSize:!1,xhrSetup:u=>{const{open:A}=u,h=e.split("?")[1];u.open=function(d,f,g){if(h&&!f.toString().includes("?")&&(f+="?"+h),!o&&f.toString().includes(".ts")){if(a)return;a=!0}A.apply(this,[d,f,g])}}});l.on(Zt.Events.BUFFER_CODECS,async(u,A)=>{var h,d;if(c)return;const f=A.video,g=(h=f==null?void 0:f.metadata)==null?void 0:h.width,p=(d=f==null?void 0:f.metadata)==null?void 0:d.height;if(g&&p){c=!0,o||l==null||l.stopLoad();const v=t??await tA(s);n({key:i,hls:l,node:s,aspectRatio:g/p,totalDuration:v})}}),l.on(Zt.Events.LEVEL_LOADED,async()=>{setTimeout(async()=>{if(c)return;c=!0,o||l==null||l.stopLoad();const u=t??await tA(s),A=l.levels[l.levels.length-1];n({key:i,hls:l,node:s,aspectRatio:A.width/A.height,totalDuration:u})},2e3)}),r&&l.on(Zt.Events.MANIFEST_PARSED,()=>{const u=window.devicePixelRatio||1,A=Math.min(r.width,r.height)*u;let h=0;for(let d=l.levels.length-1;d>=0;d--)if(Math.min(l.levels[d].width,l.levels[d].height)<=A){h=d;break}l.autoLevelCapping=h}),l.loadSource(e),l.attachMedia(s),l.startLoadOnce=(u=-1,A)=>{if(l&&!o){const h=l.levels.findIndex(d=>Math.min(d.height,d.width)===A);o=!0,l.startLoad(u),h!==-1&&(l.currentLevel=h)}}})}function Zx({config:i,elementSize:e}){const{playlist:t}=i;return t&&!Jx()&&Zt.isSupported()?zx({key:i.key,playlist:t,duration:i.duration??0,elementSize:e}):Xx({config:i,elementSize:e})}let eQ=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 r=new AbortController,n=setTimeout(()=>{r.signal.aborted||(this.host._processing=!0)},t);return r.signal.addEventListener("abort",()=>{clearTimeout(n)}),r},this._mediaFactory=Ir(async(t,r)=>{var n,s,o,a;const{key:c}=r,l=((s=(n=this.host.shadowRoot)==null?void 0:n.host)==null?void 0:s.clientWidth)??0,u=((a=(o=this.host.shadowRoot)==null?void 0:o.host)==null?void 0:a.clientHeight)??0,A=await Zx({config:r,elementSize:{width:l,height:u}}),h={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},d=Object.keys(h).reduce((f,g)=>{const p=g,v=h[p]({id:t,key:c,node:A.node});return f[p]=v,A.node.addEventListener(g,v),f},{});return{media:A,listeners:d,aspectRatio:A.aspectRatio,source:()=>A.node}},{cacheKey:([t,{key:r,src:n,playlist:s}])=>JSON.stringify({id:t,key:r,src:n==null?void 0:n.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._handleLoadedData=({id:t,key:r,node:n})=>()=>{const s=ri(t,r),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:r,node:n}})))},this._handleWaiting=({id:t,key:r,node:n})=>()=>{const s=ri(t,r),o=this.mediaState[s];o!=null&&o.initialised&&!(o!=null&&o.waiting)&&(this.mediaState={...this.mediaState,[s]:{...o,waiting:!0}},this.host.dispatchEvent(new CustomEvent("video:waiting",{detail:{id:t,key:r,node:n}})))},this._handleCanPlay=({id:t,key:r})=>()=>{const n=ri(t,r),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:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:seeking",{detail:{id:t,key:r,node:n}}))},this._handleSeeked=({id:t,key:r,node:n})=>()=>{const s=ri(t,r),o=this.mediaState[s];o!=null&&o.initialised&&(this.host.draw(),this.host.activeScenes.flatMap(a=>Ti(a.layout.node).map(({id:l})=>l)).includes(t)&&this.host.dispatchEvent(new CustomEvent("seeked",{detail:this.host.currentTime})),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:t,key:r,node:n}})))},this._handlePlay=({id:t,key:r,node:n})=>()=>{this.hasPlayed=!0,this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:t,key:r,node:n}}))},this._handlePlaying=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:t,key:r,node:n}}))},this._handlePause=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:t,key:r,node:n}}))},this._handleStalled=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:t,key:r,node:n}}))},this._handleTimeUpdate=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:t,key:r,node:n}}))},this._handleEnded=({id:t,key:r,node:n})=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:t,key:r,node:n}}))},this._handleError=({id:t,key:r,node:n})=>()=>{const s=new na(`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:r,node:n}}))},this._cleanupMedia=t=>{var r;const n=this.media[t];n&&(n.node.pause(),n.node.src="",(r=n.hls)==null||r.destroy(),Object.keys(n.listeners??{}).forEach(s=>{var o,a;if((o=this.media)!=null&&o[t]){const c=(a=n.listeners)==null?void 0:a[s];c&&n.node.removeEventListener(s,c)}}),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 ks(this.host,async([e,t,r,n])=>{var s,o;this._compositionController.abort(),this._compositionController=new AbortController;const a=this._compositionController,c=this._delayProcessing();try{if(this.host._errors=[],(!t||!this.host._languages.find(({value:l})=>t===l))&&(this.host._language=(s=this.host._languages[0])==null?void 0:s.value),e){const{width:l,height:u}=yl({aspectRatio:r,resolution:1080});try{(o=this.composition)==null||o.cleanup();const f=await od({debug:n,config:e,resolvers:{text:Wx,image:qx,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:l,rootHeight:u});if(a.signal.aborted)return;this.composition=f}catch(f){throw new na("Fatal composition error",f,!0)}this.duration=this.composition.duration;const A={...this.media},h={...this.mediaState},d=[];for(const f of this.composition.tracks)for(const g of f.scenes){const p=Ti(g.layout.node);for(const v of p){const{media:B,listeners:C}=await this._mediaFactory(g.id,v),y=ri(g.id,B.key);d.push(y);const x=(v.startOffset??0)*B.totalDuration,_=(1-(v.endOffset??0))*B.totalDuration;A[y]={...B,listeners:C,start:x,duration:_-x,speed:v.speed??1,volume:v.volume??1},h[y]={initialised:!B,waiting:!!B,...this.mediaState[y]}}}this.media=A,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(l){this.composition=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",{composed:!0,bubbles:!0,error:l,message:l.message}))}finally{c.abort(),this.host._processing=!1}},()=>[this.host.config,this.host.language,this.host.aspectRatio,this.host.debug])}_setMediaCurrentTime({time:e,scene:t}){const{id:r,layout:n,start:s}=t;Ti(n.node).forEach(({key:a})=>{const c=ri(r,a);if(this.media[c]){const l=this.media[c],u=(e-s)*l.speed;l.node.currentTime=or(l.start,u+l.start,l.start+l.duration)}})}setMediaCurrentTime(e){var t;(t=this.composition)==null||t.tracks.forEach(r=>{r.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 tQ(i){i.requestFullscreen?i.requestFullscreen():i.mozRequestFullScreen?i.mozRequestFullScreen():i.webkitRequestFullscreen?i.webkitRequestFullscreen():i.msRequestFullscreen&&i.msRequestFullscreen()}function iQ(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const iA=["progress","play-large","navigation","play","volume","current-time","duration","levels","speed","captions","fullscreen","preview"],rQ={id:"captions",event:"captions:click",label:"Closed Captions"},nQ={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},D0={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}]},sQ={id:"playbackRate",label:"Playback playbackRate",subItems:D0};class oQ extends jA{constructor(e){if(super(e),this.element=null,this.observer=void 0,e.type!==Nr.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)),Vi}}const rA=Or(oQ),aQ=dS(()=>{const i=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"}),r=new FontFace("Roobert Captions","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),n=Zh.map(s=>({load:!1,font:new FontFace(s.family,`url(${s.url})`,{style:s.style})}));return[{load:!0,font:i},{load:!0,font:e},{load:!0,font:t},{load:!0,font:r},...n]}),bi={"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"},lQ={colors:bi,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 ${bi["dark-100"]}`,medium:`0 .125rem .625rem ${bi["dark-100"]}`,large:`0 .25rem 1rem ${bi["dark-50"]}`,xl:`.25rem .25rem 1rem ${bi["dark-250"]}`,xxl:`0 .25rem 2rem ${bi["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${bi["dark-250"]}`,toolbar:`0 -.625rem .625rem ${bi["dark-50"]}`,text:`0 0 .25rem ${bi["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:bi["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},L0=AS(lQ,{delimiter:"-"}),cQ=Object.keys(L0).map(i=>En(`:host { --${i}: ${L0[i]}; }`)),Je=(i=>{const e=class extends i{firstUpdated(){aQ().forEach(({load:s,font:o})=>{document.fonts.add(o),s&&o.load()})}};return e.styles=[(i==null?void 0:i.styles)??[],cQ,pt`
2529
2529
  :host {
2530
2530
  font-family: var(--fontFamilies-sans);
2531
2531
  font-size: var(--fontSizes-medium);
@@ -2882,7 +2882,7 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
2882
2882
  height: 32px;
2883
2883
  width: 32px;
2884
2884
  }
2885
- `],an([te({type:Boolean})],lr.prototype,"active",2),an([te({type:String})],lr.prototype,"size",2),an([te({type:String})],lr.prototype,"rounded",2),an([te({type:String})],lr.prototype,"weight",2),an([te({type:String})],lr.prototype,"icon",2),lr=an([Ft("vmp-icon-button")],lr);var IQ=Object.defineProperty,vQ=Object.getOwnPropertyDescriptor,Si=(i,e,t,r)=>{for(var n=r>1?void 0:r?vQ(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&IQ(e,t,n),n};let Rr=class extends Je{constructor(){super(...arguments),this.disabled=!1,this.aspectRatio=1,this.dataResolver=Ql,this._currentTime=0,this._sceneController=new hQ(this),this._canvasRef=xt(),this._previewRef=xt(),this._previewTimeRef=xt(),this._handleScrubberMouseEnter=({detail:{x:i,y:e,elementLeft:t,elementRight:r}})=>{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(${or(t-a.left,i-a.left-o.width/2,r-a.left-o.width)}px, ${e-a.top-o.height-28}px, 0)`)}},this._handleScrubberMouseMove=({detail:{time:i,x:e,elementLeft:t,elementRight:r}})=>{var n,s,o,a,c,l,u,A,h,d;if(this._currentTime=i,(o=(s=(n=this._sceneController.composition)==null?void 0:n.tracks)==null?void 0:s[0])!=null&&o.scenes){const f=(u=(l=(c=(a=this._sceneController.composition)==null?void 0:a.tracks)==null?void 0:c[0])==null?void 0:l.scenes)==null?void 0:u.find(({start:g,duration:p})=>i>=g&&i<=g+p);if(f&&Ti(f.layout.node).forEach(({key:p})=>{var v,B;const C=ii(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=i-f.start}}),this._draw(),(A=this._previewRef)!=null&&A.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(${or(t-p.left,e-p.left-g.width/2,r-p.left-g.width)}px, ${B[1]}px, 0)`}}this._previewTimeRef.value&&this._previewTimeRef.value.setAttribute("content",nA(Math.max(0,Math.min(this._currentTime,(d=this._sceneController.composition)==null?void 0:d.duration))))}},this._handleScrubberMouseLeave=()=>{var i;(i=this._previewRef)!=null&&i.value&&(this._previewRef.value.style.opacity="0")},this._handleScrubberResize=({detail:{y:i}})=>{var e,t;if((e=this._previewRef)!=null&&e.value){const r=this._previewRef.value.getBoundingClientRect(),n=(t=this._previewRef.value.getRootNode().host)==null?void 0:t.getBoundingClientRect();if(r&&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, ${i-n.top-r.height-28}px, 0)`}}}}_draw(i=this._currentTime){this._sceneController.composition&&this._canvasRef.value&&this._sceneController.composition.draw({canvas:this._canvasRef.value,currentTime:Math.max(0,Math.min(i,this._sceneController.composition.duration))})}connectedCallback(){super.connectedCallback();const i=ds("vmp-media-player",this);i==null||i.addEventListener("scrubber:resize",this._handleScrubberResize),i==null||i.addEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),i==null||i.addEventListener("scrubber:mousemove",this._handleScrubberMouseMove),i==null||i.addEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}disconnectedCallback(){super.disconnectedCallback();const i=ds("vmp-media-player",this);i==null||i.removeEventListener("scrubber:resize",this._handleScrubberResize),i==null||i.removeEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),i==null||i.removeEventListener("scrubber:mousemove",this._handleScrubberMouseMove),i==null||i.removeEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}render(){var i,e,t;const{height:r,width:n}=yl({resolution:180,aspectRatio:this.aspectRatio}),s=((t=(e=(i=this._sceneController.composition)==null?void 0:i.tracks)==null?void 0:e[0])==null?void 0:t.scenes.length)??0;return!this.disabled&&s>1?Te`
2885
+ `],an([te({type:Boolean})],lr.prototype,"active",2),an([te({type:String})],lr.prototype,"size",2),an([te({type:String})],lr.prototype,"rounded",2),an([te({type:String})],lr.prototype,"weight",2),an([te({type:String})],lr.prototype,"icon",2),lr=an([Ft("vmp-icon-button")],lr);var IQ=Object.defineProperty,vQ=Object.getOwnPropertyDescriptor,Si=(i,e,t,r)=>{for(var n=r>1?void 0:r?vQ(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&IQ(e,t,n),n};let Rr=class extends Je{constructor(){super(...arguments),this.disabled=!1,this.aspectRatio=1,this.dataResolver=Ql,this._currentTime=0,this._sceneController=new hQ(this),this._canvasRef=xt(),this._previewRef=xt(),this._previewTimeRef=xt(),this._handleScrubberMouseEnter=({detail:{x:i,y:e,elementLeft:t,elementRight:r}})=>{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(${or(t-a.left,i-a.left-o.width/2,r-a.left-o.width)}px, ${e-a.top-o.height-28}px, 0)`)}},this._handleScrubberMouseMove=({detail:{time:i,x:e,elementLeft:t,elementRight:r}})=>{var n,s,o,a,c,l,u,A,h,d;if(this._currentTime=i,(o=(s=(n=this._sceneController.composition)==null?void 0:n.tracks)==null?void 0:s[0])!=null&&o.scenes){const f=(u=(l=(c=(a=this._sceneController.composition)==null?void 0:a.tracks)==null?void 0:c[0])==null?void 0:l.scenes)==null?void 0:u.find(({start:g,duration:p})=>i>=g&&i<=g+p);if(f&&Ti(f.layout.node).forEach(({key:p})=>{var v,B;const C=ri(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=i-f.start}}),this._draw(),(A=this._previewRef)!=null&&A.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(${or(t-p.left,e-p.left-g.width/2,r-p.left-g.width)}px, ${B[1]}px, 0)`}}this._previewTimeRef.value&&this._previewTimeRef.value.setAttribute("content",nA(Math.max(0,Math.min(this._currentTime,(d=this._sceneController.composition)==null?void 0:d.duration))))}},this._handleScrubberMouseLeave=()=>{var i;(i=this._previewRef)!=null&&i.value&&(this._previewRef.value.style.opacity="0")},this._handleScrubberResize=({detail:{y:i}})=>{var e,t;if((e=this._previewRef)!=null&&e.value){const r=this._previewRef.value.getBoundingClientRect(),n=(t=this._previewRef.value.getRootNode().host)==null?void 0:t.getBoundingClientRect();if(r&&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, ${i-n.top-r.height-28}px, 0)`}}}}_draw(i=this._currentTime){this._sceneController.composition&&this._canvasRef.value&&this._sceneController.composition.draw({canvas:this._canvasRef.value,currentTime:Math.max(0,Math.min(i,this._sceneController.composition.duration))})}connectedCallback(){super.connectedCallback();const i=ds("vmp-media-player",this);i==null||i.addEventListener("scrubber:resize",this._handleScrubberResize),i==null||i.addEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),i==null||i.addEventListener("scrubber:mousemove",this._handleScrubberMouseMove),i==null||i.addEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}disconnectedCallback(){super.disconnectedCallback();const i=ds("vmp-media-player",this);i==null||i.removeEventListener("scrubber:resize",this._handleScrubberResize),i==null||i.removeEventListener("scrubber:mouseenter",this._handleScrubberMouseEnter),i==null||i.removeEventListener("scrubber:mousemove",this._handleScrubberMouseMove),i==null||i.removeEventListener("scrubber:mouseleave",this._handleScrubberMouseLeave)}render(){var i,e,t;const{height:r,width:n}=yl({resolution:180,aspectRatio:this.aspectRatio}),s=((t=(e=(i=this._sceneController.composition)==null?void 0:i.tracks)==null?void 0:e[0])==null?void 0:t.scenes.length)??0;return!this.disabled&&s>1?Te`
2886
2886
  <div
2887
2887
  ${Qt(this._previewRef)}
2888
2888
  class="preview"
@@ -3777,7 +3777,7 @@ Schedule: ${c.map(d=>nr(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
- `],Tt([te({type:Boolean})],ft.prototype,"loading",2),Tt([te({type:Boolean})],ft.prototype,"playing",2),Tt([te({type:Number})],ft.prototype,"volume",2),Tt([te({type:Boolean})],ft.prototype,"muted",2),Tt([te({type:Number})],ft.prototype,"currentTime",2),Tt([te({type:Number})],ft.prototype,"duration",2),Tt([te({type:Array})],ft.prototype,"languages",2),Tt([te({type:String})],ft.prototype,"language",2),Tt([te({type:Array,attribute:!1})],ft.prototype,"levels",2),Tt([te({type:Number})],ft.prototype,"level",2),Tt([te({type:Number})],ft.prototype,"playbackRate",2),Tt([te({type:String})],ft.prototype,"caption",2),Tt([te({type:Array})],ft.prototype,"buffer",2),Tt([te({type:Boolean})],ft.prototype,"captions",2),Tt([te({type:Boolean})],ft.prototype,"fullscreen",2),Tt([te({type:Array})],ft.prototype,"controls",2),Tt([ut()],ft.prototype,"showControls",2),ft=Tt([Ft("vmp-player-overlay")],ft);var $Q=Object.defineProperty,HQ=Object.getOwnPropertyDescriptor,ct=(i,e,t,r)=>{for(var n=r>1?void 0:r?HQ(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&$Q(e,t,n),n};const YQ=1e3/60,VQ=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=Ql,this.languageResolver=CC,this._sceneController=new eQ(this),this._drawController=new Vx(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._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._playerRef=xt(),this._canvasRef=xt(),this._initialised=null,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{var i;if((i=this.shadowRoot)!=null&&i.host){const e=this.shadowRoot.host.clientWidth,t=this.shadowRoot.host.clientHeight;this.propAspectRatio||(this._aspectRatio=e/t),Object.values(this.media).forEach(({node:r})=>{r instanceof HTMLVideoElement&&(r.width=e,r.height=t)})}},this._handleCanvasResize=()=>{this.draw()},this._loop=()=>{this._endLoop(),this._pageHidden?this._seekerTimeout=setTimeout(this._seeker,YQ):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=(i=performance.now())=>{if(this.composition){if(this._waiting=this._drawController.activeScenes.some(({id:e,layout:t})=>Ti(t.node).some(({key:n})=>{const s=ii(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")),i-(this._lastTimestamp??0)>1e3/VQ){let e=this._drawController.currentTime;const t=(i-(this._lastTimestamp??i))/1e3*this.playbackRate;this.activeScenes.every(({id:n,layout:s},o)=>Ti(s.node).every(({key:c},l)=>{var u,A;const h=ii(n,c),d=this.media[h];return((A=(u=this._lastCurrentTime)==null?void 0:u[o])==null?void 0:A[l])!==d.node.currentTime}))&&(e+=t),this._lastCurrentTime=this.activeScenes.map(({id:n,layout:s})=>Ti(s.node).map(({key:a})=>{const c=ii(n,a);return this.media[c].node.currentTime})),this._drawController.currentTime=e,this._lastTimestamp=i}this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))}this.paused||this._loop()},this._handleError=i=>{this._errors=[...this.errors,i.error],i.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 playerElement(){return this._playerRef.value??null}get canvasElement(){return this._canvasRef.value??null}get initialised(){return this._initialised=this._initialised??new Promise(i=>{const e=setInterval(()=>{!!this.errors.find(r=>r.fatal)&&i(!1),!this.loading&&!this.processing&&this.composition&&this.duration>0&&i(!0)},500);setTimeout(()=>{clearInterval(e),i(!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(i){i!==this._paused&&(this._paused=i,this.requestUpdate(),this.dispatchEvent(new CustomEvent(i?"pause":"play")))}get paused(){return this._paused}set playbackRate(i){i!==this._playbackRate&&(this._playbackRate=i,Object.values(this.media).forEach(({node:e,speed:t})=>{e.playbackRate=or(.1,i*t,4)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:i})))}get playbackRate(){return this._playbackRate}set volume(i){const e=or(0,i,1);e!==this._volume&&(Object.values(this.media).forEach(({node:t,volume:r})=>{t.volume=e*r}),localStorage.setItem("vmp-player-volume/v2",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:i})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume/v2")??"1"))}set muted(i){Object.values(this.media).forEach(({node:e,volume:t})=>{e.muted=t===0||i}),i!==this._muted&&(this._muted=i,localStorage.setItem("vmp-player-muted/v2",i.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:i?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-player-muted/v2")==="true")}set videoResolution(i){i!==this._videoResolution&&(this._videoResolution=i,Object.values(this.media).forEach(({hls:e})=>{if(e){const t=e.levels.findIndex(r=>Math.min(r.height,r.width)===i);e.currentLevel=t??-1}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(i){i!==this._drawController.currentTime&&(this._drawController.currentTime=i,this._sceneController.setMediaCurrentTime(i))}get currentTime(){return this._drawController.currentTime}reset(i=0,e=!1){this._lastTimestamp=null,this._lastCurrentTime=null,this._drawController.currentTime=i,this._sceneController.setMediaCurrentTime(i),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:i})=>{i.pause()})}draw(i){return this._drawController.draw(i)}toggleFullscreen(i){i??this.fullscreen?iQ():this._playerRef.value&&tQ(this._playerRef.value)}connectedCallback(){var i;super.connectedCallback(),this.addEventListener("error",this._handleError),document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("visibilitychange",this._handleVisibilityChange),(i=this.shadowRoot)!=null&&i.host&&(this._observer=new ResizeObserver(this._handleContainerResize),this._observer.observe(this.shadowRoot.host))}willUpdate(i){i.has("propAspectRatio")&&(this._aspectRatio=this.propAspectRatio),i.has("propLanguage")&&(this._language=this.propLanguage)}updated(i){i.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize(),this.autoplay&&!this._sceneController.hasPlayed&&!this.processing&&i.get("_processing")&&this.play(),i.has("_processing")&&this.processing&&this.dispatchEvent(new CustomEvent("processing"))}disconnectedCallback(){var i,e;super.disconnectedCallback(),(i=this._observer)==null||i.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"?Te`
3780
+ `],Tt([te({type:Boolean})],ft.prototype,"loading",2),Tt([te({type:Boolean})],ft.prototype,"playing",2),Tt([te({type:Number})],ft.prototype,"volume",2),Tt([te({type:Boolean})],ft.prototype,"muted",2),Tt([te({type:Number})],ft.prototype,"currentTime",2),Tt([te({type:Number})],ft.prototype,"duration",2),Tt([te({type:Array})],ft.prototype,"languages",2),Tt([te({type:String})],ft.prototype,"language",2),Tt([te({type:Array,attribute:!1})],ft.prototype,"levels",2),Tt([te({type:Number})],ft.prototype,"level",2),Tt([te({type:Number})],ft.prototype,"playbackRate",2),Tt([te({type:String})],ft.prototype,"caption",2),Tt([te({type:Array})],ft.prototype,"buffer",2),Tt([te({type:Boolean})],ft.prototype,"captions",2),Tt([te({type:Boolean})],ft.prototype,"fullscreen",2),Tt([te({type:Array})],ft.prototype,"controls",2),Tt([ut()],ft.prototype,"showControls",2),ft=Tt([Ft("vmp-player-overlay")],ft);var $Q=Object.defineProperty,HQ=Object.getOwnPropertyDescriptor,ct=(i,e,t,r)=>{for(var n=r>1?void 0:r?HQ(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&$Q(e,t,n),n};const YQ=1e3/60,VQ=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=Ql,this.languageResolver=CC,this._sceneController=new eQ(this),this._drawController=new Vx(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._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._playerRef=xt(),this._canvasRef=xt(),this._initialised=null,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{var i;if((i=this.shadowRoot)!=null&&i.host){const e=this.shadowRoot.host.clientWidth,t=this.shadowRoot.host.clientHeight;if(e<=0||t<=0)return;this.propAspectRatio||(this._aspectRatio=e/t),Object.values(this.media).forEach(({node:r})=>{r instanceof HTMLVideoElement&&(r.width=e,r.height=t)}),this._updateHlsLevelCap(e,t)}},this._handleCanvasResize=()=>{this.draw()},this._loop=()=>{this._endLoop(),this._pageHidden?this._seekerTimeout=setTimeout(this._seeker,YQ):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=(i=performance.now())=>{if(this.composition){if(this._waiting=this._drawController.activeScenes.some(({id:e,layout:t})=>Ti(t.node).some(({key:n})=>{const s=ri(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")),i-(this._lastTimestamp??0)>1e3/VQ){let e=this._drawController.currentTime;const t=(i-(this._lastTimestamp??i))/1e3*this.playbackRate;this.activeScenes.every(({id:n,layout:s},o)=>Ti(s.node).every(({key:c},l)=>{var u,A;const h=ri(n,c),d=this.media[h];return((A=(u=this._lastCurrentTime)==null?void 0:u[o])==null?void 0:A[l])!==d.node.currentTime}))&&(e+=t),this._lastCurrentTime=this.activeScenes.map(({id:n,layout:s})=>Ti(s.node).map(({key:a})=>{const c=ri(n,a);return this.media[c].node.currentTime})),this._drawController.currentTime=e,this._lastTimestamp=i}this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))}this.paused||this._loop()},this._handleError=i=>{this._errors=[...this.errors,i.error],i.error.fatal&&this.pause()},this._handleFullscreenChange=()=>{var i;const e=!!(((i=this.shadowRoot)==null?void 0:i.fullscreenElement)??document.fullscreenElement===this),t=this._fullscreen;this._fullscreen=e,e?this._updateHlsLevelCap(window.screen.width,window.screen.height,!0):t&&requestAnimationFrame(()=>{var r;this._handleContainerResize(),(r=this.shadowRoot)!=null&&r.host&&this._updateHlsLevelCap(this.shadowRoot.host.clientWidth,this.shadowRoot.host.clientHeight,!0)})},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 playerElement(){return this._playerRef.value??null}get canvasElement(){return this._canvasRef.value??null}get initialised(){return this._initialised=this._initialised??new Promise(i=>{const e=setInterval(()=>{!!this.errors.find(r=>r.fatal)&&i(!1),!this.loading&&!this.processing&&this.composition&&this.duration>0&&i(!0)},500);setTimeout(()=>{clearInterval(e),i(!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(i){i!==this._paused&&(this._paused=i,this.requestUpdate(),this.dispatchEvent(new CustomEvent(i?"pause":"play")))}get paused(){return this._paused}set playbackRate(i){i!==this._playbackRate&&(this._playbackRate=i,Object.values(this.media).forEach(({node:e,speed:t})=>{e.playbackRate=or(.1,i*t,4)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:i})))}get playbackRate(){return this._playbackRate}set volume(i){const e=or(0,i,1);e!==this._volume&&(Object.values(this.media).forEach(({node:t,volume:r})=>{t.volume=e*r}),localStorage.setItem("vmp-player-volume/v2",e.toString()),this._volume=e,e>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:i})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-player-volume/v2")??"1"))}set muted(i){Object.values(this.media).forEach(({node:e,volume:t})=>{e.muted=t===0||i}),i!==this._muted&&(this._muted=i,localStorage.setItem("vmp-player-muted/v2",i.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:i?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-player-muted/v2")==="true")}get _hlsLevels(){for(const i of Object.values(this.media))if(i.hls&&i.hls.levels.length>0)return i.hls.levels;return[]}get _currentLevel(){if(this._videoResolution===-1)return-1;for(const i of Object.values(this.media))if(i.hls&&i.hls.levels.length>0)return i.hls.levels.findIndex(e=>Math.min(e.height,e.width)===this._videoResolution);return-1}set videoResolution(i){var e;i!==this._videoResolution&&(this._videoResolution=i,Object.values(this.media).forEach(({hls:t})=>{if(t)if(i===-1)t.nextLevel=-1;else{const r=t.levels.findIndex(n=>Math.min(n.height,n.width)===i);r!==-1&&(t.nextLevel=r,t.autoLevelCapping=r)}}),i===-1&&((e=this.shadowRoot)!=null&&e.host)&&this._updateHlsLevelCap(this.shadowRoot.host.clientWidth,this.shadowRoot.host.clientHeight),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(i){i!==this._drawController.currentTime&&(this._drawController.currentTime=i,this._sceneController.setMediaCurrentTime(i))}get currentTime(){return this._drawController.currentTime}_updateHlsLevelCap(i,e,t=!1){if(i<=0||e<=0||this._videoResolution!==-1)return;const r=window.devicePixelRatio||1,n=Math.min(i,e)*r;Object.values(this.media).forEach(({hls:s})=>{if(s&&s.levels.length>0){let o=0;for(let a=s.levels.length-1;a>=0;a--)if(Math.min(s.levels[a].width,s.levels[a].height)<=n){o=a;break}s.autoLevelCapping=o,t&&(s.nextLevel=o)}})}reset(i=0,e=!1){this._lastTimestamp=null,this._lastCurrentTime=null,this._drawController.currentTime=i,this._sceneController.setMediaCurrentTime(i),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:i})=>{i.pause()})}draw(i){return this._drawController.draw(i)}toggleFullscreen(i){i??this.fullscreen?iQ():this._playerRef.value&&tQ(this._playerRef.value)}connectedCallback(){var i;super.connectedCallback(),this.addEventListener("error",this._handleError),document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.addEventListener("visibilitychange",this._handleVisibilityChange),(i=this.shadowRoot)!=null&&i.host&&(this._observer=new ResizeObserver(this._handleContainerResize),this._observer.observe(this.shadowRoot.host))}willUpdate(i){i.has("propAspectRatio")&&(this._aspectRatio=this.propAspectRatio),i.has("propLanguage")&&(this._language=this.propLanguage)}updated(i){var e;i.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize(),this.autoplay&&!this._sceneController.hasPlayed&&!this.processing&&i.get("_processing")&&this.play(),i.has("_processing")&&this.processing&&this.dispatchEvent(new CustomEvent("processing")),i.has("_processing")&&!this.processing&&i.get("_processing")&&(e=this.shadowRoot)!=null&&e.host&&this._updateHlsLevelCap(this.shadowRoot.host.clientWidth,this.shadowRoot.host.clientHeight)}disconnectedCallback(){var i,e;super.disconnectedCallback(),(i=this._observer)==null||i.disconnect(),(e=this.composition)==null||e.cleanup(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.removeEventListener("visibilitychange",this._handleVisibilityChange)}_renderStyles(){return this.propAspectRatio?typeof this.propAspectRatio=="number"?Te`
3781
3781
  <style>
3782
3782
  :host {
3783
3783
  aspect-ratio: ${this.propAspectRatio};
@@ -3822,6 +3822,8 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3822
3822
  duration=${this.duration}
3823
3823
  .languages=${this.languages}
3824
3824
  .language=${this.language}
3825
+ .levels=${this._hlsLevels}
3826
+ level=${this._currentLevel}
3825
3827
  playbackRate=${this.playbackRate}
3826
3828
  caption=${this._drawController.caption}
3827
3829
  .controls=${n}
@@ -3830,7 +3832,7 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
3830
3832
  @play:click=${({detail:l})=>{e||(l?this.pause():(this.muted=this._manualMute,this.play()))}}
3831
3833
  @volume:click=${({detail:l})=>{this.muted=!l,this._manualMute=!l}}
3832
3834
  @language:click=${({detail:l})=>{this._language=l.value}}
3833
- @level:click=${({detail:l})=>{this.videoResolution=l.value.resolution}}
3835
+ @level:click=${({detail:l})=>{const u=l.value.resolution;this.videoResolution=typeof u=="number"?u:-1}}
3834
3836
  @playbackRate:click=${({detail:l})=>{this.playbackRate=l.value??1}}
3835
3837
  @captions:click=${()=>{this._captions=!this._captions}}
3836
3838
  @fullscreen:click=${()=>{this.toggleFullscreen()}}
@@ -4046,7 +4048,7 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
4046
4048
  aspectRatio=${this.aspectRatio}
4047
4049
  ></vouch-embed-player>
4048
4050
  </vouch-embed-dialog-overlay>
4049
- `}};Kt([te({type:String})],$t.prototype,"vouchId",2),Kt([te({type:String})],$t.prototype,"templateId",2),Kt([te({type:Array})],$t.prototype,"questions",2),Kt([te({type:String})],$t.prototype,"env",2),Kt([te({type:String})],$t.prototype,"apiKey",2),Kt([te({type:Boolean})],$t.prototype,"disableTracking",2),Kt([te({type:String})],$t.prototype,"trackingSource",2),Kt([te({type:Array})],$t.prototype,"controls",2),Kt([te({type:String})],$t.prototype,"preload",2),Kt([te({type:Boolean})],$t.prototype,"disableAutoplay",2),Kt([te({type:Number})],$t.prototype,"aspectRatio",2),Kt([ut()],$t.prototype,"open",2),$t=Kt([_s("vouch-embed-dialog-portal")],$t);var iw=Object.defineProperty,rw=Object.getOwnPropertyDescriptor,ri=(i,e,t,r)=>{for(var n=r>1?void 0:r?rw(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&iw(e,t,n),n};return bt.DialogEmbed=class extends xi{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="none",this.disableAutoplay=!1,this.aspectRatio=0,this._id=Ki(),this._handleRootClick=()=>{this.dispatchEvent(new CustomEvent("dialogembed:click",{detail:this._id,bubbles:!0,composed:!0}))}}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this._handleRootClick)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("click",this._handleRootClick)}render(){return Te`
4051
+ `}};Kt([te({type:String})],$t.prototype,"vouchId",2),Kt([te({type:String})],$t.prototype,"templateId",2),Kt([te({type:Array})],$t.prototype,"questions",2),Kt([te({type:String})],$t.prototype,"env",2),Kt([te({type:String})],$t.prototype,"apiKey",2),Kt([te({type:Boolean})],$t.prototype,"disableTracking",2),Kt([te({type:String})],$t.prototype,"trackingSource",2),Kt([te({type:Array})],$t.prototype,"controls",2),Kt([te({type:String})],$t.prototype,"preload",2),Kt([te({type:Boolean})],$t.prototype,"disableAutoplay",2),Kt([te({type:Number})],$t.prototype,"aspectRatio",2),Kt([ut()],$t.prototype,"open",2),$t=Kt([_s("vouch-embed-dialog-portal")],$t);var iw=Object.defineProperty,rw=Object.getOwnPropertyDescriptor,ni=(i,e,t,r)=>{for(var n=r>1?void 0:r?rw(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(e,t,n):o(n))||n);return r&&n&&iw(e,t,n),n};return bt.DialogEmbed=class extends xi{constructor(){super(...arguments),this.env="prod",this.apiKey="",this.disableTracking=!1,this.trackingSource="embedded_player",this.preload="none",this.disableAutoplay=!1,this.aspectRatio=0,this._id=Ki(),this._handleRootClick=()=>{this.dispatchEvent(new CustomEvent("dialogembed:click",{detail:this._id,bubbles:!0,composed:!0}))}}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this._handleRootClick)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("click",this._handleRootClick)}render(){return Te`
4050
4052
  <slot>
4051
4053
  <vmp-button size="large">Play</vmp-button>
4052
4054
  </slot>
@@ -4074,5 +4076,5 @@ Schedule: ${c.map(d=>nr(d))}`),u.length&&this.log(`Removed events ${u}`),this.pl
4074
4076
  width: fit-content;
4075
4077
  height: fit-content;
4076
4078
  }
4077
- `],ri([te({type:String})],bt.DialogEmbed.prototype,"vouchId",2),ri([te({type:String})],bt.DialogEmbed.prototype,"templateId",2),ri([te({type:Array})],bt.DialogEmbed.prototype,"questions",2),ri([te({type:String})],bt.DialogEmbed.prototype,"env",2),ri([te({type:String})],bt.DialogEmbed.prototype,"apiKey",2),ri([te({type:Boolean})],bt.DialogEmbed.prototype,"disableTracking",2),ri([te({type:String})],bt.DialogEmbed.prototype,"trackingSource",2),ri([te({type:Array})],bt.DialogEmbed.prototype,"controls",2),ri([te({type:String})],bt.DialogEmbed.prototype,"preload",2),ri([te({type:Boolean})],bt.DialogEmbed.prototype,"disableAutoplay",2),ri([te({type:Number})],bt.DialogEmbed.prototype,"aspectRatio",2),bt.DialogEmbed=ri([_s("vouch-embed-dialog")],bt.DialogEmbed),Object.defineProperty(bt,Symbol.toStringTag,{value:"Module"}),bt}({});
4079
+ `],ni([te({type:String})],bt.DialogEmbed.prototype,"vouchId",2),ni([te({type:String})],bt.DialogEmbed.prototype,"templateId",2),ni([te({type:Array})],bt.DialogEmbed.prototype,"questions",2),ni([te({type:String})],bt.DialogEmbed.prototype,"env",2),ni([te({type:String})],bt.DialogEmbed.prototype,"apiKey",2),ni([te({type:Boolean})],bt.DialogEmbed.prototype,"disableTracking",2),ni([te({type:String})],bt.DialogEmbed.prototype,"trackingSource",2),ni([te({type:Array})],bt.DialogEmbed.prototype,"controls",2),ni([te({type:String})],bt.DialogEmbed.prototype,"preload",2),ni([te({type:Boolean})],bt.DialogEmbed.prototype,"disableAutoplay",2),ni([te({type:Number})],bt.DialogEmbed.prototype,"aspectRatio",2),bt.DialogEmbed=ni([_s("vouch-embed-dialog")],bt.DialogEmbed),Object.defineProperty(bt,Symbol.toStringTag,{value:"Module"}),bt}({});
4078
4080
  //# sourceMappingURL=embed.iife.js.map