three-vr-player 0.3.0 → 0.4.0
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.
|
@@ -2,7 +2,7 @@ var ThreeVrPlayer=function(Gt){"use strict";/**
|
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2010-2023 Three.js Authors
|
|
4
4
|
* SPDX-License-Identifier: MIT
|
|
5
|
-
*/const qr="160",ri="",Mt="srgb",Ci="srgb-linear",jr="display-p3",Rs="display-p3-linear",Ms="linear",dt="srgb",Ls="rec709",Is="p3",Ko="300 es";class xn{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const n=this._listeners[e];if(n!==void 0){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let r=0,a=n.length;r<a;r++)n[r].call(this,e);e.target=null}}}const Nt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Qr=Math.PI/180,Zr=180/Math.PI;function is(){const s=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Nt[s&255]+Nt[s>>8&255]+Nt[s>>16&255]+Nt[s>>24&255]+"-"+Nt[e&255]+Nt[e>>8&255]+"-"+Nt[e>>16&15|64]+Nt[e>>24&255]+"-"+Nt[t&63|128]+Nt[t>>8&255]+"-"+Nt[t>>16&255]+Nt[t>>24&255]+Nt[i&255]+Nt[i>>8&255]+Nt[i>>16&255]+Nt[i>>24&255]).toLowerCase()}function Wt(s,e,t){return Math.max(e,Math.min(t,s))}function Td(s,e){return(s%e+e)%e}function Jr(s,e,t){return(1-t)*s+t*e}function Xo(s){return(s&s-1)===0&&s!==0}function ea(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function ns(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function Kt(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}class nt{constructor(e=0,t=0){nt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Wt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*i-a*n+e.x,this.y=r*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Xe{constructor(e,t,i,n,r,a,o,l,c){Xe.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c)}set(e,t,i,n,r,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=r,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],v=n[0],m=n[3],g=n[6],E=n[1],_=n[4],T=n[7],b=n[2],R=n[5],A=n[8];return r[0]=a*v+o*E+l*b,r[3]=a*m+o*_+l*R,r[6]=a*g+o*T+l*A,r[1]=c*v+h*E+u*b,r[4]=c*m+h*_+u*R,r[7]=c*g+h*T+u*A,r[2]=d*v+f*E+p*b,r[5]=d*m+f*_+p*R,r[8]=d*g+f*T+p*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*r*h+i*o*l+n*r*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*a-o*c,d=o*l-h*r,f=c*r-a*l,p=t*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/p;return e[0]=u*v,e[1]=(n*c-h*i)*v,e[2]=(o*i-n*a)*v,e[3]=d*v,e[4]=(h*t-n*l)*v,e[5]=(n*r-o*t)*v,e[6]=f*v,e[7]=(i*l-c*t)*v,e[8]=(a*t-i*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ta.makeScale(e,t)),this}rotate(e){return this.premultiply(ta.makeRotation(-e)),this}translate(e,t){return this.premultiply(ta.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const ta=new Xe;function Yo(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function Cs(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function Ad(){const s=Cs("canvas");return s.style.display="block",s}const qo={};function ss(s){s in qo||(qo[s]=!0,console.warn(s))}const jo=new Xe().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Qo=new Xe().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ws={[Ci]:{transfer:Ms,primaries:Ls,toReference:s=>s,fromReference:s=>s},[Mt]:{transfer:dt,primaries:Ls,toReference:s=>s.convertSRGBToLinear(),fromReference:s=>s.convertLinearToSRGB()},[Rs]:{transfer:Ms,primaries:Is,toReference:s=>s.applyMatrix3(Qo),fromReference:s=>s.applyMatrix3(jo)},[jr]:{transfer:dt,primaries:Is,toReference:s=>s.convertSRGBToLinear().applyMatrix3(Qo),fromReference:s=>s.applyMatrix3(jo).convertLinearToSRGB()}},bd=new Set([Ci,Rs]),st={enabled:!0,_workingColorSpace:Ci,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(s){if(!bd.has(s))throw new Error(`Unsupported working color space, "${s}".`);this._workingColorSpace=s},convert:function(s,e,t){if(this.enabled===!1||e===t||!e||!t)return s;const i=ws[e].toReference,n=ws[t].fromReference;return n(i(s))},fromWorkingColorSpace:function(s,e){return this.convert(s,this._workingColorSpace,e)},toWorkingColorSpace:function(s,e){return this.convert(s,e,this._workingColorSpace)},getPrimaries:function(s){return ws[s].primaries},getTransfer:function(s){return s===ri?Ms:ws[s].transfer}};function Sn(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function ia(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let yn;class Zo{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{yn===void 0&&(yn=Cs("canvas")),yn.width=e.width,yn.height=e.height;const i=yn.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),t=yn}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Cs("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let a=0;a<r.length;a++)r[a]=Sn(r[a]/255)*255;return i.putImageData(n,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(Sn(t[i]/255)*255):t[i]=Sn(t[i]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Rd=0;class Jo{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Rd++}),this.uuid=is(),this.data=e,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let r;if(Array.isArray(n)){r=[];for(let a=0,o=n.length;a<o;a++)n[a].isDataTexture?r.push(na(n[a].image)):r.push(na(n[a]))}else r=na(n);i.url=r}return t||(e.images[this.uuid]=i),i}}function na(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&s instanceof ImageBitmap?Zo.getDataURL(s):s.data?{data:Array.from(s.data),width:s.width,height:s.height,type:s.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let Md=0;class Xt extends xn{constructor(e=Xt.DEFAULT_IMAGE,t=Xt.DEFAULT_MAPPING,i=1001,n=1001,r=1006,a=1008,o=1023,l=1009,c=Xt.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Md++}),this.uuid=is(),this.name="",this.source=new Jo(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=r,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new nt(0,0),this.repeat=new nt(1,1),this.center=new nt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Xe,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof h=="string"?this.colorSpace=h:(ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===3001?Mt:ri),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case 1e3:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case 1e3:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Mt?3001:3e3}set encoding(e){ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===3001?Mt:ri}}Xt.DEFAULT_IMAGE=null,Xt.DEFAULT_MAPPING=300,Xt.DEFAULT_ANISOTROPY=1;class Ft{constructor(e=0,t=0,i=0,n=1){Ft.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*r,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*r,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*r,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,r;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],f=l[5],p=l[9],v=l[2],m=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-v)<.01&&Math.abs(p-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+v)<.1&&Math.abs(p+m)<.1&&Math.abs(c+f+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const _=(c+1)/2,T=(f+1)/2,b=(g+1)/2,R=(h+d)/4,A=(u+v)/4,C=(p+m)/4;return _>T&&_>b?_<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(_),n=R/i,r=A/i):T>b?T<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(T),i=R/n,r=C/n):b<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(b),i=A/r,n=C/r),this.set(i,n,r,t),this}let E=Math.sqrt((m-p)*(m-p)+(u-v)*(u-v)+(d-h)*(d-h));return Math.abs(E)<.001&&(E=1),this.x=(m-p)/E,this.y=(u-v)/E,this.z=(d-h)/E,this.w=Math.acos((c+f+g-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ld extends xn{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Ft(0,0,e,t),this.scissorTest=!1,this.viewport=new Ft(0,0,e,t);const n={width:e,height:t,depth:1};i.encoding!==void 0&&(ss("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),i.colorSpace=i.encoding===3001?Mt:ri),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},i),this.texture=new Xt(n,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=i.generateMipmaps,this.texture.internalFormat=i.internalFormat,this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}setSize(e,t,i=1){(this.width!==e||this.height!==t||this.depth!==i)&&(this.width=e,this.height=t,this.depth=i,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=i,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Jo(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class nn extends Ld{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class el extends Xt{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Id extends Xt{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class rs{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],u=i[n+3];const d=r[a+0],f=r[a+1],p=r[a+2],v=r[a+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=v;return}if(u!==v||l!==d||c!==f||h!==p){let m=1-o;const g=l*d+c*f+h*p+u*v,E=g>=0?1:-1,_=1-g*g;if(_>Number.EPSILON){const b=Math.sqrt(_),R=Math.atan2(b,g*E);m=Math.sin(m*R)/b,o=Math.sin(o*R)/b}const T=o*E;if(l=l*m+d*T,c=c*m+f*T,h=h*m+p*T,u=u*m+v*T,m===1-o){const b=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=b,c*=b,h*=b,u*=b}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,i,n,r,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],u=r[a],d=r[a+1],f=r[a+2],p=r[a+3];return e[t]=o*p+h*u+l*f-c*d,e[t+1]=l*p+h*d+c*u-o*f,e[t+2]=c*p+h*f+o*d-l*u,e[t+3]=h*p-o*u-l*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),u=o(r/2),d=l(i/2),f=l(n/2),p=l(r/2);switch(a){case"XYZ":this._x=d*h*u+c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u+d*f*p;break;case"YZX":this._x=d*h*u+c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u-d*f*p;break;case"XZY":this._x=d*h*u-c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u+d*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=i+o+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-l)*f,this._y=(r-c)*f,this._z=(a-n)*f}else if(i>o&&i>u){const f=2*Math.sqrt(1+i-o-u);this._w=(h-l)/f,this._x=.25*f,this._y=(n+a)/f,this._z=(r+c)/f}else if(o>u){const f=2*Math.sqrt(1+o-i-u);this._w=(r-c)/f,this._x=(n+a)/f,this._y=.25*f,this._z=(l+h)/f}else{const f=2*Math.sqrt(1+u-i-o);this._w=(a-n)/f,this._x=(r+c)/f,this._y=(l+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<Number.EPSILON?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Wt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-r*l,this._y=n*h+a*l+r*o-i*c,this._z=r*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-r*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,n=this._y,r=this._z,a=this._w;let o=a*e._w+i*e._x+n*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*a+t*this._w,this._x=f*i+t*this._x,this._y=f*n+t*this._y,this._z=f*r+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=a*u+this._w*d,this._x=i*u+this._x*d,this._y=n*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=Math.random(),t=Math.sqrt(1-e),i=Math.sqrt(e),n=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(t*Math.cos(n),i*Math.sin(r),i*Math.cos(r),t*Math.sin(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Q{constructor(e=0,t=0,i=0){Q.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(tl.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(tl.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,a=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-r*n),u=2*(r*i-a*t);return this.x=t+l*c+a*u-o*h,this.y=i+l*h+o*c-r*u,this.z=n+l*u+r*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-r*o,this.y=r*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return sa.copy(this).projectOnVector(e),this.sub(sa)}reflect(e){return this.sub(sa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Wt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,t=Math.random()*Math.PI*2,i=Math.sqrt(1-e**2);return this.x=i*Math.cos(t),this.y=i*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const sa=new Q,tl=new rs;class as{constructor(e=new Q(1/0,1/0,1/0),t=new Q(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(ui.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(ui.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=ui.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(i!==void 0){const r=i.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,ui):ui.fromBufferAttribute(r,a),ui.applyMatrix4(e.matrixWorld),this.expandByPoint(ui);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ds.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Ds.copy(i.boundingBox)),Ds.applyMatrix4(e.matrixWorld),this.union(Ds)}const n=e.children;for(let r=0,a=n.length;r<a;r++)this.expandByObject(n[r],t);return this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y||e.z<this.min.z||e.z>this.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y||e.max.z<this.min.z||e.min.z>this.max.z)}intersectsSphere(e){return this.clampPoint(e.center,ui),ui.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(os),Ps.subVectors(this.max,os),Tn.subVectors(e.a,os),An.subVectors(e.b,os),bn.subVectors(e.c,os),Wi.subVectors(An,Tn),Ki.subVectors(bn,An),sn.subVectors(Tn,bn);let t=[0,-Wi.z,Wi.y,0,-Ki.z,Ki.y,0,-sn.z,sn.y,Wi.z,0,-Wi.x,Ki.z,0,-Ki.x,sn.z,0,-sn.x,-Wi.y,Wi.x,0,-Ki.y,Ki.x,0,-sn.y,sn.x,0];return!ra(t,Tn,An,bn,Ps)||(t=[1,0,0,0,1,0,0,0,1],!ra(t,Tn,An,bn,Ps))?!1:(Fs.crossVectors(Wi,Ki),t=[Fs.x,Fs.y,Fs.z],ra(t,Tn,An,bn,Ps))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ui).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ui).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const wi=[new Q,new Q,new Q,new Q,new Q,new Q,new Q,new Q],ui=new Q,Ds=new as,Tn=new Q,An=new Q,bn=new Q,Wi=new Q,Ki=new Q,sn=new Q,os=new Q,Ps=new Q,Fs=new Q,rn=new Q;function ra(s,e,t,i,n){for(let r=0,a=s.length-3;r<=a;r+=3){rn.fromArray(s,r);const o=n.x*Math.abs(rn.x)+n.y*Math.abs(rn.y)+n.z*Math.abs(rn.z),l=e.dot(rn),c=t.dot(rn),h=i.dot(rn);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const Cd=new as,ls=new Q,aa=new Q;class oa{constructor(e=new Q,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):Cd.setFromPoints(e).getCenter(i);let n=0;for(let r=0,a=e.length;r<a;r++)n=Math.max(n,i.distanceToSquared(e[r]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ls.subVectors(e,this.center);const t=ls.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(ls,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(aa.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ls.copy(e.center).add(aa)),this.expandByPoint(ls.copy(e.center).sub(aa))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Di=new Q,la=new Q,Os=new Q,Xi=new Q,ca=new Q,Us=new Q,ha=new Q;class wd{constructor(e=new Q,t=new Q(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Di)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Di.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Di.copy(this.origin).addScaledVector(this.direction,t),Di.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){la.copy(e).add(t).multiplyScalar(.5),Os.copy(t).sub(e).normalize(),Xi.copy(this.origin).sub(la);const r=e.distanceTo(t)*.5,a=-this.direction.dot(Os),o=Xi.dot(this.direction),l=-Xi.dot(Os),c=Xi.lengthSq(),h=Math.abs(1-a*a);let u,d,f,p;if(h>0)if(u=a*l-o,d=a*o-l,p=r*h,u>=0)if(d>=-p)if(d<=p){const v=1/h;u*=v,d*=v,f=u*(u+a*d+2*o)+d*(a*u+d+2*l)+c}else d=r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;else d=-r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;else d<=-p?(u=Math.max(0,-(-a*r+o)),d=u>0?-r:Math.min(Math.max(-r,-l),r),f=-u*u+d*(d+2*l)+c):d<=p?(u=0,d=Math.min(Math.max(-r,-l),r),f=d*(d+2*l)+c):(u=Math.max(0,-(a*r+o)),d=u>0?r:Math.min(Math.max(-r,-l),r),f=-u*u+d*(d+2*l)+c);else d=a>0?-r:r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(la).addScaledVector(Os,d),f}intersectSphere(e,t){Di.subVectors(e.center,this.origin);const i=Di.dot(this.direction),n=Di.dot(Di)-i*i,r=e.radius*e.radius;if(n>r)return null;const a=Math.sqrt(r-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,n=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,n=(e.min.x-d.x)*c),h>=0?(r=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),i>a||r>n||((r>i||isNaN(i))&&(i=r),(a<n||isNaN(n))&&(n=a),u>=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),i>l||o>n)||((o>i||i!==i)&&(i=o),(l<n||n!==n)&&(n=l),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,Di)!==null}intersectTriangle(e,t,i,n,r){ca.subVectors(t,e),Us.subVectors(i,e),ha.crossVectors(ca,Us);let a=this.direction.dot(ha),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Xi.subVectors(this.origin,e);const l=o*this.direction.dot(Us.crossVectors(Xi,Us));if(l<0)return null;const c=o*this.direction.dot(ca.cross(Xi));if(c<0||l+c>a)return null;const h=-o*Xi.dot(ha);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ot{constructor(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m){Ot.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m)}set(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=v,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ot().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,n=1/Rn.setFromMatrixColumn(e,0).length(),r=1/Rn.setFromMatrixColumn(e,1).length(),a=1/Rn.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,r=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const d=a*h,f=a*u,p=o*h,v=o*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=f+p*c,t[5]=d-v*c,t[9]=-o*l,t[2]=v-d*c,t[6]=p+f*c,t[10]=a*l}else if(e.order==="YXZ"){const d=l*h,f=l*u,p=c*h,v=c*u;t[0]=d+v*o,t[4]=p*o-f,t[8]=a*c,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=f*o-p,t[6]=v+d*o,t[10]=a*l}else if(e.order==="ZXY"){const d=l*h,f=l*u,p=c*h,v=c*u;t[0]=d-v*o,t[4]=-a*u,t[8]=p+f*o,t[1]=f+p*o,t[5]=a*h,t[9]=v-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const d=a*h,f=a*u,p=o*h,v=o*u;t[0]=l*h,t[4]=p*c-f,t[8]=d*c+v,t[1]=l*u,t[5]=v*c+d,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const d=a*l,f=a*c,p=o*l,v=o*c;t[0]=l*h,t[4]=v-d*u,t[8]=p*u+f,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=f*u+p,t[10]=d-v*u}else if(e.order==="XZY"){const d=a*l,f=a*c,p=o*l,v=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+v,t[5]=a*h,t[9]=f*u-p,t[2]=p*u-f,t[6]=o*h,t[10]=v*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Dd,e,Pd)}lookAt(e,t,i){const n=this.elements;return Zt.subVectors(e,t),Zt.lengthSq()===0&&(Zt.z=1),Zt.normalize(),Yi.crossVectors(i,Zt),Yi.lengthSq()===0&&(Math.abs(i.z)===1?Zt.x+=1e-4:Zt.z+=1e-4,Zt.normalize(),Yi.crossVectors(i,Zt)),Yi.normalize(),Ns.crossVectors(Zt,Yi),n[0]=Yi.x,n[4]=Ns.x,n[8]=Zt.x,n[1]=Yi.y,n[5]=Ns.y,n[9]=Zt.y,n[2]=Yi.z,n[6]=Ns.z,n[10]=Zt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],v=i[6],m=i[10],g=i[14],E=i[3],_=i[7],T=i[11],b=i[15],R=n[0],A=n[4],C=n[8],S=n[12],y=n[1],w=n[5],U=n[9],X=n[13],P=n[2],F=n[6],D=n[10],k=n[14],N=n[3],B=n[7],q=n[11],V=n[15];return r[0]=a*R+o*y+l*P+c*N,r[4]=a*A+o*w+l*F+c*B,r[8]=a*C+o*U+l*D+c*q,r[12]=a*S+o*X+l*k+c*V,r[1]=h*R+u*y+d*P+f*N,r[5]=h*A+u*w+d*F+f*B,r[9]=h*C+u*U+d*D+f*q,r[13]=h*S+u*X+d*k+f*V,r[2]=p*R+v*y+m*P+g*N,r[6]=p*A+v*w+m*F+g*B,r[10]=p*C+v*U+m*D+g*q,r[14]=p*S+v*X+m*k+g*V,r[3]=E*R+_*y+T*P+b*N,r[7]=E*A+_*w+T*F+b*B,r[11]=E*C+_*U+T*D+b*q,r[15]=E*S+_*X+T*k+b*V,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],f=e[14],p=e[3],v=e[7],m=e[11],g=e[15];return p*(+r*l*u-n*c*u-r*o*d+i*c*d+n*o*f-i*l*f)+v*(+t*l*f-t*c*d+r*a*d-n*a*f+n*c*h-r*l*h)+m*(+t*c*u-t*o*f-r*a*u+i*a*f+r*o*h-i*c*h)+g*(-n*o*h-t*l*u+t*o*d+n*a*u-i*a*d+i*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],v=e[13],m=e[14],g=e[15],E=u*m*c-v*d*c+v*l*f-o*m*f-u*l*g+o*d*g,_=p*d*c-h*m*c-p*l*f+a*m*f+h*l*g-a*d*g,T=h*v*c-p*u*c+p*o*f-a*v*f-h*o*g+a*u*g,b=p*u*l-h*v*l-p*o*d+a*v*d+h*o*m-a*u*m,R=t*E+i*_+n*T+r*b;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/R;return e[0]=E*A,e[1]=(v*d*r-u*m*r-v*n*f+i*m*f+u*n*g-i*d*g)*A,e[2]=(o*m*r-v*l*r+v*n*c-i*m*c-o*n*g+i*l*g)*A,e[3]=(u*l*r-o*d*r-u*n*c+i*d*c+o*n*f-i*l*f)*A,e[4]=_*A,e[5]=(h*m*r-p*d*r+p*n*f-t*m*f-h*n*g+t*d*g)*A,e[6]=(p*l*r-a*m*r-p*n*c+t*m*c+a*n*g-t*l*g)*A,e[7]=(a*d*r-h*l*r+h*n*c-t*d*c-a*n*f+t*l*f)*A,e[8]=T*A,e[9]=(p*u*r-h*v*r-p*i*f+t*v*f+h*i*g-t*u*g)*A,e[10]=(a*v*r-p*o*r+p*i*c-t*v*c-a*i*g+t*o*g)*A,e[11]=(h*o*r-a*u*r-h*i*c+t*u*c+a*i*f-t*o*f)*A,e[12]=b*A,e[13]=(h*v*n-p*u*n+p*i*d-t*v*d-h*i*m+t*u*m)*A,e[14]=(p*o*n-a*v*n-p*i*l+t*v*l+a*i*m-t*o*m)*A,e[15]=(a*u*n-h*o*n+h*i*l-t*u*l-a*i*d+t*o*d)*A,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),r=1-i,a=e.x,o=e.y,l=e.z,c=r*a,h=r*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,h*o+i,h*l-n*a,0,c*l-n*o,h*l+n*a,r*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,r,a){return this.set(1,i,r,0,e,1,a,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,a=t._y,o=t._z,l=t._w,c=r+r,h=a+a,u=o+o,d=r*c,f=r*h,p=r*u,v=a*h,m=a*u,g=o*u,E=l*c,_=l*h,T=l*u,b=i.x,R=i.y,A=i.z;return n[0]=(1-(v+g))*b,n[1]=(f+T)*b,n[2]=(p-_)*b,n[3]=0,n[4]=(f-T)*R,n[5]=(1-(d+g))*R,n[6]=(m+E)*R,n[7]=0,n[8]=(p+_)*A,n[9]=(m-E)*A,n[10]=(1-(d+v))*A,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;let r=Rn.set(n[0],n[1],n[2]).length();const a=Rn.set(n[4],n[5],n[6]).length(),o=Rn.set(n[8],n[9],n[10]).length();this.determinant()<0&&(r=-r),e.x=n[12],e.y=n[13],e.z=n[14],di.copy(this);const c=1/r,h=1/a,u=1/o;return di.elements[0]*=c,di.elements[1]*=c,di.elements[2]*=c,di.elements[4]*=h,di.elements[5]*=h,di.elements[6]*=h,di.elements[8]*=u,di.elements[9]*=u,di.elements[10]*=u,t.setFromRotationMatrix(di),i.x=r,i.y=a,i.z=o,this}makePerspective(e,t,i,n,r,a,o=2e3){const l=this.elements,c=2*r/(t-e),h=2*r/(i-n),u=(t+e)/(t-e),d=(i+n)/(i-n);let f,p;if(o===2e3)f=-(a+r)/(a-r),p=-2*a*r/(a-r);else if(o===2001)f=-a/(a-r),p=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=f,l[14]=p,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,i,n,r,a,o=2e3){const l=this.elements,c=1/(t-e),h=1/(i-n),u=1/(a-r),d=(t+e)*c,f=(i+n)*h;let p,v;if(o===2e3)p=(a+r)*u,v=-2*u;else if(o===2001)p=r*u,v=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-f,l[2]=0,l[6]=0,l[10]=v,l[14]=-p,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Rn=new Q,di=new Ot,Dd=new Q(0,0,0),Pd=new Q(1,1,1),Yi=new Q,Ns=new Q,Zt=new Q,il=new Ot,nl=new rs;class ks{constructor(e=0,t=0,i=0,n=ks.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,r=n[0],a=n[4],o=n[8],l=n[1],c=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(t){case"XYZ":this._y=Math.asin(Wt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Wt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Wt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-Wt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Wt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Wt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return il.makeRotationFromQuaternion(e),this.setFromRotationMatrix(il,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return nl.setFromEuler(this),this.setFromQuaternion(nl,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}ks.DEFAULT_ORDER="XYZ";class sl{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let Fd=0;const rl=new Q,Mn=new rs,Pi=new Ot,Bs=new Q,cs=new Q,Od=new Q,Ud=new rs,al=new Q(1,0,0),ol=new Q(0,1,0),ll=new Q(0,0,1),Nd={type:"added"},kd={type:"removed"};class Jt extends xn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Fd++}),this.uuid=is(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Jt.DEFAULT_UP.clone();const e=new Q,t=new ks,i=new rs,n=new Q(1,1,1);function r(){i.setFromEuler(t,!1)}function a(){t.setFromQuaternion(i,void 0,!1)}t._onChange(r),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new Ot},normalMatrix:{value:new Xe}}),this.matrix=new Ot,this.matrixWorld=new Ot,this.matrixAutoUpdate=Jt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Jt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new sl,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Mn.setFromAxisAngle(e,t),this.quaternion.multiply(Mn),this}rotateOnWorldAxis(e,t){return Mn.setFromAxisAngle(e,t),this.quaternion.premultiply(Mn),this}rotateX(e){return this.rotateOnAxis(al,e)}rotateY(e){return this.rotateOnAxis(ol,e)}rotateZ(e){return this.rotateOnAxis(ll,e)}translateOnAxis(e,t){return rl.copy(e).applyQuaternion(this.quaternion),this.position.add(rl.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(al,e)}translateY(e){return this.translateOnAxis(ol,e)}translateZ(e){return this.translateOnAxis(ll,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pi.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?Bs.copy(e):Bs.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),cs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pi.lookAt(cs,Bs,this.up):Pi.lookAt(Bs,cs,this.up),this.quaternion.setFromRotationMatrix(Pi),n&&(Pi.extractRotation(n.matrixWorld),Mn.setFromRotationMatrix(Pi),this.quaternion.premultiply(Mn.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.parent!==null&&e.parent.remove(e),e.parent=this,this.children.push(e),e.dispatchEvent(Nd)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(kd)),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pi),this.add(e),e.updateWorldMatrix(!1,!0),this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const a=this.children[i].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,e,Od),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,Ud,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++){const r=t[i];(r.matrixWorldAutoUpdate===!0||e===!0)&&r.updateMatrixWorld(e)}}updateWorldMatrix(e,t){const i=this.parent;if(e===!0&&i!==null&&i.matrixWorldAutoUpdate===!0&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),t===!0){const n=this.children;for(let r=0,a=n.length;r<a;r++){const o=n[r];o.matrixWorldAutoUpdate===!0&&o.updateWorldMatrix(!1,!0)}}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.visibility=this._visibility,n.active=this._active,n.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),n.maxGeometryCount=this._maxGeometryCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),this.boundingBox!==null&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()}));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];r(e.shapes,u)}else r(e.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(r(e.materials,this.material[l]));n.material=o}else n.material=r(e.materials,this.material);if(this.children.length>0){n.children=[];for(let o=0;o<this.children.length;o++)n.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];n.animations.push(r(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),f=a(e.animations),p=a(e.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){const n=e.children[i];this.add(n.clone())}return this}}Jt.DEFAULT_UP=new Q(0,1,0),Jt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Jt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const fi=new Q,Fi=new Q,ua=new Q,Oi=new Q,Ln=new Q,In=new Q,cl=new Q,da=new Q,fa=new Q,pa=new Q;let Gs=!1;class pi{constructor(e=new Q,t=new Q,i=new Q){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),fi.subVectors(e,t),n.cross(fi);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){fi.subVectors(n,t),Fi.subVectors(i,t),ua.subVectors(e,t);const a=fi.dot(fi),o=fi.dot(Fi),l=fi.dot(ua),c=Fi.dot(Fi),h=Fi.dot(ua),u=a*c-o*o;if(u===0)return r.set(0,0,0),null;const d=1/u,f=(c*l-o*h)*d,p=(a*h-o*l)*d;return r.set(1-f-p,p,f)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,Oi)===null?!1:Oi.x>=0&&Oi.y>=0&&Oi.x+Oi.y<=1}static getUV(e,t,i,n,r,a,o,l){return Gs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),Gs=!0),this.getInterpolation(e,t,i,n,r,a,o,l)}static getInterpolation(e,t,i,n,r,a,o,l){return this.getBarycoord(e,t,i,n,Oi)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Oi.x),l.addScaledVector(a,Oi.y),l.addScaledVector(o,Oi.z),l)}static isFrontFacing(e,t,i,n){return fi.subVectors(i,t),Fi.subVectors(e,t),fi.cross(Fi).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return fi.subVectors(this.c,this.b),Fi.subVectors(this.a,this.b),fi.cross(Fi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(.3333333333333333)}getNormal(e){return pi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return pi.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,i,n,r){return Gs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),Gs=!0),pi.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}getInterpolation(e,t,i,n,r){return pi.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return pi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return pi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let a,o;Ln.subVectors(n,i),In.subVectors(r,i),da.subVectors(e,i);const l=Ln.dot(da),c=In.dot(da);if(l<=0&&c<=0)return t.copy(i);fa.subVectors(e,n);const h=Ln.dot(fa),u=In.dot(fa);if(h>=0&&u<=h)return t.copy(n);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(Ln,a);pa.subVectors(e,r);const f=Ln.dot(pa),p=In.dot(pa);if(p>=0&&f<=p)return t.copy(r);const v=f*c-l*p;if(v<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(In,o);const m=h*p-f*u;if(m<=0&&u-h>=0&&f-p>=0)return cl.subVectors(r,n),o=(u-h)/(u-h+(f-p)),t.copy(n).addScaledVector(cl,o);const g=1/(m+v+d);return a=v*g,o=d*g,t.copy(i).addScaledVector(Ln,a).addScaledVector(In,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const hl={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},qi={h:0,s:0,l:0},Vs={h:0,s:0,l:0};function ma(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<.16666666666666666?s+(e-s)*6*t:t<.5?e:t<.6666666666666666?s+(e-s)*6*(.6666666666666666-t):s}class rt{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,st.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=st.workingColorSpace){return this.r=e,this.g=t,this.b=i,st.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=st.workingColorSpace){if(e=Td(e,1),t=Wt(t,0,1),i=Wt(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,a=2*i-r;this.r=ma(a,r,e+.3333333333333333),this.g=ma(a,r,e),this.b=ma(a,r,e-.3333333333333333)}return st.toWorkingColorSpace(this,n),this}setStyle(e,t=Mt){function i(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=n[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mt){const i=hl[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Sn(e.r),this.g=Sn(e.g),this.b=Sn(e.b),this}copyLinearToSRGB(e){return this.r=ia(e.r),this.g=ia(e.g),this.b=ia(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mt){return st.fromWorkingColorSpace(kt.copy(this),e),Math.round(Wt(kt.r*255,0,255))*65536+Math.round(Wt(kt.g*255,0,255))*256+Math.round(Wt(kt.b*255,0,255))}getHexString(e=Mt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=st.workingColorSpace){st.fromWorkingColorSpace(kt.copy(this),t);const i=kt.r,n=kt.g,r=kt.b,a=Math.max(i,n,r),o=Math.min(i,n,r);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const u=a-o;switch(c=h<=.5?u/(a+o):u/(2-a-o),a){case i:l=(n-r)/u+(n<r?6:0);break;case n:l=(r-i)/u+2;break;case r:l=(i-n)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=st.workingColorSpace){return st.fromWorkingColorSpace(kt.copy(this),t),e.r=kt.r,e.g=kt.g,e.b=kt.b,e}getStyle(e=Mt){st.fromWorkingColorSpace(kt.copy(this),e);const t=kt.r,i=kt.g,n=kt.b;return e!==Mt?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(e,t,i){return this.getHSL(qi),this.setHSL(qi.h+e,qi.s+t,qi.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(qi),e.getHSL(Vs);const i=Jr(qi.h,Vs.h,t),n=Jr(qi.s,Vs.s,t),r=Jr(qi.l,Vs.l,t);return this.setHSL(i,n,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,r=e.elements;return this.r=r[0]*t+r[3]*i+r[6]*n,this.g=r[1]*t+r[4]*i+r[7]*n,this.b=r[2]*t+r[5]*i+r[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const kt=new rt;rt.NAMES=hl;let Bd=0;class Hs extends xn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Bd++}),this.uuid=is(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new rt(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(i.blending=this.blending),this.side!==0&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==204&&(i.blendSrc=this.blendSrc),this.blendDst!==205&&(i.blendDst=this.blendDst),this.blendEquation!==100&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(i.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=n(e.textures),a=n(e.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let r=0;r!==n;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class hs extends Hs{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new rt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const St=new Q,$s=new nt;class Ei{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=35044,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,r=this.itemSize;n<r;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)$s.fromBufferAttribute(this,t),$s.applyMatrix3(e),this.setXY(t,$s.x,$s.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyMatrix3(e),this.setXYZ(t,St.x,St.y,St.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyMatrix4(e),this.setXYZ(t,St.x,St.y,St.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyNormalMatrix(e),this.setXYZ(t,St.x,St.y,St.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.transformDirection(e),this.setXYZ(t,St.x,St.y,St.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=ns(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Kt(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ns(t,this.array)),t}setX(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ns(t,this.array)),t}setY(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=ns(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=ns(t,this.array)),t}setW(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array),n=Kt(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array),n=Kt(n,this.array),r=Kt(r,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}}class ul extends Ei{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class dl extends Ei{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class xi extends Ei{constructor(e,t,i){super(new Float32Array(e),t,i)}}let Gd=0;const ai=new Ot,ga=new Jt,Cn=new Q,ei=new as,us=new as,Lt=new Q;class ji extends xn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Gd++}),this.uuid=is(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Yo(e)?dl:ul)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const r=new Xe().getNormalMatrix(e);i.applyNormalMatrix(r),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return ai.makeRotationFromQuaternion(e),this.applyMatrix4(ai),this}rotateX(e){return ai.makeRotationX(e),this.applyMatrix4(ai),this}rotateY(e){return ai.makeRotationY(e),this.applyMatrix4(ai),this}rotateZ(e){return ai.makeRotationZ(e),this.applyMatrix4(ai),this}translate(e,t,i){return ai.makeTranslation(e,t,i),this.applyMatrix4(ai),this}scale(e,t,i){return ai.makeScale(e,t,i),this.applyMatrix4(ai),this}lookAt(e){return ga.lookAt(e),ga.updateMatrix(),this.applyMatrix4(ga.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Cn).negate(),this.translate(Cn.x,Cn.y,Cn.z),this}setFromPoints(e){const t=[];for(let i=0,n=e.length;i<n;i++){const r=e[i];t.push(r.x,r.y,r.z||0)}return this.setAttribute("position",new xi(t,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new as);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingBox.set(new Q(-1/0,-1/0,-1/0),new Q(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i<n;i++){const r=t[i];ei.setFromBufferAttribute(r),this.morphTargetsRelative?(Lt.addVectors(this.boundingBox.min,ei.min),this.boundingBox.expandByPoint(Lt),Lt.addVectors(this.boundingBox.max,ei.max),this.boundingBox.expandByPoint(Lt)):(this.boundingBox.expandByPoint(ei.min),this.boundingBox.expandByPoint(ei.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new oa);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingSphere.set(new Q,1/0);return}if(e){const i=this.boundingSphere.center;if(ei.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];us.setFromBufferAttribute(o),this.morphTargetsRelative?(Lt.addVectors(ei.min,us.min),ei.expandByPoint(Lt),Lt.addVectors(ei.max,us.max),ei.expandByPoint(Lt)):(ei.expandByPoint(us.min),ei.expandByPoint(us.max))}ei.getCenter(i);let n=0;for(let r=0,a=e.count;r<a;r++)Lt.fromBufferAttribute(e,r),n=Math.max(n,i.distanceToSquared(Lt));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)Lt.fromBufferAttribute(o,c),l&&(Cn.fromBufferAttribute(e,c),Lt.add(Cn)),n=Math.max(n,i.distanceToSquared(Lt))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.array,n=t.position.array,r=t.normal.array,a=t.uv.array,o=n.length/3;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Ei(new Float32Array(4*o),4));const l=this.getAttribute("tangent").array,c=[],h=[];for(let y=0;y<o;y++)c[y]=new Q,h[y]=new Q;const u=new Q,d=new Q,f=new Q,p=new nt,v=new nt,m=new nt,g=new Q,E=new Q;function _(y,w,U){u.fromArray(n,y*3),d.fromArray(n,w*3),f.fromArray(n,U*3),p.fromArray(a,y*2),v.fromArray(a,w*2),m.fromArray(a,U*2),d.sub(u),f.sub(u),v.sub(p),m.sub(p);const X=1/(v.x*m.y-m.x*v.y);isFinite(X)&&(g.copy(d).multiplyScalar(m.y).addScaledVector(f,-v.y).multiplyScalar(X),E.copy(f).multiplyScalar(v.x).addScaledVector(d,-m.x).multiplyScalar(X),c[y].add(g),c[w].add(g),c[U].add(g),h[y].add(E),h[w].add(E),h[U].add(E))}let T=this.groups;T.length===0&&(T=[{start:0,count:i.length}]);for(let y=0,w=T.length;y<w;++y){const U=T[y],X=U.start,P=U.count;for(let F=X,D=X+P;F<D;F+=3)_(i[F+0],i[F+1],i[F+2])}const b=new Q,R=new Q,A=new Q,C=new Q;function S(y){A.fromArray(r,y*3),C.copy(A);const w=c[y];b.copy(w),b.sub(A.multiplyScalar(A.dot(w))).normalize(),R.crossVectors(C,w);const X=R.dot(h[y])<0?-1:1;l[y*4]=b.x,l[y*4+1]=b.y,l[y*4+2]=b.z,l[y*4+3]=X}for(let y=0,w=T.length;y<w;++y){const U=T[y],X=U.start,P=U.count;for(let F=X,D=X+P;F<D;F+=3)S(i[F+0]),S(i[F+1]),S(i[F+2])}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new Ei(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new Q,r=new Q,a=new Q,o=new Q,l=new Q,c=new Q,h=new Q,u=new Q;if(e)for(let d=0,f=e.count;d<f;d+=3){const p=e.getX(d+0),v=e.getX(d+1),m=e.getX(d+2);n.fromBufferAttribute(t,p),r.fromBufferAttribute(t,v),a.fromBufferAttribute(t,m),h.subVectors(a,r),u.subVectors(n,r),h.cross(u),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,v),c.fromBufferAttribute(i,m),o.add(h),l.add(h),c.add(h),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(v,l.x,l.y,l.z),i.setXYZ(m,c.x,c.y,c.z)}else for(let d=0,f=t.count;d<f;d+=3)n.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,r),u.subVectors(n,r),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Lt.fromBufferAttribute(e,t),Lt.normalize(),e.setXYZ(t,Lt.x,Lt.y,Lt.z)}toNonIndexed(){function e(o,l){const c=o.array,h=o.itemSize,u=o.normalized,d=new c.constructor(l.length*h);let f=0,p=0;for(let v=0,m=l.length;v<m;v++){o.isInterleavedBufferAttribute?f=l[v]*o.data.stride+o.offset:f=l[v]*h;for(let g=0;g<h;g++)d[p++]=c[f++]}return new Ei(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ji,i=this.index.array,n=this.attributes;for(const o in n){const l=n[o],c=e(l,i);t.setAttribute(o,c)}const r=this.morphAttributes;for(const o in r){const l=[],c=r[o];for(let h=0,u=c.length;h<u;h++){const d=c[h],f=e(d,i);l.push(f)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const f=c[u];h.push(f.toJSON(e.data))}h.length>0&&(n[l]=h,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone(t));const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],u=r[c];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,h=a.length;c<h;c++){const u=a[c];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const fl=new Ot,an=new wd,zs=new oa,pl=new Q,wn=new Q,Dn=new Q,Pn=new Q,va=new Q,Ws=new Q,Ks=new nt,Xs=new nt,Ys=new nt,ml=new Q,gl=new Q,vl=new Q,qs=new Q,js=new Q;class mi extends Jt{constructor(e=new ji,t=new hs){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=n.length;r<a;r++){const o=n[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,r=i.morphAttributes.position,a=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const o=this.morphTargetInfluences;if(r&&o){Ws.set(0,0,0);for(let l=0,c=r.length;l<c;l++){const h=o[l],u=r[l];h!==0&&(va.fromBufferAttribute(u,e),a?Ws.addScaledVector(va,h):Ws.addScaledVector(va.sub(t),h))}t.add(Ws)}return t}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),zs.copy(i.boundingSphere),zs.applyMatrix4(r),an.copy(e.ray).recast(e.near),!(zs.containsPoint(an.origin)===!1&&(an.intersectSphere(zs,pl)===null||an.origin.distanceToSquared(pl)>(e.far-e.near)**2))&&(fl.copy(r).invert(),an.copy(e.ray).applyMatrix4(fl),!(i.boundingBox!==null&&an.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,an)))}_computeIntersections(e,t,i){let n;const r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,v=d.length;p<v;p++){const m=d[p],g=a[m.materialIndex],E=Math.max(m.start,f.start),_=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let T=E,b=_;T<b;T+=3){const R=o.getX(T),A=o.getX(T+1),C=o.getX(T+2);n=Qs(this,g,e,i,c,h,u,R,A,C),n&&(n.faceIndex=Math.floor(T/3),n.face.materialIndex=m.materialIndex,t.push(n))}}else{const p=Math.max(0,f.start),v=Math.min(o.count,f.start+f.count);for(let m=p,g=v;m<g;m+=3){const E=o.getX(m),_=o.getX(m+1),T=o.getX(m+2);n=Qs(this,a,e,i,c,h,u,E,_,T),n&&(n.faceIndex=Math.floor(m/3),t.push(n))}}else if(l!==void 0)if(Array.isArray(a))for(let p=0,v=d.length;p<v;p++){const m=d[p],g=a[m.materialIndex],E=Math.max(m.start,f.start),_=Math.min(l.count,Math.min(m.start+m.count,f.start+f.count));for(let T=E,b=_;T<b;T+=3){const R=T,A=T+1,C=T+2;n=Qs(this,g,e,i,c,h,u,R,A,C),n&&(n.faceIndex=Math.floor(T/3),n.face.materialIndex=m.materialIndex,t.push(n))}}else{const p=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let m=p,g=v;m<g;m+=3){const E=m,_=m+1,T=m+2;n=Qs(this,a,e,i,c,h,u,E,_,T),n&&(n.faceIndex=Math.floor(m/3),t.push(n))}}}}function Vd(s,e,t,i,n,r,a,o){let l;if(e.side===1?l=i.intersectTriangle(a,r,n,!0,o):l=i.intersectTriangle(n,r,a,e.side===0,o),l===null)return null;js.copy(o),js.applyMatrix4(s.matrixWorld);const c=t.ray.origin.distanceTo(js);return c<t.near||c>t.far?null:{distance:c,point:js.clone(),object:s}}function Qs(s,e,t,i,n,r,a,o,l,c){s.getVertexPosition(o,wn),s.getVertexPosition(l,Dn),s.getVertexPosition(c,Pn);const h=Vd(s,e,t,i,wn,Dn,Pn,qs);if(h){n&&(Ks.fromBufferAttribute(n,o),Xs.fromBufferAttribute(n,l),Ys.fromBufferAttribute(n,c),h.uv=pi.getInterpolation(qs,wn,Dn,Pn,Ks,Xs,Ys,new nt)),r&&(Ks.fromBufferAttribute(r,o),Xs.fromBufferAttribute(r,l),Ys.fromBufferAttribute(r,c),h.uv1=pi.getInterpolation(qs,wn,Dn,Pn,Ks,Xs,Ys,new nt),h.uv2=h.uv1),a&&(ml.fromBufferAttribute(a,o),gl.fromBufferAttribute(a,l),vl.fromBufferAttribute(a,c),h.normal=pi.getInterpolation(qs,wn,Dn,Pn,ml,gl,vl,new Q),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const u={a:o,b:l,c,normal:new Q,materialIndex:0};pi.getNormal(wn,Dn,Pn,u.normal),h.face=u}return h}class ds extends ji{constructor(e=1,t=1,i=1,n=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:a};const o=this;n=Math.floor(n),r=Math.floor(r),a=Math.floor(a);const l=[],c=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,t,e,a,r,0),p("z","y","x",1,-1,i,t,-e,a,r,1),p("x","z","y",1,1,e,i,t,n,a,2),p("x","z","y",1,-1,e,i,-t,n,a,3),p("x","y","z",1,-1,e,t,i,n,r,4),p("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(l),this.setAttribute("position",new xi(c,3)),this.setAttribute("normal",new xi(h,3)),this.setAttribute("uv",new xi(u,2));function p(v,m,g,E,_,T,b,R,A,C,S){const y=T/A,w=b/C,U=T/2,X=b/2,P=R/2,F=A+1,D=C+1;let k=0,N=0;const B=new Q;for(let q=0;q<D;q++){const V=q*w-X;for(let W=0;W<F;W++){const $=W*y-U;B[v]=$*E,B[m]=V*_,B[g]=P,c.push(B.x,B.y,B.z),B[v]=0,B[m]=0,B[g]=R>0?1:-1,h.push(B.x,B.y,B.z),u.push(W/A),u.push(1-q/C),k+=1}}for(let q=0;q<C;q++)for(let V=0;V<A;V++){const W=d+V+F*q,$=d+V+F*(q+1),ee=d+(V+1)+F*(q+1),ie=d+(V+1)+F*q;l.push(W,$,ie),l.push($,ee,ie),N+=6}o.addGroup(f,N,S),f+=N,d+=k}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ds(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Fn(s){const e={};for(const t in s){e[t]={};for(const i in s[t]){const n=s[t][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=n.clone():Array.isArray(n)?e[t][i]=n.slice():e[t][i]=n}}return e}function Vt(s){const e={};for(let t=0;t<s.length;t++){const i=Fn(s[t]);for(const n in i)e[n]=i[n]}return e}function Hd(s){const e=[];for(let t=0;t<s.length;t++)e.push(s[t].clone());return e}function _l(s){return s.getRenderTarget()===null?s.outputColorSpace:st.workingColorSpace}const $d={clone:Fn,merge:Vt};var zd=`void main() {
|
|
5
|
+
*/const qr="160",ri="",Mt="srgb",Ci="srgb-linear",jr="display-p3",Rs="display-p3-linear",Ms="linear",dt="srgb",Ls="rec709",Is="p3",Ko="300 es";class xn{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const n=this._listeners[e];if(n!==void 0){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let r=0,a=n.length;r<a;r++)n[r].call(this,e);e.target=null}}}const Nt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Qr=Math.PI/180,Zr=180/Math.PI;function is(){const s=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Nt[s&255]+Nt[s>>8&255]+Nt[s>>16&255]+Nt[s>>24&255]+"-"+Nt[e&255]+Nt[e>>8&255]+"-"+Nt[e>>16&15|64]+Nt[e>>24&255]+"-"+Nt[t&63|128]+Nt[t>>8&255]+"-"+Nt[t>>16&255]+Nt[t>>24&255]+Nt[i&255]+Nt[i>>8&255]+Nt[i>>16&255]+Nt[i>>24&255]).toLowerCase()}function Wt(s,e,t){return Math.max(e,Math.min(t,s))}function Td(s,e){return(s%e+e)%e}function Jr(s,e,t){return(1-t)*s+t*e}function Xo(s){return(s&s-1)===0&&s!==0}function ea(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function ns(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function Kt(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}class nt{constructor(e=0,t=0){nt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Wt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*i-a*n+e.x,this.y=r*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Xe{constructor(e,t,i,n,r,a,o,l,c){Xe.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c)}set(e,t,i,n,r,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=r,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],v=n[0],m=n[3],g=n[6],E=n[1],_=n[4],T=n[7],b=n[2],R=n[5],A=n[8];return r[0]=a*v+o*E+l*b,r[3]=a*m+o*_+l*R,r[6]=a*g+o*T+l*A,r[1]=c*v+h*E+u*b,r[4]=c*m+h*_+u*R,r[7]=c*g+h*T+u*A,r[2]=d*v+f*E+p*b,r[5]=d*m+f*_+p*R,r[8]=d*g+f*T+p*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*r*h+i*o*l+n*r*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*a-o*c,d=o*l-h*r,f=c*r-a*l,p=t*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/p;return e[0]=u*v,e[1]=(n*c-h*i)*v,e[2]=(o*i-n*a)*v,e[3]=d*v,e[4]=(h*t-n*l)*v,e[5]=(n*r-o*t)*v,e[6]=f*v,e[7]=(i*l-c*t)*v,e[8]=(a*t-i*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ta.makeScale(e,t)),this}rotate(e){return this.premultiply(ta.makeRotation(-e)),this}translate(e,t){return this.premultiply(ta.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const ta=new Xe;function Yo(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function Cs(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function Ad(){const s=Cs("canvas");return s.style.display="block",s}const qo={};function ss(s){s in qo||(qo[s]=!0,console.warn(s))}const jo=new Xe().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Qo=new Xe().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ws={[Ci]:{transfer:Ms,primaries:Ls,toReference:s=>s,fromReference:s=>s},[Mt]:{transfer:dt,primaries:Ls,toReference:s=>s.convertSRGBToLinear(),fromReference:s=>s.convertLinearToSRGB()},[Rs]:{transfer:Ms,primaries:Is,toReference:s=>s.applyMatrix3(Qo),fromReference:s=>s.applyMatrix3(jo)},[jr]:{transfer:dt,primaries:Is,toReference:s=>s.convertSRGBToLinear().applyMatrix3(Qo),fromReference:s=>s.applyMatrix3(jo).convertLinearToSRGB()}},bd=new Set([Ci,Rs]),st={enabled:!0,_workingColorSpace:Ci,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(s){if(!bd.has(s))throw new Error(`Unsupported working color space, "${s}".`);this._workingColorSpace=s},convert:function(s,e,t){if(this.enabled===!1||e===t||!e||!t)return s;const i=ws[e].toReference,n=ws[t].fromReference;return n(i(s))},fromWorkingColorSpace:function(s,e){return this.convert(s,this._workingColorSpace,e)},toWorkingColorSpace:function(s,e){return this.convert(s,e,this._workingColorSpace)},getPrimaries:function(s){return ws[s].primaries},getTransfer:function(s){return s===ri?Ms:ws[s].transfer}};function Sn(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function ia(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}let yn;class Zo{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{yn===void 0&&(yn=Cs("canvas")),yn.width=e.width,yn.height=e.height;const i=yn.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),t=yn}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Cs("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),r=n.data;for(let a=0;a<r.length;a++)r[a]=Sn(r[a]/255)*255;return i.putImageData(n,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(Sn(t[i]/255)*255):t[i]=Sn(t[i]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Rd=0;class Jo{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Rd++}),this.uuid=is(),this.data=e,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let r;if(Array.isArray(n)){r=[];for(let a=0,o=n.length;a<o;a++)n[a].isDataTexture?r.push(na(n[a].image)):r.push(na(n[a]))}else r=na(n);i.url=r}return t||(e.images[this.uuid]=i),i}}function na(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&s instanceof ImageBitmap?Zo.getDataURL(s):s.data?{data:Array.from(s.data),width:s.width,height:s.height,type:s.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let Md=0;class Xt extends xn{constructor(e=Xt.DEFAULT_IMAGE,t=Xt.DEFAULT_MAPPING,i=1001,n=1001,r=1006,a=1008,o=1023,l=1009,c=Xt.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Md++}),this.uuid=is(),this.name="",this.source=new Jo(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=r,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new nt(0,0),this.repeat=new nt(1,1),this.center=new nt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Xe,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof h=="string"?this.colorSpace=h:(ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===3001?Mt:ri),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case 1e3:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case 1e3:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Mt?3001:3e3}set encoding(e){ss("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===3001?Mt:ri}}Xt.DEFAULT_IMAGE=null,Xt.DEFAULT_MAPPING=300,Xt.DEFAULT_ANISOTROPY=1;class Ft{constructor(e=0,t=0,i=0,n=1){Ft.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*r,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*r,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*r,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,r;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],f=l[5],p=l[9],v=l[2],m=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-v)<.01&&Math.abs(p-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+v)<.1&&Math.abs(p+m)<.1&&Math.abs(c+f+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const _=(c+1)/2,T=(f+1)/2,b=(g+1)/2,R=(h+d)/4,A=(u+v)/4,C=(p+m)/4;return _>T&&_>b?_<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(_),n=R/i,r=A/i):T>b?T<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(T),i=R/n,r=C/n):b<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(b),i=A/r,n=C/r),this.set(i,n,r,t),this}let E=Math.sqrt((m-p)*(m-p)+(u-v)*(u-v)+(d-h)*(d-h));return Math.abs(E)<.001&&(E=1),this.x=(m-p)/E,this.y=(u-v)/E,this.z=(d-h)/E,this.w=Math.acos((c+f+g-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ld extends xn{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Ft(0,0,e,t),this.scissorTest=!1,this.viewport=new Ft(0,0,e,t);const n={width:e,height:t,depth:1};i.encoding!==void 0&&(ss("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),i.colorSpace=i.encoding===3001?Mt:ri),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},i),this.texture=new Xt(n,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=i.generateMipmaps,this.texture.internalFormat=i.internalFormat,this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}setSize(e,t,i=1){(this.width!==e||this.height!==t||this.depth!==i)&&(this.width=e,this.height=t,this.depth=i,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=i,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Jo(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class nn extends Ld{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class el extends Xt{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Id extends Xt{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class rs{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,r,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],u=i[n+3];const d=r[a+0],f=r[a+1],p=r[a+2],v=r[a+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=v;return}if(u!==v||l!==d||c!==f||h!==p){let m=1-o;const g=l*d+c*f+h*p+u*v,E=g>=0?1:-1,_=1-g*g;if(_>Number.EPSILON){const b=Math.sqrt(_),R=Math.atan2(b,g*E);m=Math.sin(m*R)/b,o=Math.sin(o*R)/b}const T=o*E;if(l=l*m+d*T,c=c*m+f*T,h=h*m+p*T,u=u*m+v*T,m===1-o){const b=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=b,c*=b,h*=b,u*=b}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,i,n,r,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],u=r[a],d=r[a+1],f=r[a+2],p=r[a+3];return e[t]=o*p+h*u+l*f-c*d,e[t+1]=l*p+h*d+c*u-o*f,e[t+2]=c*p+h*f+o*d-l*u,e[t+3]=h*p-o*u-l*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),u=o(r/2),d=l(i/2),f=l(n/2),p=l(r/2);switch(a){case"XYZ":this._x=d*h*u+c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u+d*f*p;break;case"YZX":this._x=d*h*u+c*f*p,this._y=c*f*u+d*h*p,this._z=c*h*p-d*f*u,this._w=c*h*u-d*f*p;break;case"XZY":this._x=d*h*u-c*f*p,this._y=c*f*u-d*h*p,this._z=c*h*p+d*f*u,this._w=c*h*u+d*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=i+o+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-l)*f,this._y=(r-c)*f,this._z=(a-n)*f}else if(i>o&&i>u){const f=2*Math.sqrt(1+i-o-u);this._w=(h-l)/f,this._x=.25*f,this._y=(n+a)/f,this._z=(r+c)/f}else if(o>u){const f=2*Math.sqrt(1+o-i-u);this._w=(r-c)/f,this._x=(n+a)/f,this._y=.25*f,this._z=(l+h)/f}else{const f=2*Math.sqrt(1+u-i-o);this._w=(a-n)/f,this._x=(r+c)/f,this._y=(l+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<Number.EPSILON?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Wt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-r*l,this._y=n*h+a*l+r*o-i*c,this._z=r*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-r*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,n=this._y,r=this._z,a=this._w;let o=a*e._w+i*e._x+n*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*a+t*this._w,this._x=f*i+t*this._x,this._y=f*n+t*this._y,this._z=f*r+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=a*u+this._w*d,this._x=i*u+this._x*d,this._y=n*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=Math.random(),t=Math.sqrt(1-e),i=Math.sqrt(e),n=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(t*Math.cos(n),i*Math.sin(r),i*Math.cos(r),t*Math.sin(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Q{constructor(e=0,t=0,i=0){Q.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(tl.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(tl.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,a=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-r*n),u=2*(r*i-a*t);return this.x=t+l*c+a*u-o*h,this.y=i+l*h+o*c-r*u,this.z=n+l*u+r*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-r*o,this.y=r*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return sa.copy(this).projectOnVector(e),this.sub(sa)}reflect(e){return this.sub(sa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Wt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,t=Math.random()*Math.PI*2,i=Math.sqrt(1-e**2);return this.x=i*Math.cos(t),this.y=i*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const sa=new Q,tl=new rs;class as{constructor(e=new Q(1/0,1/0,1/0),t=new Q(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(ui.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(ui.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=ui.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(i!==void 0){const r=i.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,ui):ui.fromBufferAttribute(r,a),ui.applyMatrix4(e.matrixWorld),this.expandByPoint(ui);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ds.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Ds.copy(i.boundingBox)),Ds.applyMatrix4(e.matrixWorld),this.union(Ds)}const n=e.children;for(let r=0,a=n.length;r<a;r++)this.expandByObject(n[r],t);return this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y||e.z<this.min.z||e.z>this.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y||e.max.z<this.min.z||e.min.z>this.max.z)}intersectsSphere(e){return this.clampPoint(e.center,ui),ui.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(os),Ps.subVectors(this.max,os),Tn.subVectors(e.a,os),An.subVectors(e.b,os),bn.subVectors(e.c,os),Wi.subVectors(An,Tn),Ki.subVectors(bn,An),sn.subVectors(Tn,bn);let t=[0,-Wi.z,Wi.y,0,-Ki.z,Ki.y,0,-sn.z,sn.y,Wi.z,0,-Wi.x,Ki.z,0,-Ki.x,sn.z,0,-sn.x,-Wi.y,Wi.x,0,-Ki.y,Ki.x,0,-sn.y,sn.x,0];return!ra(t,Tn,An,bn,Ps)||(t=[1,0,0,0,1,0,0,0,1],!ra(t,Tn,An,bn,Ps))?!1:(Fs.crossVectors(Wi,Ki),t=[Fs.x,Fs.y,Fs.z],ra(t,Tn,An,bn,Ps))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ui).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ui).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const wi=[new Q,new Q,new Q,new Q,new Q,new Q,new Q,new Q],ui=new Q,Ds=new as,Tn=new Q,An=new Q,bn=new Q,Wi=new Q,Ki=new Q,sn=new Q,os=new Q,Ps=new Q,Fs=new Q,rn=new Q;function ra(s,e,t,i,n){for(let r=0,a=s.length-3;r<=a;r+=3){rn.fromArray(s,r);const o=n.x*Math.abs(rn.x)+n.y*Math.abs(rn.y)+n.z*Math.abs(rn.z),l=e.dot(rn),c=t.dot(rn),h=i.dot(rn);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const Cd=new as,ls=new Q,aa=new Q;class oa{constructor(e=new Q,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):Cd.setFromPoints(e).getCenter(i);let n=0;for(let r=0,a=e.length;r<a;r++)n=Math.max(n,i.distanceToSquared(e[r]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ls.subVectors(e,this.center);const t=ls.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(ls,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(aa.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ls.copy(e.center).add(aa)),this.expandByPoint(ls.copy(e.center).sub(aa))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Di=new Q,la=new Q,Os=new Q,Xi=new Q,ca=new Q,Us=new Q,ha=new Q;class wd{constructor(e=new Q,t=new Q(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Di)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Di.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Di.copy(this.origin).addScaledVector(this.direction,t),Di.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){la.copy(e).add(t).multiplyScalar(.5),Os.copy(t).sub(e).normalize(),Xi.copy(this.origin).sub(la);const r=e.distanceTo(t)*.5,a=-this.direction.dot(Os),o=Xi.dot(this.direction),l=-Xi.dot(Os),c=Xi.lengthSq(),h=Math.abs(1-a*a);let u,d,f,p;if(h>0)if(u=a*l-o,d=a*o-l,p=r*h,u>=0)if(d>=-p)if(d<=p){const v=1/h;u*=v,d*=v,f=u*(u+a*d+2*o)+d*(a*u+d+2*l)+c}else d=r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;else d=-r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;else d<=-p?(u=Math.max(0,-(-a*r+o)),d=u>0?-r:Math.min(Math.max(-r,-l),r),f=-u*u+d*(d+2*l)+c):d<=p?(u=0,d=Math.min(Math.max(-r,-l),r),f=d*(d+2*l)+c):(u=Math.max(0,-(a*r+o)),d=u>0?r:Math.min(Math.max(-r,-l),r),f=-u*u+d*(d+2*l)+c);else d=a>0?-r:r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(la).addScaledVector(Os,d),f}intersectSphere(e,t){Di.subVectors(e.center,this.origin);const i=Di.dot(this.direction),n=Di.dot(Di)-i*i,r=e.radius*e.radius;if(n>r)return null;const a=Math.sqrt(r-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,n=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,n=(e.min.x-d.x)*c),h>=0?(r=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),i>a||r>n||((r>i||isNaN(i))&&(i=r),(a<n||isNaN(n))&&(n=a),u>=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),i>l||o>n)||((o>i||i!==i)&&(i=o),(l<n||n!==n)&&(n=l),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,Di)!==null}intersectTriangle(e,t,i,n,r){ca.subVectors(t,e),Us.subVectors(i,e),ha.crossVectors(ca,Us);let a=this.direction.dot(ha),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Xi.subVectors(this.origin,e);const l=o*this.direction.dot(Us.crossVectors(Xi,Us));if(l<0)return null;const c=o*this.direction.dot(ca.cross(Xi));if(c<0||l+c>a)return null;const h=-o*Xi.dot(ha);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ot{constructor(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m){Ot.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m)}set(e,t,i,n,r,a,o,l,c,h,u,d,f,p,v,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=v,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ot().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,n=1/Rn.setFromMatrixColumn(e,0).length(),r=1/Rn.setFromMatrixColumn(e,1).length(),a=1/Rn.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,r=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const d=a*h,f=a*u,p=o*h,v=o*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=f+p*c,t[5]=d-v*c,t[9]=-o*l,t[2]=v-d*c,t[6]=p+f*c,t[10]=a*l}else if(e.order==="YXZ"){const d=l*h,f=l*u,p=c*h,v=c*u;t[0]=d+v*o,t[4]=p*o-f,t[8]=a*c,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=f*o-p,t[6]=v+d*o,t[10]=a*l}else if(e.order==="ZXY"){const d=l*h,f=l*u,p=c*h,v=c*u;t[0]=d-v*o,t[4]=-a*u,t[8]=p+f*o,t[1]=f+p*o,t[5]=a*h,t[9]=v-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const d=a*h,f=a*u,p=o*h,v=o*u;t[0]=l*h,t[4]=p*c-f,t[8]=d*c+v,t[1]=l*u,t[5]=v*c+d,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const d=a*l,f=a*c,p=o*l,v=o*c;t[0]=l*h,t[4]=v-d*u,t[8]=p*u+f,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=f*u+p,t[10]=d-v*u}else if(e.order==="XZY"){const d=a*l,f=a*c,p=o*l,v=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+v,t[5]=a*h,t[9]=f*u-p,t[2]=p*u-f,t[6]=o*h,t[10]=v*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Dd,e,Pd)}lookAt(e,t,i){const n=this.elements;return Zt.subVectors(e,t),Zt.lengthSq()===0&&(Zt.z=1),Zt.normalize(),Yi.crossVectors(i,Zt),Yi.lengthSq()===0&&(Math.abs(i.z)===1?Zt.x+=1e-4:Zt.z+=1e-4,Zt.normalize(),Yi.crossVectors(i,Zt)),Yi.normalize(),Ns.crossVectors(Zt,Yi),n[0]=Yi.x,n[4]=Ns.x,n[8]=Zt.x,n[1]=Yi.y,n[5]=Ns.y,n[9]=Zt.y,n[2]=Yi.z,n[6]=Ns.z,n[10]=Zt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,r=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],v=i[6],m=i[10],g=i[14],E=i[3],_=i[7],T=i[11],b=i[15],R=n[0],A=n[4],C=n[8],S=n[12],y=n[1],w=n[5],N=n[9],Y=n[13],D=n[2],F=n[6],O=n[10],$=n[14],k=n[3],B=n[7],X=n[11],P=n[15];return r[0]=a*R+o*y+l*D+c*k,r[4]=a*A+o*w+l*F+c*B,r[8]=a*C+o*N+l*O+c*X,r[12]=a*S+o*Y+l*$+c*P,r[1]=h*R+u*y+d*D+f*k,r[5]=h*A+u*w+d*F+f*B,r[9]=h*C+u*N+d*O+f*X,r[13]=h*S+u*Y+d*$+f*P,r[2]=p*R+v*y+m*D+g*k,r[6]=p*A+v*w+m*F+g*B,r[10]=p*C+v*N+m*O+g*X,r[14]=p*S+v*Y+m*$+g*P,r[3]=E*R+_*y+T*D+b*k,r[7]=E*A+_*w+T*F+b*B,r[11]=E*C+_*N+T*O+b*X,r[15]=E*S+_*Y+T*$+b*P,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],r=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],f=e[14],p=e[3],v=e[7],m=e[11],g=e[15];return p*(+r*l*u-n*c*u-r*o*d+i*c*d+n*o*f-i*l*f)+v*(+t*l*f-t*c*d+r*a*d-n*a*f+n*c*h-r*l*h)+m*(+t*c*u-t*o*f-r*a*u+i*a*f+r*o*h-i*c*h)+g*(-n*o*h-t*l*u+t*o*d+n*a*u-i*a*d+i*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],v=e[13],m=e[14],g=e[15],E=u*m*c-v*d*c+v*l*f-o*m*f-u*l*g+o*d*g,_=p*d*c-h*m*c-p*l*f+a*m*f+h*l*g-a*d*g,T=h*v*c-p*u*c+p*o*f-a*v*f-h*o*g+a*u*g,b=p*u*l-h*v*l-p*o*d+a*v*d+h*o*m-a*u*m,R=t*E+i*_+n*T+r*b;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/R;return e[0]=E*A,e[1]=(v*d*r-u*m*r-v*n*f+i*m*f+u*n*g-i*d*g)*A,e[2]=(o*m*r-v*l*r+v*n*c-i*m*c-o*n*g+i*l*g)*A,e[3]=(u*l*r-o*d*r-u*n*c+i*d*c+o*n*f-i*l*f)*A,e[4]=_*A,e[5]=(h*m*r-p*d*r+p*n*f-t*m*f-h*n*g+t*d*g)*A,e[6]=(p*l*r-a*m*r-p*n*c+t*m*c+a*n*g-t*l*g)*A,e[7]=(a*d*r-h*l*r+h*n*c-t*d*c-a*n*f+t*l*f)*A,e[8]=T*A,e[9]=(p*u*r-h*v*r-p*i*f+t*v*f+h*i*g-t*u*g)*A,e[10]=(a*v*r-p*o*r+p*i*c-t*v*c-a*i*g+t*o*g)*A,e[11]=(h*o*r-a*u*r-h*i*c+t*u*c+a*i*f-t*o*f)*A,e[12]=b*A,e[13]=(h*v*n-p*u*n+p*i*d-t*v*d-h*i*m+t*u*m)*A,e[14]=(p*o*n-a*v*n-p*i*l+t*v*l+a*i*m-t*o*m)*A,e[15]=(a*u*n-h*o*n+h*i*l-t*u*l-a*i*d+t*o*d)*A,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),r=1-i,a=e.x,o=e.y,l=e.z,c=r*a,h=r*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,h*o+i,h*l-n*a,0,c*l-n*o,h*l+n*a,r*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,r,a){return this.set(1,i,r,0,e,1,a,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,a=t._y,o=t._z,l=t._w,c=r+r,h=a+a,u=o+o,d=r*c,f=r*h,p=r*u,v=a*h,m=a*u,g=o*u,E=l*c,_=l*h,T=l*u,b=i.x,R=i.y,A=i.z;return n[0]=(1-(v+g))*b,n[1]=(f+T)*b,n[2]=(p-_)*b,n[3]=0,n[4]=(f-T)*R,n[5]=(1-(d+g))*R,n[6]=(m+E)*R,n[7]=0,n[8]=(p+_)*A,n[9]=(m-E)*A,n[10]=(1-(d+v))*A,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;let r=Rn.set(n[0],n[1],n[2]).length();const a=Rn.set(n[4],n[5],n[6]).length(),o=Rn.set(n[8],n[9],n[10]).length();this.determinant()<0&&(r=-r),e.x=n[12],e.y=n[13],e.z=n[14],di.copy(this);const c=1/r,h=1/a,u=1/o;return di.elements[0]*=c,di.elements[1]*=c,di.elements[2]*=c,di.elements[4]*=h,di.elements[5]*=h,di.elements[6]*=h,di.elements[8]*=u,di.elements[9]*=u,di.elements[10]*=u,t.setFromRotationMatrix(di),i.x=r,i.y=a,i.z=o,this}makePerspective(e,t,i,n,r,a,o=2e3){const l=this.elements,c=2*r/(t-e),h=2*r/(i-n),u=(t+e)/(t-e),d=(i+n)/(i-n);let f,p;if(o===2e3)f=-(a+r)/(a-r),p=-2*a*r/(a-r);else if(o===2001)f=-a/(a-r),p=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=f,l[14]=p,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,i,n,r,a,o=2e3){const l=this.elements,c=1/(t-e),h=1/(i-n),u=1/(a-r),d=(t+e)*c,f=(i+n)*h;let p,v;if(o===2e3)p=(a+r)*u,v=-2*u;else if(o===2001)p=r*u,v=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-f,l[2]=0,l[6]=0,l[10]=v,l[14]=-p,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Rn=new Q,di=new Ot,Dd=new Q(0,0,0),Pd=new Q(1,1,1),Yi=new Q,Ns=new Q,Zt=new Q,il=new Ot,nl=new rs;class ks{constructor(e=0,t=0,i=0,n=ks.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,r=n[0],a=n[4],o=n[8],l=n[1],c=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(t){case"XYZ":this._y=Math.asin(Wt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Wt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Wt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-Wt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Wt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Wt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return il.makeRotationFromQuaternion(e),this.setFromRotationMatrix(il,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return nl.setFromEuler(this),this.setFromQuaternion(nl,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}ks.DEFAULT_ORDER="XYZ";class sl{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let Fd=0;const rl=new Q,Mn=new rs,Pi=new Ot,Bs=new Q,cs=new Q,Od=new Q,Ud=new rs,al=new Q(1,0,0),ol=new Q(0,1,0),ll=new Q(0,0,1),Nd={type:"added"},kd={type:"removed"};class Jt extends xn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Fd++}),this.uuid=is(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Jt.DEFAULT_UP.clone();const e=new Q,t=new ks,i=new rs,n=new Q(1,1,1);function r(){i.setFromEuler(t,!1)}function a(){t.setFromQuaternion(i,void 0,!1)}t._onChange(r),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new Ot},normalMatrix:{value:new Xe}}),this.matrix=new Ot,this.matrixWorld=new Ot,this.matrixAutoUpdate=Jt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Jt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new sl,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Mn.setFromAxisAngle(e,t),this.quaternion.multiply(Mn),this}rotateOnWorldAxis(e,t){return Mn.setFromAxisAngle(e,t),this.quaternion.premultiply(Mn),this}rotateX(e){return this.rotateOnAxis(al,e)}rotateY(e){return this.rotateOnAxis(ol,e)}rotateZ(e){return this.rotateOnAxis(ll,e)}translateOnAxis(e,t){return rl.copy(e).applyQuaternion(this.quaternion),this.position.add(rl.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(al,e)}translateY(e){return this.translateOnAxis(ol,e)}translateZ(e){return this.translateOnAxis(ll,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pi.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?Bs.copy(e):Bs.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),cs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pi.lookAt(cs,Bs,this.up):Pi.lookAt(Bs,cs,this.up),this.quaternion.setFromRotationMatrix(Pi),n&&(Pi.extractRotation(n.matrixWorld),Mn.setFromRotationMatrix(Pi),this.quaternion.premultiply(Mn.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.parent!==null&&e.parent.remove(e),e.parent=this,this.children.push(e),e.dispatchEvent(Nd)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(kd)),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pi),this.add(e),e.updateWorldMatrix(!1,!0),this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const a=this.children[i].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,e,Od),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,Ud,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++){const r=t[i];(r.matrixWorldAutoUpdate===!0||e===!0)&&r.updateMatrixWorld(e)}}updateWorldMatrix(e,t){const i=this.parent;if(e===!0&&i!==null&&i.matrixWorldAutoUpdate===!0&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),t===!0){const n=this.children;for(let r=0,a=n.length;r<a;r++){const o=n[r];o.matrixWorldAutoUpdate===!0&&o.updateWorldMatrix(!1,!0)}}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.visibility=this._visibility,n.active=this._active,n.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),n.maxGeometryCount=this._maxGeometryCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),this.boundingBox!==null&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()}));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];r(e.shapes,u)}else r(e.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(r(e.materials,this.material[l]));n.material=o}else n.material=r(e.materials,this.material);if(this.children.length>0){n.children=[];for(let o=0;o<this.children.length;o++)n.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];n.animations.push(r(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),f=a(e.animations),p=a(e.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){const n=e.children[i];this.add(n.clone())}return this}}Jt.DEFAULT_UP=new Q(0,1,0),Jt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Jt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const fi=new Q,Fi=new Q,ua=new Q,Oi=new Q,Ln=new Q,In=new Q,cl=new Q,da=new Q,fa=new Q,pa=new Q;let Gs=!1;class pi{constructor(e=new Q,t=new Q,i=new Q){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),fi.subVectors(e,t),n.cross(fi);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){fi.subVectors(n,t),Fi.subVectors(i,t),ua.subVectors(e,t);const a=fi.dot(fi),o=fi.dot(Fi),l=fi.dot(ua),c=Fi.dot(Fi),h=Fi.dot(ua),u=a*c-o*o;if(u===0)return r.set(0,0,0),null;const d=1/u,f=(c*l-o*h)*d,p=(a*h-o*l)*d;return r.set(1-f-p,p,f)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,Oi)===null?!1:Oi.x>=0&&Oi.y>=0&&Oi.x+Oi.y<=1}static getUV(e,t,i,n,r,a,o,l){return Gs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),Gs=!0),this.getInterpolation(e,t,i,n,r,a,o,l)}static getInterpolation(e,t,i,n,r,a,o,l){return this.getBarycoord(e,t,i,n,Oi)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Oi.x),l.addScaledVector(a,Oi.y),l.addScaledVector(o,Oi.z),l)}static isFrontFacing(e,t,i,n){return fi.subVectors(i,t),Fi.subVectors(e,t),fi.cross(Fi).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return fi.subVectors(this.c,this.b),Fi.subVectors(this.a,this.b),fi.cross(Fi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(.3333333333333333)}getNormal(e){return pi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return pi.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,i,n,r){return Gs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),Gs=!0),pi.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}getInterpolation(e,t,i,n,r){return pi.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return pi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return pi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let a,o;Ln.subVectors(n,i),In.subVectors(r,i),da.subVectors(e,i);const l=Ln.dot(da),c=In.dot(da);if(l<=0&&c<=0)return t.copy(i);fa.subVectors(e,n);const h=Ln.dot(fa),u=In.dot(fa);if(h>=0&&u<=h)return t.copy(n);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(Ln,a);pa.subVectors(e,r);const f=Ln.dot(pa),p=In.dot(pa);if(p>=0&&f<=p)return t.copy(r);const v=f*c-l*p;if(v<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(In,o);const m=h*p-f*u;if(m<=0&&u-h>=0&&f-p>=0)return cl.subVectors(r,n),o=(u-h)/(u-h+(f-p)),t.copy(n).addScaledVector(cl,o);const g=1/(m+v+d);return a=v*g,o=d*g,t.copy(i).addScaledVector(Ln,a).addScaledVector(In,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const hl={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},qi={h:0,s:0,l:0},Vs={h:0,s:0,l:0};function ma(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<.16666666666666666?s+(e-s)*6*t:t<.5?e:t<.6666666666666666?s+(e-s)*6*(.6666666666666666-t):s}class rt{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,st.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=st.workingColorSpace){return this.r=e,this.g=t,this.b=i,st.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=st.workingColorSpace){if(e=Td(e,1),t=Wt(t,0,1),i=Wt(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,a=2*i-r;this.r=ma(a,r,e+.3333333333333333),this.g=ma(a,r,e),this.b=ma(a,r,e-.3333333333333333)}return st.toWorkingColorSpace(this,n),this}setStyle(e,t=Mt){function i(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=n[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mt){const i=hl[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Sn(e.r),this.g=Sn(e.g),this.b=Sn(e.b),this}copyLinearToSRGB(e){return this.r=ia(e.r),this.g=ia(e.g),this.b=ia(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mt){return st.fromWorkingColorSpace(kt.copy(this),e),Math.round(Wt(kt.r*255,0,255))*65536+Math.round(Wt(kt.g*255,0,255))*256+Math.round(Wt(kt.b*255,0,255))}getHexString(e=Mt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=st.workingColorSpace){st.fromWorkingColorSpace(kt.copy(this),t);const i=kt.r,n=kt.g,r=kt.b,a=Math.max(i,n,r),o=Math.min(i,n,r);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const u=a-o;switch(c=h<=.5?u/(a+o):u/(2-a-o),a){case i:l=(n-r)/u+(n<r?6:0);break;case n:l=(r-i)/u+2;break;case r:l=(i-n)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=st.workingColorSpace){return st.fromWorkingColorSpace(kt.copy(this),t),e.r=kt.r,e.g=kt.g,e.b=kt.b,e}getStyle(e=Mt){st.fromWorkingColorSpace(kt.copy(this),e);const t=kt.r,i=kt.g,n=kt.b;return e!==Mt?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(e,t,i){return this.getHSL(qi),this.setHSL(qi.h+e,qi.s+t,qi.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(qi),e.getHSL(Vs);const i=Jr(qi.h,Vs.h,t),n=Jr(qi.s,Vs.s,t),r=Jr(qi.l,Vs.l,t);return this.setHSL(i,n,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,r=e.elements;return this.r=r[0]*t+r[3]*i+r[6]*n,this.g=r[1]*t+r[4]*i+r[7]*n,this.b=r[2]*t+r[5]*i+r[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const kt=new rt;rt.NAMES=hl;let Bd=0;class Hs extends xn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Bd++}),this.uuid=is(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new rt(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];if(n===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(i.blending=this.blending),this.side!==0&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==204&&(i.blendSrc=this.blendSrc),this.blendDst!==205&&(i.blendDst=this.blendDst),this.blendEquation!==100&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(i.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=n(e.textures),a=n(e.images);r.length>0&&(i.textures=r),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let r=0;r!==n;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class hs extends Hs{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new rt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const St=new Q,$s=new nt;class Ei{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=35044,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,r=this.itemSize;n<r;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)$s.fromBufferAttribute(this,t),$s.applyMatrix3(e),this.setXY(t,$s.x,$s.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyMatrix3(e),this.setXYZ(t,St.x,St.y,St.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyMatrix4(e),this.setXYZ(t,St.x,St.y,St.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.applyNormalMatrix(e),this.setXYZ(t,St.x,St.y,St.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)St.fromBufferAttribute(this,t),St.transformDirection(e),this.setXYZ(t,St.x,St.y,St.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=ns(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Kt(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ns(t,this.array)),t}setX(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ns(t,this.array)),t}setY(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=ns(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=ns(t,this.array)),t}setW(e,t){return this.normalized&&(t=Kt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array),n=Kt(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=Kt(t,this.array),i=Kt(i,this.array),n=Kt(n,this.array),r=Kt(r,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}}class ul extends Ei{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class dl extends Ei{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class xi extends Ei{constructor(e,t,i){super(new Float32Array(e),t,i)}}let Gd=0;const ai=new Ot,ga=new Jt,Cn=new Q,ei=new as,us=new as,Lt=new Q;class ji extends xn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Gd++}),this.uuid=is(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Yo(e)?dl:ul)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const r=new Xe().getNormalMatrix(e);i.applyNormalMatrix(r),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return ai.makeRotationFromQuaternion(e),this.applyMatrix4(ai),this}rotateX(e){return ai.makeRotationX(e),this.applyMatrix4(ai),this}rotateY(e){return ai.makeRotationY(e),this.applyMatrix4(ai),this}rotateZ(e){return ai.makeRotationZ(e),this.applyMatrix4(ai),this}translate(e,t,i){return ai.makeTranslation(e,t,i),this.applyMatrix4(ai),this}scale(e,t,i){return ai.makeScale(e,t,i),this.applyMatrix4(ai),this}lookAt(e){return ga.lookAt(e),ga.updateMatrix(),this.applyMatrix4(ga.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Cn).negate(),this.translate(Cn.x,Cn.y,Cn.z),this}setFromPoints(e){const t=[];for(let i=0,n=e.length;i<n;i++){const r=e[i];t.push(r.x,r.y,r.z||0)}return this.setAttribute("position",new xi(t,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new as);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingBox.set(new Q(-1/0,-1/0,-1/0),new Q(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i<n;i++){const r=t[i];ei.setFromBufferAttribute(r),this.morphTargetsRelative?(Lt.addVectors(this.boundingBox.min,ei.min),this.boundingBox.expandByPoint(Lt),Lt.addVectors(this.boundingBox.max,ei.max),this.boundingBox.expandByPoint(Lt)):(this.boundingBox.expandByPoint(ei.min),this.boundingBox.expandByPoint(ei.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new oa);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingSphere.set(new Q,1/0);return}if(e){const i=this.boundingSphere.center;if(ei.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];us.setFromBufferAttribute(o),this.morphTargetsRelative?(Lt.addVectors(ei.min,us.min),ei.expandByPoint(Lt),Lt.addVectors(ei.max,us.max),ei.expandByPoint(Lt)):(ei.expandByPoint(us.min),ei.expandByPoint(us.max))}ei.getCenter(i);let n=0;for(let r=0,a=e.count;r<a;r++)Lt.fromBufferAttribute(e,r),n=Math.max(n,i.distanceToSquared(Lt));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)Lt.fromBufferAttribute(o,c),l&&(Cn.fromBufferAttribute(e,c),Lt.add(Cn)),n=Math.max(n,i.distanceToSquared(Lt))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.array,n=t.position.array,r=t.normal.array,a=t.uv.array,o=n.length/3;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Ei(new Float32Array(4*o),4));const l=this.getAttribute("tangent").array,c=[],h=[];for(let y=0;y<o;y++)c[y]=new Q,h[y]=new Q;const u=new Q,d=new Q,f=new Q,p=new nt,v=new nt,m=new nt,g=new Q,E=new Q;function _(y,w,N){u.fromArray(n,y*3),d.fromArray(n,w*3),f.fromArray(n,N*3),p.fromArray(a,y*2),v.fromArray(a,w*2),m.fromArray(a,N*2),d.sub(u),f.sub(u),v.sub(p),m.sub(p);const Y=1/(v.x*m.y-m.x*v.y);isFinite(Y)&&(g.copy(d).multiplyScalar(m.y).addScaledVector(f,-v.y).multiplyScalar(Y),E.copy(f).multiplyScalar(v.x).addScaledVector(d,-m.x).multiplyScalar(Y),c[y].add(g),c[w].add(g),c[N].add(g),h[y].add(E),h[w].add(E),h[N].add(E))}let T=this.groups;T.length===0&&(T=[{start:0,count:i.length}]);for(let y=0,w=T.length;y<w;++y){const N=T[y],Y=N.start,D=N.count;for(let F=Y,O=Y+D;F<O;F+=3)_(i[F+0],i[F+1],i[F+2])}const b=new Q,R=new Q,A=new Q,C=new Q;function S(y){A.fromArray(r,y*3),C.copy(A);const w=c[y];b.copy(w),b.sub(A.multiplyScalar(A.dot(w))).normalize(),R.crossVectors(C,w);const Y=R.dot(h[y])<0?-1:1;l[y*4]=b.x,l[y*4+1]=b.y,l[y*4+2]=b.z,l[y*4+3]=Y}for(let y=0,w=T.length;y<w;++y){const N=T[y],Y=N.start,D=N.count;for(let F=Y,O=Y+D;F<O;F+=3)S(i[F+0]),S(i[F+1]),S(i[F+2])}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new Ei(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new Q,r=new Q,a=new Q,o=new Q,l=new Q,c=new Q,h=new Q,u=new Q;if(e)for(let d=0,f=e.count;d<f;d+=3){const p=e.getX(d+0),v=e.getX(d+1),m=e.getX(d+2);n.fromBufferAttribute(t,p),r.fromBufferAttribute(t,v),a.fromBufferAttribute(t,m),h.subVectors(a,r),u.subVectors(n,r),h.cross(u),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,v),c.fromBufferAttribute(i,m),o.add(h),l.add(h),c.add(h),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(v,l.x,l.y,l.z),i.setXYZ(m,c.x,c.y,c.z)}else for(let d=0,f=t.count;d<f;d+=3)n.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,r),u.subVectors(n,r),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Lt.fromBufferAttribute(e,t),Lt.normalize(),e.setXYZ(t,Lt.x,Lt.y,Lt.z)}toNonIndexed(){function e(o,l){const c=o.array,h=o.itemSize,u=o.normalized,d=new c.constructor(l.length*h);let f=0,p=0;for(let v=0,m=l.length;v<m;v++){o.isInterleavedBufferAttribute?f=l[v]*o.data.stride+o.offset:f=l[v]*h;for(let g=0;g<h;g++)d[p++]=c[f++]}return new Ei(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ji,i=this.index.array,n=this.attributes;for(const o in n){const l=n[o],c=e(l,i);t.setAttribute(o,c)}const r=this.morphAttributes;for(const o in r){const l=[],c=r[o];for(let h=0,u=c.length;h<u;h++){const d=c[h],f=e(d,i);l.push(f)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const f=c[u];h.push(f.toJSON(e.data))}h.length>0&&(n[l]=h,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone(t));const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],u=r[c];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,h=a.length;c<h;c++){const u=a[c];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const fl=new Ot,an=new wd,zs=new oa,pl=new Q,wn=new Q,Dn=new Q,Pn=new Q,va=new Q,Ws=new Q,Ks=new nt,Xs=new nt,Ys=new nt,ml=new Q,gl=new Q,vl=new Q,qs=new Q,js=new Q;class mi extends Jt{constructor(e=new ji,t=new hs){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=n.length;r<a;r++){const o=n[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,r=i.morphAttributes.position,a=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const o=this.morphTargetInfluences;if(r&&o){Ws.set(0,0,0);for(let l=0,c=r.length;l<c;l++){const h=o[l],u=r[l];h!==0&&(va.fromBufferAttribute(u,e),a?Ws.addScaledVector(va,h):Ws.addScaledVector(va.sub(t),h))}t.add(Ws)}return t}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),zs.copy(i.boundingSphere),zs.applyMatrix4(r),an.copy(e.ray).recast(e.near),!(zs.containsPoint(an.origin)===!1&&(an.intersectSphere(zs,pl)===null||an.origin.distanceToSquared(pl)>(e.far-e.near)**2))&&(fl.copy(r).invert(),an.copy(e.ray).applyMatrix4(fl),!(i.boundingBox!==null&&an.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,an)))}_computeIntersections(e,t,i){let n;const r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,v=d.length;p<v;p++){const m=d[p],g=a[m.materialIndex],E=Math.max(m.start,f.start),_=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let T=E,b=_;T<b;T+=3){const R=o.getX(T),A=o.getX(T+1),C=o.getX(T+2);n=Qs(this,g,e,i,c,h,u,R,A,C),n&&(n.faceIndex=Math.floor(T/3),n.face.materialIndex=m.materialIndex,t.push(n))}}else{const p=Math.max(0,f.start),v=Math.min(o.count,f.start+f.count);for(let m=p,g=v;m<g;m+=3){const E=o.getX(m),_=o.getX(m+1),T=o.getX(m+2);n=Qs(this,a,e,i,c,h,u,E,_,T),n&&(n.faceIndex=Math.floor(m/3),t.push(n))}}else if(l!==void 0)if(Array.isArray(a))for(let p=0,v=d.length;p<v;p++){const m=d[p],g=a[m.materialIndex],E=Math.max(m.start,f.start),_=Math.min(l.count,Math.min(m.start+m.count,f.start+f.count));for(let T=E,b=_;T<b;T+=3){const R=T,A=T+1,C=T+2;n=Qs(this,g,e,i,c,h,u,R,A,C),n&&(n.faceIndex=Math.floor(T/3),n.face.materialIndex=m.materialIndex,t.push(n))}}else{const p=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let m=p,g=v;m<g;m+=3){const E=m,_=m+1,T=m+2;n=Qs(this,a,e,i,c,h,u,E,_,T),n&&(n.faceIndex=Math.floor(m/3),t.push(n))}}}}function Vd(s,e,t,i,n,r,a,o){let l;if(e.side===1?l=i.intersectTriangle(a,r,n,!0,o):l=i.intersectTriangle(n,r,a,e.side===0,o),l===null)return null;js.copy(o),js.applyMatrix4(s.matrixWorld);const c=t.ray.origin.distanceTo(js);return c<t.near||c>t.far?null:{distance:c,point:js.clone(),object:s}}function Qs(s,e,t,i,n,r,a,o,l,c){s.getVertexPosition(o,wn),s.getVertexPosition(l,Dn),s.getVertexPosition(c,Pn);const h=Vd(s,e,t,i,wn,Dn,Pn,qs);if(h){n&&(Ks.fromBufferAttribute(n,o),Xs.fromBufferAttribute(n,l),Ys.fromBufferAttribute(n,c),h.uv=pi.getInterpolation(qs,wn,Dn,Pn,Ks,Xs,Ys,new nt)),r&&(Ks.fromBufferAttribute(r,o),Xs.fromBufferAttribute(r,l),Ys.fromBufferAttribute(r,c),h.uv1=pi.getInterpolation(qs,wn,Dn,Pn,Ks,Xs,Ys,new nt),h.uv2=h.uv1),a&&(ml.fromBufferAttribute(a,o),gl.fromBufferAttribute(a,l),vl.fromBufferAttribute(a,c),h.normal=pi.getInterpolation(qs,wn,Dn,Pn,ml,gl,vl,new Q),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const u={a:o,b:l,c,normal:new Q,materialIndex:0};pi.getNormal(wn,Dn,Pn,u.normal),h.face=u}return h}class ds extends ji{constructor(e=1,t=1,i=1,n=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:a};const o=this;n=Math.floor(n),r=Math.floor(r),a=Math.floor(a);const l=[],c=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,t,e,a,r,0),p("z","y","x",1,-1,i,t,-e,a,r,1),p("x","z","y",1,1,e,i,t,n,a,2),p("x","z","y",1,-1,e,i,-t,n,a,3),p("x","y","z",1,-1,e,t,i,n,r,4),p("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(l),this.setAttribute("position",new xi(c,3)),this.setAttribute("normal",new xi(h,3)),this.setAttribute("uv",new xi(u,2));function p(v,m,g,E,_,T,b,R,A,C,S){const y=T/A,w=b/C,N=T/2,Y=b/2,D=R/2,F=A+1,O=C+1;let $=0,k=0;const B=new Q;for(let X=0;X<O;X++){const P=X*w-Y;for(let V=0;V<F;V++){const G=V*y-N;B[v]=G*E,B[m]=P*_,B[g]=D,c.push(B.x,B.y,B.z),B[v]=0,B[m]=0,B[g]=R>0?1:-1,h.push(B.x,B.y,B.z),u.push(V/A),u.push(1-X/C),$+=1}}for(let X=0;X<C;X++)for(let P=0;P<A;P++){const V=d+P+F*X,G=d+P+F*(X+1),J=d+(P+1)+F*(X+1),ie=d+(P+1)+F*X;l.push(V,G,ie),l.push(G,J,ie),k+=6}o.addGroup(f,k,S),f+=k,d+=$}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ds(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Fn(s){const e={};for(const t in s){e[t]={};for(const i in s[t]){const n=s[t][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=n.clone():Array.isArray(n)?e[t][i]=n.slice():e[t][i]=n}}return e}function Vt(s){const e={};for(let t=0;t<s.length;t++){const i=Fn(s[t]);for(const n in i)e[n]=i[n]}return e}function Hd(s){const e=[];for(let t=0;t<s.length;t++)e.push(s[t].clone());return e}function _l(s){return s.getRenderTarget()===null?s.outputColorSpace:st.workingColorSpace}const $d={clone:Fn,merge:Vt};var zd=`void main() {
|
|
6
6
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
7
7
|
}`,Wd=`void main() {
|
|
8
8
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
@@ -3474,7 +3474,7 @@ void main() {
|
|
|
3474
3474
|
#include <tonemapping_fragment>
|
|
3475
3475
|
#include <colorspace_fragment>
|
|
3476
3476
|
#include <fog_fragment>
|
|
3477
|
-
}`},ce={common:{diffuse:{value:new rt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Xe},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Xe}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Xe}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Xe}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Xe},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Xe},normalScale:{value:new nt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Xe},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Xe}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Xe}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Xe}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new rt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new rt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0},uvTransform:{value:new Xe}},sprite:{diffuse:{value:new rt(16777215)},opacity:{value:1},center:{value:new nt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Xe},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0}}},Si={basic:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new rt(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new rt(0)},specular:{value:new rt(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:Vt([ce.common,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.roughnessmap,ce.metalnessmap,ce.fog,ce.lights,{emissive:{value:new rt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:Vt([ce.common,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.gradientmap,ce.fog,ce.lights,{emissive:{value:new rt(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:Vt([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:Vt([ce.points,ce.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:Vt([ce.common,ce.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:Vt([ce.common,ce.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:Vt([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:Vt([ce.sprite,ce.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Xe},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distanceRGBA:{uniforms:Vt([ce.common,ce.displacementmap,{referencePosition:{value:new Q},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distanceRGBA_vert,fragmentShader:He.distanceRGBA_frag},shadow:{uniforms:Vt([ce.lights,ce.fog,{color:{value:new rt(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};Si.physical={uniforms:Vt([Si.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Xe},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Xe},clearcoatNormalScale:{value:new nt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Xe},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Xe},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Xe},sheen:{value:0},sheenColor:{value:new rt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Xe},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Xe},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Xe},transmissionSamplerSize:{value:new nt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Xe},attenuationDistance:{value:0},attenuationColor:{value:new rt(0)},specularColor:{value:new rt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Xe},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Xe},anisotropyVector:{value:new nt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Xe}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const er={r:0,b:0,g:0};function Qp(s,e,t,i,n,r,a){const o=new rt(0);let l=r===!0?0:1,c,h,u=null,d=0,f=null;function p(m,g){let E=!1,_=g.isScene===!0?g.background:null;_&&_.isTexture&&(_=(g.backgroundBlurriness>0?t:e).get(_)),_===null?v(o,l):_&&_.isColor&&(v(_,1),E=!0);const T=s.xr.getEnvironmentBlendMode();T==="additive"?i.buffers.color.setClear(0,0,0,1,a):T==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(s.autoClear||E)&&s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil),_&&(_.isCubeTexture||_.mapping===306)?(h===void 0&&(h=new mi(new ds(1,1,1),new on({name:"BackgroundCubeMaterial",uniforms:Fn(Si.backgroundCube.uniforms),vertexShader:Si.backgroundCube.vertexShader,fragmentShader:Si.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(b,R,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h.material.uniforms.envMap.value=_,h.material.uniforms.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,h.material.toneMapped=st.getTransfer(_.colorSpace)!==dt,(u!==_||d!==_.version||f!==s.toneMapping)&&(h.material.needsUpdate=!0,u=_,d=_.version,f=s.toneMapping),h.layers.enableAll(),m.unshift(h,h.geometry,h.material,0,0,null)):_&&_.isTexture&&(c===void 0&&(c=new mi(new Js(2,2),new on({name:"BackgroundMaterial",uniforms:Fn(Si.background.uniforms),vertexShader:Si.background.vertexShader,fragmentShader:Si.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.t2D.value=_,c.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,c.material.toneMapped=st.getTransfer(_.colorSpace)!==dt,_.matrixAutoUpdate===!0&&_.updateMatrix(),c.material.uniforms.uvTransform.value.copy(_.matrix),(u!==_||d!==_.version||f!==s.toneMapping)&&(c.material.needsUpdate=!0,u=_,d=_.version,f=s.toneMapping),c.layers.enableAll(),m.unshift(c,c.geometry,c.material,0,0,null))}function v(m,g){m.getRGB(er,_l(s)),i.buffers.color.setClear(er.r,er.g,er.b,g,a)}return{getClearColor:function(){return o},setClearColor:function(m,g=1){o.set(m),l=g,v(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(m){l=m,v(o,l)},render:p}}function Zp(s,e,t,i){const n=s.getParameter(s.MAX_VERTEX_ATTRIBS),r=i.isWebGL2?null:e.get("OES_vertex_array_object"),a=i.isWebGL2||r!==null,o={},l=m(null);let c=l,h=!1;function u(P,F,D,k,N){let B=!1;if(a){const q=v(k,D,F);c!==q&&(c=q,f(c.object)),B=g(P,k,D,N),B&&E(P,k,D,N)}else{const q=F.wireframe===!0;(c.geometry!==k.id||c.program!==D.id||c.wireframe!==q)&&(c.geometry=k.id,c.program=D.id,c.wireframe=q,B=!0)}N!==null&&t.update(N,s.ELEMENT_ARRAY_BUFFER),(B||h)&&(h=!1,C(P,F,D,k),N!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t.get(N).buffer))}function d(){return i.isWebGL2?s.createVertexArray():r.createVertexArrayOES()}function f(P){return i.isWebGL2?s.bindVertexArray(P):r.bindVertexArrayOES(P)}function p(P){return i.isWebGL2?s.deleteVertexArray(P):r.deleteVertexArrayOES(P)}function v(P,F,D){const k=D.wireframe===!0;let N=o[P.id];N===void 0&&(N={},o[P.id]=N);let B=N[F.id];B===void 0&&(B={},N[F.id]=B);let q=B[k];return q===void 0&&(q=m(d()),B[k]=q),q}function m(P){const F=[],D=[],k=[];for(let N=0;N<n;N++)F[N]=0,D[N]=0,k[N]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:F,enabledAttributes:D,attributeDivisors:k,object:P,attributes:{},index:null}}function g(P,F,D,k){const N=c.attributes,B=F.attributes;let q=0;const V=D.getAttributes();for(const W in V)if(V[W].location>=0){const ee=N[W];let ie=B[W];if(ie===void 0&&(W==="instanceMatrix"&&P.instanceMatrix&&(ie=P.instanceMatrix),W==="instanceColor"&&P.instanceColor&&(ie=P.instanceColor)),ee===void 0||ee.attribute!==ie||ie&&ee.data!==ie.data)return!0;q++}return c.attributesNum!==q||c.index!==k}function E(P,F,D,k){const N={},B=F.attributes;let q=0;const V=D.getAttributes();for(const W in V)if(V[W].location>=0){let ee=B[W];ee===void 0&&(W==="instanceMatrix"&&P.instanceMatrix&&(ee=P.instanceMatrix),W==="instanceColor"&&P.instanceColor&&(ee=P.instanceColor));const ie={};ie.attribute=ee,ee&&ee.data&&(ie.data=ee.data),N[W]=ie,q++}c.attributes=N,c.attributesNum=q,c.index=k}function _(){const P=c.newAttributes;for(let F=0,D=P.length;F<D;F++)P[F]=0}function T(P){b(P,0)}function b(P,F){const D=c.newAttributes,k=c.enabledAttributes,N=c.attributeDivisors;D[P]=1,k[P]===0&&(s.enableVertexAttribArray(P),k[P]=1),N[P]!==F&&((i.isWebGL2?s:e.get("ANGLE_instanced_arrays"))[i.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](P,F),N[P]=F)}function R(){const P=c.newAttributes,F=c.enabledAttributes;for(let D=0,k=F.length;D<k;D++)F[D]!==P[D]&&(s.disableVertexAttribArray(D),F[D]=0)}function A(P,F,D,k,N,B,q){q===!0?s.vertexAttribIPointer(P,F,D,N,B):s.vertexAttribPointer(P,F,D,k,N,B)}function C(P,F,D,k){if(i.isWebGL2===!1&&(P.isInstancedMesh||k.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;_();const N=k.attributes,B=D.getAttributes(),q=F.defaultAttributeValues;for(const V in B){const W=B[V];if(W.location>=0){let $=N[V];if($===void 0&&(V==="instanceMatrix"&&P.instanceMatrix&&($=P.instanceMatrix),V==="instanceColor"&&P.instanceColor&&($=P.instanceColor)),$!==void 0){const ee=$.normalized,ie=$.itemSize,oe=t.get($);if(oe===void 0)continue;const me=oe.buffer,Se=oe.type,be=oe.bytesPerElement,Te=i.isWebGL2===!0&&(Se===s.INT||Se===s.UNSIGNED_INT||$.gpuType===1013);if($.isInterleavedBufferAttribute){const Ge=$.data,Y=Ge.stride,Rt=$.offset;if(Ge.isInstancedInterleavedBuffer){for(let Re=0;Re<W.locationSize;Re++)b(W.location+Re,Ge.meshPerAttribute);P.isInstancedMesh!==!0&&k._maxInstanceCount===void 0&&(k._maxInstanceCount=Ge.meshPerAttribute*Ge.count)}else for(let Re=0;Re<W.locationSize;Re++)T(W.location+Re);s.bindBuffer(s.ARRAY_BUFFER,me);for(let Re=0;Re<W.locationSize;Re++)A(W.location+Re,ie/W.locationSize,Se,ee,Y*be,(Rt+ie/W.locationSize*Re)*be,Te)}else{if($.isInstancedBufferAttribute){for(let Ge=0;Ge<W.locationSize;Ge++)b(W.location+Ge,$.meshPerAttribute);P.isInstancedMesh!==!0&&k._maxInstanceCount===void 0&&(k._maxInstanceCount=$.meshPerAttribute*$.count)}else for(let Ge=0;Ge<W.locationSize;Ge++)T(W.location+Ge);s.bindBuffer(s.ARRAY_BUFFER,me);for(let Ge=0;Ge<W.locationSize;Ge++)A(W.location+Ge,ie/W.locationSize,Se,ee,ie*be,ie/W.locationSize*Ge*be,Te)}}else if(q!==void 0){const ee=q[V];if(ee!==void 0)switch(ee.length){case 2:s.vertexAttrib2fv(W.location,ee);break;case 3:s.vertexAttrib3fv(W.location,ee);break;case 4:s.vertexAttrib4fv(W.location,ee);break;default:s.vertexAttrib1fv(W.location,ee)}}}}R()}function S(){U();for(const P in o){const F=o[P];for(const D in F){const k=F[D];for(const N in k)p(k[N].object),delete k[N];delete F[D]}delete o[P]}}function y(P){if(o[P.id]===void 0)return;const F=o[P.id];for(const D in F){const k=F[D];for(const N in k)p(k[N].object),delete k[N];delete F[D]}delete o[P.id]}function w(P){for(const F in o){const D=o[F];if(D[P.id]===void 0)continue;const k=D[P.id];for(const N in k)p(k[N].object),delete k[N];delete D[P.id]}}function U(){X(),h=!0,c!==l&&(c=l,f(c.object))}function X(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:u,reset:U,resetDefaultState:X,dispose:S,releaseStatesOfGeometry:y,releaseStatesOfProgram:w,initAttributes:_,enableAttribute:T,disableUnusedAttributes:R}}function Jp(s,e,t,i){const n=i.isWebGL2;let r;function a(h){r=h}function o(h,u){s.drawArrays(r,h,u),t.update(u,r,1)}function l(h,u,d){if(d===0)return;let f,p;if(n)f=s,p="drawArraysInstanced";else if(f=e.get("ANGLE_instanced_arrays"),p="drawArraysInstancedANGLE",f===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}f[p](r,h,u,d),t.update(u,r,d)}function c(h,u,d){if(d===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let p=0;p<d;p++)this.render(h[p],u[p]);else{f.multiDrawArraysWEBGL(r,h,0,u,0,d);let p=0;for(let v=0;v<d;v++)p+=u[v];t.update(p,r,1)}}this.setMode=a,this.render=o,this.renderInstances=l,this.renderMultiDraw=c}function em(s,e,t){let i;function n(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");i=s.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function r(A){if(A==="highp"){if(s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.HIGH_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const a=typeof WebGL2RenderingContext<"u"&&s.constructor.name==="WebGL2RenderingContext";let o=t.precision!==void 0?t.precision:"highp";const l=r(o);l!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",l,"instead."),o=l);const c=a||e.has("WEBGL_draw_buffers"),h=t.logarithmicDepthBuffer===!0,u=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),d=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),f=s.getParameter(s.MAX_TEXTURE_SIZE),p=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),v=s.getParameter(s.MAX_VERTEX_ATTRIBS),m=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),g=s.getParameter(s.MAX_VARYING_VECTORS),E=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),_=d>0,T=a||e.has("OES_texture_float"),b=_&&T,R=a?s.getParameter(s.MAX_SAMPLES):0;return{isWebGL2:a,drawBuffers:c,getMaxAnisotropy:n,getMaxPrecision:r,precision:o,logarithmicDepthBuffer:h,maxTextures:u,maxVertexTextures:d,maxTextureSize:f,maxCubemapSize:p,maxAttributes:v,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:E,vertexTextures:_,floatFragmentTextures:T,floatVertexTextures:b,maxSamples:R}}function tm(s){const e=this;let t=null,i=0,n=!1,r=!1;const a=new ln,o=new Xe,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||i!==0||n;return n=d,i=u.length,f},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,g=s.get(u);if(!n||p===null||p.length===0||r&&!m)r?h(null):c();else{const E=r?0:i,_=E*4;let T=g.clippingState||null;l.value=T,T=h(p,d,_,f);for(let b=0;b!==_;++b)T[b]=t[b];g.clippingState=T,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=E}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(u,d,f,p){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=l.value,p!==!0||m===null){const g=f+v*4,E=d.matrixWorldInverse;o.getNormalMatrix(E),(m===null||m.length<g)&&(m=new Float32Array(g));for(let _=0,T=f;_!==v;++_,T+=4)a.copy(u[_]).applyMatrix4(E,o),a.normal.toArray(m,T),m[T+3]=a.constant}l.value=m,l.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function im(s){let e=new WeakMap;function t(a,o){return o===303?a.mapping=301:o===304&&(a.mapping=302),a}function i(a){if(a&&a.isTexture){const o=a.mapping;if(o===303||o===304)if(e.has(a)){const l=e.get(a).texture;return t(l,a.mapping)}else{const l=a.image;if(l&&l.height>0){const c=new Xd(l.height/2);return c.fromEquirectangularTexture(s,a),e.set(a,c),a.addEventListener("dispose",n),t(c.texture,a.mapping)}else return null}}return a}function n(a){const o=a.target;o.removeEventListener("dispose",n);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function r(){e=new WeakMap}return{get:i,dispose:r}}class nm extends El{constructor(e=-1,t=1,i=1,n=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=n,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,i,n,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let r=i-e,a=i+e,o=n+t,l=n-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=c*this.view.offsetX,a=r+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const Nn=4,Tl=[.125,.215,.35,.446,.526,.582],hn=20,Ea=new nm,Al=new rt;let xa=null,Sa=0,ya=0;const un=(1+Math.sqrt(5))/2,kn=1/un,bl=[new Q(1,1,1),new Q(-1,1,1),new Q(1,1,-1),new Q(-1,1,-1),new Q(0,un,kn),new Q(0,un,-kn),new Q(kn,0,un),new Q(-kn,0,un),new Q(un,kn,0),new Q(-un,kn,0)];class Rl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,n=100){xa=this._renderer.getRenderTarget(),Sa=this._renderer.getActiveCubeFace(),ya=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,i,n,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Il(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Ll(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(xa,Sa,ya),e.scissorTest=!1,tr(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),xa=this._renderer.getRenderTarget(),Sa=this._renderer.getActiveCubeFace(),ya=this._renderer.getActiveMipmapLevel();const i=t||this._allocateTargets();return this._textureToCubeUV(e,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:1006,minFilter:1006,generateMipmaps:!1,type:1016,format:1023,colorSpace:Ci,depthBuffer:!1},n=Ml(e,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ml(e,t,i);const{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=sm(r)),this._blurMaterial=rm(r,e,t)}return n}_compileMaterial(e){const t=new mi(this._lodPlanes[0],e);this._renderer.compile(t,Ea)}_sceneToCubeUV(e,t,i,n){const o=new oi(90,1,t,i),l=[1,-1,1,1,1,1],c=[1,1,1,-1,-1,-1],h=this._renderer,u=h.autoClear,d=h.toneMapping;h.getClearColor(Al),h.toneMapping=0,h.autoClear=!1;const f=new hs({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),p=new mi(new ds,f);let v=!1;const m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,v=!0):(f.color.copy(Al),v=!0);for(let g=0;g<6;g++){const E=g%3;E===0?(o.up.set(0,l[g],0),o.lookAt(c[g],0,0)):E===1?(o.up.set(0,0,l[g]),o.lookAt(0,c[g],0)):(o.up.set(0,l[g],0),o.lookAt(0,0,c[g]));const _=this._cubeSize;tr(n,E*_,g>2?_:0,_,_),h.setRenderTarget(n),v&&h.render(p,o),h.render(e,o)}p.geometry.dispose(),p.material.dispose(),h.toneMapping=d,h.autoClear=u,e.background=m}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===301||e.mapping===302;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=Il()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Ll());const r=n?this._cubemapMaterial:this._equirectMaterial,a=new mi(this._lodPlanes[0],r),o=r.uniforms;o.envMap.value=e;const l=this._cubeSize;tr(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,Ea)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;for(let n=1;n<this._lodPlanes.length;n++){const r=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=bl[(n-1)%bl.length];this._blur(e,n-1,n,r,a)}t.autoClear=i}_blur(e,t,i,n,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",r),this._halfBlur(a,e,i,i,n,"longitudinal",r)}_halfBlur(e,t,i,n,r,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new mi(this._lodPlanes[n],c),d=c.uniforms,f=this._sizeLods[i]-1,p=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*hn-1),v=r/p,m=isFinite(r)?1+Math.floor(h*v):hn;m>hn&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${hn}`);const g=[];let E=0;for(let A=0;A<hn;++A){const C=A/v,S=Math.exp(-C*C/2);g.push(S),A===0?E+=S:A<m&&(E+=2*S)}for(let A=0;A<g.length;A++)g[A]=g[A]/E;d.envMap.value=e.texture,d.samples.value=m,d.weights.value=g,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:_}=this;d.dTheta.value=p,d.mipInt.value=_-i;const T=this._sizeLods[n],b=3*T*(n>_-Nn?n-_+Nn:0),R=4*(this._cubeSize-T);tr(t,b,R,3*T,2*T),l.setRenderTarget(t),l.render(u,Ea)}}function sm(s){const e=[],t=[],i=[];let n=s;const r=s-Nn+1+Tl.length;for(let a=0;a<r;a++){const o=Math.pow(2,n);t.push(o);let l=1/o;a>s-Nn?l=Tl[a-s+Nn-1]:a===0&&(l=0),i.push(l);const c=1/(o-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,v=3,m=2,g=1,E=new Float32Array(v*p*f),_=new Float32Array(m*p*f),T=new Float32Array(g*p*f);for(let R=0;R<f;R++){const A=R%3*2/3-1,C=R>2?0:-1,S=[A,C,0,A+2/3,C,0,A+2/3,C+1,0,A,C,0,A+2/3,C+1,0,A,C+1,0];E.set(S,v*p*R),_.set(d,m*p*R);const y=[R,R,R,R,R,R];T.set(y,g*p*R)}const b=new ji;b.setAttribute("position",new Ei(E,v)),b.setAttribute("uv",new Ei(_,m)),b.setAttribute("faceIndex",new Ei(T,g)),e.push(b),n>Nn&&n--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function Ml(s,e,t){const i=new nn(s,e,t);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function tr(s,e,t,i,n){s.viewport.set(e,t,i,n),s.scissor.set(e,t,i,n)}function rm(s,e,t){const i=new Float32Array(hn),n=new Q(0,1,0);return new on({name:"SphericalGaussianBlur",defines:{n:hn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Ta(),fragmentShader:`
|
|
3477
|
+
}`},ce={common:{diffuse:{value:new rt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Xe},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Xe}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Xe}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Xe}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Xe},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Xe},normalScale:{value:new nt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Xe},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Xe}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Xe}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Xe}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new rt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new rt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0},uvTransform:{value:new Xe}},sprite:{diffuse:{value:new rt(16777215)},opacity:{value:1},center:{value:new nt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Xe},alphaMap:{value:null},alphaMapTransform:{value:new Xe},alphaTest:{value:0}}},Si={basic:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new rt(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:Vt([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new rt(0)},specular:{value:new rt(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:Vt([ce.common,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.roughnessmap,ce.metalnessmap,ce.fog,ce.lights,{emissive:{value:new rt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:Vt([ce.common,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.gradientmap,ce.fog,ce.lights,{emissive:{value:new rt(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:Vt([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:Vt([ce.points,ce.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:Vt([ce.common,ce.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:Vt([ce.common,ce.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:Vt([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:Vt([ce.sprite,ce.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Xe},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distanceRGBA:{uniforms:Vt([ce.common,ce.displacementmap,{referencePosition:{value:new Q},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distanceRGBA_vert,fragmentShader:He.distanceRGBA_frag},shadow:{uniforms:Vt([ce.lights,ce.fog,{color:{value:new rt(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};Si.physical={uniforms:Vt([Si.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Xe},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Xe},clearcoatNormalScale:{value:new nt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Xe},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Xe},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Xe},sheen:{value:0},sheenColor:{value:new rt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Xe},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Xe},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Xe},transmissionSamplerSize:{value:new nt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Xe},attenuationDistance:{value:0},attenuationColor:{value:new rt(0)},specularColor:{value:new rt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Xe},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Xe},anisotropyVector:{value:new nt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Xe}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const er={r:0,b:0,g:0};function Qp(s,e,t,i,n,r,a){const o=new rt(0);let l=r===!0?0:1,c,h,u=null,d=0,f=null;function p(m,g){let E=!1,_=g.isScene===!0?g.background:null;_&&_.isTexture&&(_=(g.backgroundBlurriness>0?t:e).get(_)),_===null?v(o,l):_&&_.isColor&&(v(_,1),E=!0);const T=s.xr.getEnvironmentBlendMode();T==="additive"?i.buffers.color.setClear(0,0,0,1,a):T==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(s.autoClear||E)&&s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil),_&&(_.isCubeTexture||_.mapping===306)?(h===void 0&&(h=new mi(new ds(1,1,1),new on({name:"BackgroundCubeMaterial",uniforms:Fn(Si.backgroundCube.uniforms),vertexShader:Si.backgroundCube.vertexShader,fragmentShader:Si.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(b,R,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h.material.uniforms.envMap.value=_,h.material.uniforms.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,h.material.toneMapped=st.getTransfer(_.colorSpace)!==dt,(u!==_||d!==_.version||f!==s.toneMapping)&&(h.material.needsUpdate=!0,u=_,d=_.version,f=s.toneMapping),h.layers.enableAll(),m.unshift(h,h.geometry,h.material,0,0,null)):_&&_.isTexture&&(c===void 0&&(c=new mi(new Js(2,2),new on({name:"BackgroundMaterial",uniforms:Fn(Si.background.uniforms),vertexShader:Si.background.vertexShader,fragmentShader:Si.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.t2D.value=_,c.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,c.material.toneMapped=st.getTransfer(_.colorSpace)!==dt,_.matrixAutoUpdate===!0&&_.updateMatrix(),c.material.uniforms.uvTransform.value.copy(_.matrix),(u!==_||d!==_.version||f!==s.toneMapping)&&(c.material.needsUpdate=!0,u=_,d=_.version,f=s.toneMapping),c.layers.enableAll(),m.unshift(c,c.geometry,c.material,0,0,null))}function v(m,g){m.getRGB(er,_l(s)),i.buffers.color.setClear(er.r,er.g,er.b,g,a)}return{getClearColor:function(){return o},setClearColor:function(m,g=1){o.set(m),l=g,v(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(m){l=m,v(o,l)},render:p}}function Zp(s,e,t,i){const n=s.getParameter(s.MAX_VERTEX_ATTRIBS),r=i.isWebGL2?null:e.get("OES_vertex_array_object"),a=i.isWebGL2||r!==null,o={},l=m(null);let c=l,h=!1;function u(D,F,O,$,k){let B=!1;if(a){const X=v($,O,F);c!==X&&(c=X,f(c.object)),B=g(D,$,O,k),B&&E(D,$,O,k)}else{const X=F.wireframe===!0;(c.geometry!==$.id||c.program!==O.id||c.wireframe!==X)&&(c.geometry=$.id,c.program=O.id,c.wireframe=X,B=!0)}k!==null&&t.update(k,s.ELEMENT_ARRAY_BUFFER),(B||h)&&(h=!1,C(D,F,O,$),k!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t.get(k).buffer))}function d(){return i.isWebGL2?s.createVertexArray():r.createVertexArrayOES()}function f(D){return i.isWebGL2?s.bindVertexArray(D):r.bindVertexArrayOES(D)}function p(D){return i.isWebGL2?s.deleteVertexArray(D):r.deleteVertexArrayOES(D)}function v(D,F,O){const $=O.wireframe===!0;let k=o[D.id];k===void 0&&(k={},o[D.id]=k);let B=k[F.id];B===void 0&&(B={},k[F.id]=B);let X=B[$];return X===void 0&&(X=m(d()),B[$]=X),X}function m(D){const F=[],O=[],$=[];for(let k=0;k<n;k++)F[k]=0,O[k]=0,$[k]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:F,enabledAttributes:O,attributeDivisors:$,object:D,attributes:{},index:null}}function g(D,F,O,$){const k=c.attributes,B=F.attributes;let X=0;const P=O.getAttributes();for(const V in P)if(P[V].location>=0){const J=k[V];let ie=B[V];if(ie===void 0&&(V==="instanceMatrix"&&D.instanceMatrix&&(ie=D.instanceMatrix),V==="instanceColor"&&D.instanceColor&&(ie=D.instanceColor)),J===void 0||J.attribute!==ie||ie&&J.data!==ie.data)return!0;X++}return c.attributesNum!==X||c.index!==$}function E(D,F,O,$){const k={},B=F.attributes;let X=0;const P=O.getAttributes();for(const V in P)if(P[V].location>=0){let J=B[V];J===void 0&&(V==="instanceMatrix"&&D.instanceMatrix&&(J=D.instanceMatrix),V==="instanceColor"&&D.instanceColor&&(J=D.instanceColor));const ie={};ie.attribute=J,J&&J.data&&(ie.data=J.data),k[V]=ie,X++}c.attributes=k,c.attributesNum=X,c.index=$}function _(){const D=c.newAttributes;for(let F=0,O=D.length;F<O;F++)D[F]=0}function T(D){b(D,0)}function b(D,F){const O=c.newAttributes,$=c.enabledAttributes,k=c.attributeDivisors;O[D]=1,$[D]===0&&(s.enableVertexAttribArray(D),$[D]=1),k[D]!==F&&((i.isWebGL2?s:e.get("ANGLE_instanced_arrays"))[i.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](D,F),k[D]=F)}function R(){const D=c.newAttributes,F=c.enabledAttributes;for(let O=0,$=F.length;O<$;O++)F[O]!==D[O]&&(s.disableVertexAttribArray(O),F[O]=0)}function A(D,F,O,$,k,B,X){X===!0?s.vertexAttribIPointer(D,F,O,k,B):s.vertexAttribPointer(D,F,O,$,k,B)}function C(D,F,O,$){if(i.isWebGL2===!1&&(D.isInstancedMesh||$.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;_();const k=$.attributes,B=O.getAttributes(),X=F.defaultAttributeValues;for(const P in B){const V=B[P];if(V.location>=0){let G=k[P];if(G===void 0&&(P==="instanceMatrix"&&D.instanceMatrix&&(G=D.instanceMatrix),P==="instanceColor"&&D.instanceColor&&(G=D.instanceColor)),G!==void 0){const J=G.normalized,ie=G.itemSize,oe=t.get(G);if(oe===void 0)continue;const me=oe.buffer,Se=oe.type,be=oe.bytesPerElement,Te=i.isWebGL2===!0&&(Se===s.INT||Se===s.UNSIGNED_INT||G.gpuType===1013);if(G.isInterleavedBufferAttribute){const Ge=G.data,q=Ge.stride,Rt=G.offset;if(Ge.isInstancedInterleavedBuffer){for(let Re=0;Re<V.locationSize;Re++)b(V.location+Re,Ge.meshPerAttribute);D.isInstancedMesh!==!0&&$._maxInstanceCount===void 0&&($._maxInstanceCount=Ge.meshPerAttribute*Ge.count)}else for(let Re=0;Re<V.locationSize;Re++)T(V.location+Re);s.bindBuffer(s.ARRAY_BUFFER,me);for(let Re=0;Re<V.locationSize;Re++)A(V.location+Re,ie/V.locationSize,Se,J,q*be,(Rt+ie/V.locationSize*Re)*be,Te)}else{if(G.isInstancedBufferAttribute){for(let Ge=0;Ge<V.locationSize;Ge++)b(V.location+Ge,G.meshPerAttribute);D.isInstancedMesh!==!0&&$._maxInstanceCount===void 0&&($._maxInstanceCount=G.meshPerAttribute*G.count)}else for(let Ge=0;Ge<V.locationSize;Ge++)T(V.location+Ge);s.bindBuffer(s.ARRAY_BUFFER,me);for(let Ge=0;Ge<V.locationSize;Ge++)A(V.location+Ge,ie/V.locationSize,Se,J,ie*be,ie/V.locationSize*Ge*be,Te)}}else if(X!==void 0){const J=X[P];if(J!==void 0)switch(J.length){case 2:s.vertexAttrib2fv(V.location,J);break;case 3:s.vertexAttrib3fv(V.location,J);break;case 4:s.vertexAttrib4fv(V.location,J);break;default:s.vertexAttrib1fv(V.location,J)}}}}R()}function S(){N();for(const D in o){const F=o[D];for(const O in F){const $=F[O];for(const k in $)p($[k].object),delete $[k];delete F[O]}delete o[D]}}function y(D){if(o[D.id]===void 0)return;const F=o[D.id];for(const O in F){const $=F[O];for(const k in $)p($[k].object),delete $[k];delete F[O]}delete o[D.id]}function w(D){for(const F in o){const O=o[F];if(O[D.id]===void 0)continue;const $=O[D.id];for(const k in $)p($[k].object),delete $[k];delete O[D.id]}}function N(){Y(),h=!0,c!==l&&(c=l,f(c.object))}function Y(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:u,reset:N,resetDefaultState:Y,dispose:S,releaseStatesOfGeometry:y,releaseStatesOfProgram:w,initAttributes:_,enableAttribute:T,disableUnusedAttributes:R}}function Jp(s,e,t,i){const n=i.isWebGL2;let r;function a(h){r=h}function o(h,u){s.drawArrays(r,h,u),t.update(u,r,1)}function l(h,u,d){if(d===0)return;let f,p;if(n)f=s,p="drawArraysInstanced";else if(f=e.get("ANGLE_instanced_arrays"),p="drawArraysInstancedANGLE",f===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}f[p](r,h,u,d),t.update(u,r,d)}function c(h,u,d){if(d===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let p=0;p<d;p++)this.render(h[p],u[p]);else{f.multiDrawArraysWEBGL(r,h,0,u,0,d);let p=0;for(let v=0;v<d;v++)p+=u[v];t.update(p,r,1)}}this.setMode=a,this.render=o,this.renderInstances=l,this.renderMultiDraw=c}function em(s,e,t){let i;function n(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");i=s.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function r(A){if(A==="highp"){if(s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.HIGH_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const a=typeof WebGL2RenderingContext<"u"&&s.constructor.name==="WebGL2RenderingContext";let o=t.precision!==void 0?t.precision:"highp";const l=r(o);l!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",l,"instead."),o=l);const c=a||e.has("WEBGL_draw_buffers"),h=t.logarithmicDepthBuffer===!0,u=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),d=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),f=s.getParameter(s.MAX_TEXTURE_SIZE),p=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),v=s.getParameter(s.MAX_VERTEX_ATTRIBS),m=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),g=s.getParameter(s.MAX_VARYING_VECTORS),E=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),_=d>0,T=a||e.has("OES_texture_float"),b=_&&T,R=a?s.getParameter(s.MAX_SAMPLES):0;return{isWebGL2:a,drawBuffers:c,getMaxAnisotropy:n,getMaxPrecision:r,precision:o,logarithmicDepthBuffer:h,maxTextures:u,maxVertexTextures:d,maxTextureSize:f,maxCubemapSize:p,maxAttributes:v,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:E,vertexTextures:_,floatFragmentTextures:T,floatVertexTextures:b,maxSamples:R}}function tm(s){const e=this;let t=null,i=0,n=!1,r=!1;const a=new ln,o=new Xe,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||i!==0||n;return n=d,i=u.length,f},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,g=s.get(u);if(!n||p===null||p.length===0||r&&!m)r?h(null):c();else{const E=r?0:i,_=E*4;let T=g.clippingState||null;l.value=T,T=h(p,d,_,f);for(let b=0;b!==_;++b)T[b]=t[b];g.clippingState=T,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=E}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(u,d,f,p){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=l.value,p!==!0||m===null){const g=f+v*4,E=d.matrixWorldInverse;o.getNormalMatrix(E),(m===null||m.length<g)&&(m=new Float32Array(g));for(let _=0,T=f;_!==v;++_,T+=4)a.copy(u[_]).applyMatrix4(E,o),a.normal.toArray(m,T),m[T+3]=a.constant}l.value=m,l.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function im(s){let e=new WeakMap;function t(a,o){return o===303?a.mapping=301:o===304&&(a.mapping=302),a}function i(a){if(a&&a.isTexture){const o=a.mapping;if(o===303||o===304)if(e.has(a)){const l=e.get(a).texture;return t(l,a.mapping)}else{const l=a.image;if(l&&l.height>0){const c=new Xd(l.height/2);return c.fromEquirectangularTexture(s,a),e.set(a,c),a.addEventListener("dispose",n),t(c.texture,a.mapping)}else return null}}return a}function n(a){const o=a.target;o.removeEventListener("dispose",n);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function r(){e=new WeakMap}return{get:i,dispose:r}}class nm extends El{constructor(e=-1,t=1,i=1,n=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=n,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,i,n,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let r=i-e,a=i+e,o=n+t,l=n-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=c*this.view.offsetX,a=r+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const Nn=4,Tl=[.125,.215,.35,.446,.526,.582],hn=20,Ea=new nm,Al=new rt;let xa=null,Sa=0,ya=0;const un=(1+Math.sqrt(5))/2,kn=1/un,bl=[new Q(1,1,1),new Q(-1,1,1),new Q(1,1,-1),new Q(-1,1,-1),new Q(0,un,kn),new Q(0,un,-kn),new Q(kn,0,un),new Q(-kn,0,un),new Q(un,kn,0),new Q(-un,kn,0)];class Rl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,n=100){xa=this._renderer.getRenderTarget(),Sa=this._renderer.getActiveCubeFace(),ya=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,i,n,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Il(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Ll(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(xa,Sa,ya),e.scissorTest=!1,tr(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),xa=this._renderer.getRenderTarget(),Sa=this._renderer.getActiveCubeFace(),ya=this._renderer.getActiveMipmapLevel();const i=t||this._allocateTargets();return this._textureToCubeUV(e,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:1006,minFilter:1006,generateMipmaps:!1,type:1016,format:1023,colorSpace:Ci,depthBuffer:!1},n=Ml(e,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ml(e,t,i);const{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=sm(r)),this._blurMaterial=rm(r,e,t)}return n}_compileMaterial(e){const t=new mi(this._lodPlanes[0],e);this._renderer.compile(t,Ea)}_sceneToCubeUV(e,t,i,n){const o=new oi(90,1,t,i),l=[1,-1,1,1,1,1],c=[1,1,1,-1,-1,-1],h=this._renderer,u=h.autoClear,d=h.toneMapping;h.getClearColor(Al),h.toneMapping=0,h.autoClear=!1;const f=new hs({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),p=new mi(new ds,f);let v=!1;const m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,v=!0):(f.color.copy(Al),v=!0);for(let g=0;g<6;g++){const E=g%3;E===0?(o.up.set(0,l[g],0),o.lookAt(c[g],0,0)):E===1?(o.up.set(0,0,l[g]),o.lookAt(0,c[g],0)):(o.up.set(0,l[g],0),o.lookAt(0,0,c[g]));const _=this._cubeSize;tr(n,E*_,g>2?_:0,_,_),h.setRenderTarget(n),v&&h.render(p,o),h.render(e,o)}p.geometry.dispose(),p.material.dispose(),h.toneMapping=d,h.autoClear=u,e.background=m}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===301||e.mapping===302;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=Il()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Ll());const r=n?this._cubemapMaterial:this._equirectMaterial,a=new mi(this._lodPlanes[0],r),o=r.uniforms;o.envMap.value=e;const l=this._cubeSize;tr(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,Ea)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;for(let n=1;n<this._lodPlanes.length;n++){const r=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=bl[(n-1)%bl.length];this._blur(e,n-1,n,r,a)}t.autoClear=i}_blur(e,t,i,n,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",r),this._halfBlur(a,e,i,i,n,"longitudinal",r)}_halfBlur(e,t,i,n,r,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new mi(this._lodPlanes[n],c),d=c.uniforms,f=this._sizeLods[i]-1,p=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*hn-1),v=r/p,m=isFinite(r)?1+Math.floor(h*v):hn;m>hn&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${hn}`);const g=[];let E=0;for(let A=0;A<hn;++A){const C=A/v,S=Math.exp(-C*C/2);g.push(S),A===0?E+=S:A<m&&(E+=2*S)}for(let A=0;A<g.length;A++)g[A]=g[A]/E;d.envMap.value=e.texture,d.samples.value=m,d.weights.value=g,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:_}=this;d.dTheta.value=p,d.mipInt.value=_-i;const T=this._sizeLods[n],b=3*T*(n>_-Nn?n-_+Nn:0),R=4*(this._cubeSize-T);tr(t,b,R,3*T,2*T),l.setRenderTarget(t),l.render(u,Ea)}}function sm(s){const e=[],t=[],i=[];let n=s;const r=s-Nn+1+Tl.length;for(let a=0;a<r;a++){const o=Math.pow(2,n);t.push(o);let l=1/o;a>s-Nn?l=Tl[a-s+Nn-1]:a===0&&(l=0),i.push(l);const c=1/(o-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,v=3,m=2,g=1,E=new Float32Array(v*p*f),_=new Float32Array(m*p*f),T=new Float32Array(g*p*f);for(let R=0;R<f;R++){const A=R%3*2/3-1,C=R>2?0:-1,S=[A,C,0,A+2/3,C,0,A+2/3,C+1,0,A,C,0,A+2/3,C+1,0,A,C+1,0];E.set(S,v*p*R),_.set(d,m*p*R);const y=[R,R,R,R,R,R];T.set(y,g*p*R)}const b=new ji;b.setAttribute("position",new Ei(E,v)),b.setAttribute("uv",new Ei(_,m)),b.setAttribute("faceIndex",new Ei(T,g)),e.push(b),n>Nn&&n--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function Ml(s,e,t){const i=new nn(s,e,t);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function tr(s,e,t,i,n){s.viewport.set(e,t,i,n),s.scissor.set(e,t,i,n)}function rm(s,e,t){const i=new Float32Array(hn),n=new Q(0,1,0);return new on({name:"SphericalGaussianBlur",defines:{n:hn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Ta(),fragmentShader:`
|
|
3478
3478
|
|
|
3479
3479
|
precision mediump float;
|
|
3480
3480
|
precision mediump int;
|
|
@@ -3624,7 +3624,7 @@ void main() {
|
|
|
3624
3624
|
gl_Position = vec4( position, 1.0 );
|
|
3625
3625
|
|
|
3626
3626
|
}
|
|
3627
|
-
`}function am(s){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===303||l===304,h=l===301||l===302;if(c||h)if(o.isRenderTargetTexture&&o.needsPMREMUpdate===!0){o.needsPMREMUpdate=!1;let u=e.get(o);return t===null&&(t=new Rl(s)),u=c?t.fromEquirectangular(o,u):t.fromCubemap(o,u),e.set(o,u),u.texture}else{if(e.has(o))return e.get(o).texture;{const u=o.image;if(c&&u&&u.height>0||h&&u&&n(u)){t===null&&(t=new Rl(s));const d=c?t.fromEquirectangular(o):t.fromCubemap(o);return e.set(o,d),o.addEventListener("dispose",r),d.texture}else return null}}}return o}function n(o){let l=0;const c=6;for(let h=0;h<c;h++)o[h]!==void 0&&l++;return l===c}function r(o){const l=o.target;l.removeEventListener("dispose",r);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:a}}function om(s){const e={};function t(i){if(e[i]!==void 0)return e[i];let n;switch(i){case"WEBGL_depth_texture":n=s.getExtension("WEBGL_depth_texture")||s.getExtension("MOZ_WEBGL_depth_texture")||s.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=s.getExtension("EXT_texture_filter_anisotropic")||s.getExtension("MOZ_EXT_texture_filter_anisotropic")||s.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=s.getExtension("WEBGL_compressed_texture_s3tc")||s.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=s.getExtension("WEBGL_compressed_texture_pvrtc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=s.getExtension(i)}return e[i]=n,n}return{has:function(i){return t(i)!==null},init:function(i){i.isWebGL2?(t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance")):(t("WEBGL_depth_texture"),t("OES_texture_float"),t("OES_texture_half_float"),t("OES_texture_half_float_linear"),t("OES_standard_derivatives"),t("OES_element_index_uint"),t("OES_vertex_array_object"),t("ANGLE_instanced_arrays")),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture")},get:function(i){const n=t(i);return n===null&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function lm(s,e,t,i){const n={},r=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const p in d.attributes)e.remove(d.attributes[p]);for(const p in d.morphAttributes){const v=d.morphAttributes[p];for(let m=0,g=v.length;m<g;m++)e.remove(v[m])}d.removeEventListener("dispose",a),delete n[d.id];const f=r.get(d);f&&(e.remove(f),r.delete(d)),i.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return n[d.id]===!0||(d.addEventListener("dispose",a),n[d.id]=!0,t.memory.geometries++),d}function l(u){const d=u.attributes;for(const p in d)e.update(d[p],s.ARRAY_BUFFER);const f=u.morphAttributes;for(const p in f){const v=f[p];for(let m=0,g=v.length;m<g;m++)e.update(v[m],s.ARRAY_BUFFER)}}function c(u){const d=[],f=u.index,p=u.attributes.position;let v=0;if(f!==null){const E=f.array;v=f.version;for(let _=0,T=E.length;_<T;_+=3){const b=E[_+0],R=E[_+1],A=E[_+2];d.push(b,R,R,A,A,b)}}else if(p!==void 0){const E=p.array;v=p.version;for(let _=0,T=E.length/3-1;_<T;_+=3){const b=_+0,R=_+1,A=_+2;d.push(b,R,R,A,A,b)}}else return;const m=new(Yo(d)?dl:ul)(d,1);m.version=v;const g=r.get(u);g&&e.remove(g),r.set(u,m)}function h(u){const d=r.get(u);if(d){const f=u.index;f!==null&&d.version<f.version&&c(u)}else c(u);return r.get(u)}return{get:o,update:l,getWireframeAttribute:h}}function cm(s,e,t,i){const n=i.isWebGL2;let r;function a(f){r=f}let o,l;function c(f){o=f.type,l=f.bytesPerElement}function h(f,p){s.drawElements(r,p,o,f*l),t.update(p,r,1)}function u(f,p,v){if(v===0)return;let m,g;if(n)m=s,g="drawElementsInstanced";else if(m=e.get("ANGLE_instanced_arrays"),g="drawElementsInstancedANGLE",m===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}m[g](r,p,o,f*l,v),t.update(p,r,v)}function d(f,p,v){if(v===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let g=0;g<v;g++)this.render(f[g]/l,p[g]);else{m.multiDrawElementsWEBGL(r,p,0,o,f,0,v);let g=0;for(let E=0;E<v;E++)g+=p[E];t.update(g,r,1)}}this.setMode=a,this.setIndex=c,this.render=h,this.renderInstances=u,this.renderMultiDraw=d}function hm(s){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(r,a,o){switch(t.calls++,a){case s.TRIANGLES:t.triangles+=o*(r/3);break;case s.LINES:t.lines+=o*(r/2);break;case s.LINE_STRIP:t.lines+=o*(r-1);break;case s.LINE_LOOP:t.lines+=o*r;break;case s.POINTS:t.points+=o*r;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function n(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:n,update:i}}function um(s,e){return s[0]-e[0]}function dm(s,e){return Math.abs(e[1])-Math.abs(s[1])}function fm(s,e,t){const i={},n=new Float32Array(8),r=new WeakMap,a=new Ft,o=[];for(let c=0;c<8;c++)o[c]=[c,0];function l(c,h,u){const d=c.morphTargetInfluences;if(e.isWebGL2===!0){const f=h.morphAttributes.position||h.morphAttributes.normal||h.morphAttributes.color,p=f!==void 0?f.length:0;let v=r.get(h);if(v===void 0||v.count!==p){let P=function(){U.dispose(),r.delete(h),h.removeEventListener("dispose",P)};v!==void 0&&v.texture.dispose();const E=h.morphAttributes.position!==void 0,_=h.morphAttributes.normal!==void 0,T=h.morphAttributes.color!==void 0,b=h.morphAttributes.position||[],R=h.morphAttributes.normal||[],A=h.morphAttributes.color||[];let C=0;E===!0&&(C=1),_===!0&&(C=2),T===!0&&(C=3);let S=h.attributes.position.count*C,y=1;S>e.maxTextureSize&&(y=Math.ceil(S/e.maxTextureSize),S=e.maxTextureSize);const w=new Float32Array(S*y*4*p),U=new el(w,S,y,p);U.type=1015,U.needsUpdate=!0;const X=C*4;for(let F=0;F<p;F++){const D=b[F],k=R[F],N=A[F],B=S*y*4*F;for(let q=0;q<D.count;q++){const V=q*X;E===!0&&(a.fromBufferAttribute(D,q),w[B+V+0]=a.x,w[B+V+1]=a.y,w[B+V+2]=a.z,w[B+V+3]=0),_===!0&&(a.fromBufferAttribute(k,q),w[B+V+4]=a.x,w[B+V+5]=a.y,w[B+V+6]=a.z,w[B+V+7]=0),T===!0&&(a.fromBufferAttribute(N,q),w[B+V+8]=a.x,w[B+V+9]=a.y,w[B+V+10]=a.z,w[B+V+11]=N.itemSize===4?a.w:1)}}v={count:p,texture:U,size:new nt(S,y)},r.set(h,v),h.addEventListener("dispose",P)}let m=0;for(let E=0;E<d.length;E++)m+=d[E];const g=h.morphTargetsRelative?1:1-m;u.getUniforms().setValue(s,"morphTargetBaseInfluence",g),u.getUniforms().setValue(s,"morphTargetInfluences",d),u.getUniforms().setValue(s,"morphTargetsTexture",v.texture,t),u.getUniforms().setValue(s,"morphTargetsTextureSize",v.size)}else{const f=d===void 0?0:d.length;let p=i[h.id];if(p===void 0||p.length!==f){p=[];for(let _=0;_<f;_++)p[_]=[_,0];i[h.id]=p}for(let _=0;_<f;_++){const T=p[_];T[0]=_,T[1]=d[_]}p.sort(dm);for(let _=0;_<8;_++)_<f&&p[_][1]?(o[_][0]=p[_][0],o[_][1]=p[_][1]):(o[_][0]=Number.MAX_SAFE_INTEGER,o[_][1]=0);o.sort(um);const v=h.morphAttributes.position,m=h.morphAttributes.normal;let g=0;for(let _=0;_<8;_++){const T=o[_],b=T[0],R=T[1];b!==Number.MAX_SAFE_INTEGER&&R?(v&&h.getAttribute("morphTarget"+_)!==v[b]&&h.setAttribute("morphTarget"+_,v[b]),m&&h.getAttribute("morphNormal"+_)!==m[b]&&h.setAttribute("morphNormal"+_,m[b]),n[_]=R,g+=R):(v&&h.hasAttribute("morphTarget"+_)===!0&&h.deleteAttribute("morphTarget"+_),m&&h.hasAttribute("morphNormal"+_)===!0&&h.deleteAttribute("morphNormal"+_),n[_]=0)}const E=h.morphTargetsRelative?1:1-g;u.getUniforms().setValue(s,"morphTargetBaseInfluence",E),u.getUniforms().setValue(s,"morphTargetInfluences",n)}}return{update:l}}function pm(s,e,t,i){let n=new WeakMap;function r(l){const c=i.render.frame,h=l.geometry,u=e.get(l,h);if(n.get(u)!==c&&(e.update(u),n.set(u,c)),l.isInstancedMesh&&(l.hasEventListener("dispose",o)===!1&&l.addEventListener("dispose",o),n.get(l)!==c&&(t.update(l.instanceMatrix,s.ARRAY_BUFFER),l.instanceColor!==null&&t.update(l.instanceColor,s.ARRAY_BUFFER),n.set(l,c))),l.isSkinnedMesh){const d=l.skeleton;n.get(d)!==c&&(d.update(),n.set(d,c))}return u}function a(){n=new WeakMap}function o(l){const c=l.target;c.removeEventListener("dispose",o),t.remove(c.instanceMatrix),c.instanceColor!==null&&t.remove(c.instanceColor)}return{update:r,dispose:a}}class Cl extends Xt{constructor(e,t,i,n,r,a,o,l,c,h){if(h=h!==void 0?h:1026,h!==1026&&h!==1027)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");i===void 0&&h===1026&&(i=1014),i===void 0&&h===1027&&(i=1020),super(null,n,r,a,o,l,h,i,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:1003,this.minFilter=l!==void 0?l:1003,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const wl=new Xt,Dl=new Cl(1,1);Dl.compareFunction=515;const Pl=new el,Fl=new Id,Ol=new xl,Ul=[],Nl=[],kl=new Float32Array(16),Bl=new Float32Array(9),Gl=new Float32Array(4);function Bn(s,e,t){const i=s[0];if(i<=0||i>0)return s;const n=e*t;let r=Ul[n];if(r===void 0&&(r=new Float32Array(n),Ul[n]=r),e!==0){i.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,s[a].toArray(r,o)}return r}function yt(s,e){if(s.length!==e.length)return!1;for(let t=0,i=s.length;t<i;t++)if(s[t]!==e[t])return!1;return!0}function Tt(s,e){for(let t=0,i=e.length;t<i;t++)s[t]=e[t]}function ir(s,e){let t=Nl[e];t===void 0&&(t=new Int32Array(e),Nl[e]=t);for(let i=0;i!==e;++i)t[i]=s.allocateTextureUnit();return t}function mm(s,e){const t=this.cache;t[0]!==e&&(s.uniform1f(this.addr,e),t[0]=e)}function gm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2fv(this.addr,e),Tt(t,e)}}function vm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(s.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(yt(t,e))return;s.uniform3fv(this.addr,e),Tt(t,e)}}function _m(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4fv(this.addr,e),Tt(t,e)}}function Em(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix2fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;Gl.set(i),s.uniformMatrix2fv(this.addr,!1,Gl),Tt(t,i)}}function xm(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix3fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;Bl.set(i),s.uniformMatrix3fv(this.addr,!1,Bl),Tt(t,i)}}function Sm(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix4fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;kl.set(i),s.uniformMatrix4fv(this.addr,!1,kl),Tt(t,i)}}function ym(s,e){const t=this.cache;t[0]!==e&&(s.uniform1i(this.addr,e),t[0]=e)}function Tm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2iv(this.addr,e),Tt(t,e)}}function Am(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(yt(t,e))return;s.uniform3iv(this.addr,e),Tt(t,e)}}function bm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4iv(this.addr,e),Tt(t,e)}}function Rm(s,e){const t=this.cache;t[0]!==e&&(s.uniform1ui(this.addr,e),t[0]=e)}function Mm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2uiv(this.addr,e),Tt(t,e)}}function Lm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(yt(t,e))return;s.uniform3uiv(this.addr,e),Tt(t,e)}}function Im(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4uiv(this.addr,e),Tt(t,e)}}function Cm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n);const r=this.type===s.SAMPLER_2D_SHADOW?Dl:wl;t.setTexture2D(e||r,n)}function wm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(e||Fl,n)}function Dm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(e||Ol,n)}function Pm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(e||Pl,n)}function Fm(s){switch(s){case 5126:return mm;case 35664:return gm;case 35665:return vm;case 35666:return _m;case 35674:return Em;case 35675:return xm;case 35676:return Sm;case 5124:case 35670:return ym;case 35667:case 35671:return Tm;case 35668:case 35672:return Am;case 35669:case 35673:return bm;case 5125:return Rm;case 36294:return Mm;case 36295:return Lm;case 36296:return Im;case 35678:case 36198:case 36298:case 36306:case 35682:return Cm;case 35679:case 36299:case 36307:return wm;case 35680:case 36300:case 36308:case 36293:return Dm;case 36289:case 36303:case 36311:case 36292:return Pm}}function Om(s,e){s.uniform1fv(this.addr,e)}function Um(s,e){const t=Bn(e,this.size,2);s.uniform2fv(this.addr,t)}function Nm(s,e){const t=Bn(e,this.size,3);s.uniform3fv(this.addr,t)}function km(s,e){const t=Bn(e,this.size,4);s.uniform4fv(this.addr,t)}function Bm(s,e){const t=Bn(e,this.size,4);s.uniformMatrix2fv(this.addr,!1,t)}function Gm(s,e){const t=Bn(e,this.size,9);s.uniformMatrix3fv(this.addr,!1,t)}function Vm(s,e){const t=Bn(e,this.size,16);s.uniformMatrix4fv(this.addr,!1,t)}function Hm(s,e){s.uniform1iv(this.addr,e)}function $m(s,e){s.uniform2iv(this.addr,e)}function zm(s,e){s.uniform3iv(this.addr,e)}function Wm(s,e){s.uniform4iv(this.addr,e)}function Km(s,e){s.uniform1uiv(this.addr,e)}function Xm(s,e){s.uniform2uiv(this.addr,e)}function Ym(s,e){s.uniform3uiv(this.addr,e)}function qm(s,e){s.uniform4uiv(this.addr,e)}function jm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture2D(e[a]||wl,r[a])}function Qm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture3D(e[a]||Fl,r[a])}function Zm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTextureCube(e[a]||Ol,r[a])}function Jm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture2DArray(e[a]||Pl,r[a])}function eg(s){switch(s){case 5126:return Om;case 35664:return Um;case 35665:return Nm;case 35666:return km;case 35674:return Bm;case 35675:return Gm;case 35676:return Vm;case 5124:case 35670:return Hm;case 35667:case 35671:return $m;case 35668:case 35672:return zm;case 35669:case 35673:return Wm;case 5125:return Km;case 36294:return Xm;case 36295:return Ym;case 36296:return qm;case 35678:case 36198:case 36298:case 36306:case 35682:return jm;case 35679:case 36299:case 36307:return Qm;case 35680:case 36300:case 36308:case 36293:return Zm;case 36289:case 36303:case 36311:case 36292:return Jm}}class tg{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=Fm(t.type)}}class ig{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=eg(t.type)}}class ng{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let r=0,a=n.length;r!==a;++r){const o=n[r];o.setValue(e,t[o.id],i)}}}const Aa=/(\w+)(\])?(\[|\.)?/g;function Vl(s,e){s.seq.push(e),s.map[e.id]=e}function sg(s,e,t){const i=s.name,n=i.length;for(Aa.lastIndex=0;;){const r=Aa.exec(i),a=Aa.lastIndex;let o=r[1];const l=r[2]==="]",c=r[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===n){Vl(t,c===void 0?new tg(o,s,e):new ig(o,s,e));break}else{let u=t.map[o];u===void 0&&(u=new ng(o),Vl(t,u)),t=u}}}class nr{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const r=e.getActiveUniform(t,n),a=e.getUniformLocation(t,r.name);sg(r,a,this)}}setValue(e,t,i,n){const r=this.map[t];r!==void 0&&r.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];n!==void 0&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let r=0,a=t.length;r!==a;++r){const o=t[r],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,r=e.length;n!==r;++n){const a=e[n];a.id in t&&i.push(a)}return i}}function Hl(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}const rg=37297;let ag=0;function og(s,e){const t=s.split(`
|
|
3627
|
+
`}function am(s){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===303||l===304,h=l===301||l===302;if(c||h)if(o.isRenderTargetTexture&&o.needsPMREMUpdate===!0){o.needsPMREMUpdate=!1;let u=e.get(o);return t===null&&(t=new Rl(s)),u=c?t.fromEquirectangular(o,u):t.fromCubemap(o,u),e.set(o,u),u.texture}else{if(e.has(o))return e.get(o).texture;{const u=o.image;if(c&&u&&u.height>0||h&&u&&n(u)){t===null&&(t=new Rl(s));const d=c?t.fromEquirectangular(o):t.fromCubemap(o);return e.set(o,d),o.addEventListener("dispose",r),d.texture}else return null}}}return o}function n(o){let l=0;const c=6;for(let h=0;h<c;h++)o[h]!==void 0&&l++;return l===c}function r(o){const l=o.target;l.removeEventListener("dispose",r);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:a}}function om(s){const e={};function t(i){if(e[i]!==void 0)return e[i];let n;switch(i){case"WEBGL_depth_texture":n=s.getExtension("WEBGL_depth_texture")||s.getExtension("MOZ_WEBGL_depth_texture")||s.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=s.getExtension("EXT_texture_filter_anisotropic")||s.getExtension("MOZ_EXT_texture_filter_anisotropic")||s.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=s.getExtension("WEBGL_compressed_texture_s3tc")||s.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=s.getExtension("WEBGL_compressed_texture_pvrtc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=s.getExtension(i)}return e[i]=n,n}return{has:function(i){return t(i)!==null},init:function(i){i.isWebGL2?(t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance")):(t("WEBGL_depth_texture"),t("OES_texture_float"),t("OES_texture_half_float"),t("OES_texture_half_float_linear"),t("OES_standard_derivatives"),t("OES_element_index_uint"),t("OES_vertex_array_object"),t("ANGLE_instanced_arrays")),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture")},get:function(i){const n=t(i);return n===null&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function lm(s,e,t,i){const n={},r=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const p in d.attributes)e.remove(d.attributes[p]);for(const p in d.morphAttributes){const v=d.morphAttributes[p];for(let m=0,g=v.length;m<g;m++)e.remove(v[m])}d.removeEventListener("dispose",a),delete n[d.id];const f=r.get(d);f&&(e.remove(f),r.delete(d)),i.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return n[d.id]===!0||(d.addEventListener("dispose",a),n[d.id]=!0,t.memory.geometries++),d}function l(u){const d=u.attributes;for(const p in d)e.update(d[p],s.ARRAY_BUFFER);const f=u.morphAttributes;for(const p in f){const v=f[p];for(let m=0,g=v.length;m<g;m++)e.update(v[m],s.ARRAY_BUFFER)}}function c(u){const d=[],f=u.index,p=u.attributes.position;let v=0;if(f!==null){const E=f.array;v=f.version;for(let _=0,T=E.length;_<T;_+=3){const b=E[_+0],R=E[_+1],A=E[_+2];d.push(b,R,R,A,A,b)}}else if(p!==void 0){const E=p.array;v=p.version;for(let _=0,T=E.length/3-1;_<T;_+=3){const b=_+0,R=_+1,A=_+2;d.push(b,R,R,A,A,b)}}else return;const m=new(Yo(d)?dl:ul)(d,1);m.version=v;const g=r.get(u);g&&e.remove(g),r.set(u,m)}function h(u){const d=r.get(u);if(d){const f=u.index;f!==null&&d.version<f.version&&c(u)}else c(u);return r.get(u)}return{get:o,update:l,getWireframeAttribute:h}}function cm(s,e,t,i){const n=i.isWebGL2;let r;function a(f){r=f}let o,l;function c(f){o=f.type,l=f.bytesPerElement}function h(f,p){s.drawElements(r,p,o,f*l),t.update(p,r,1)}function u(f,p,v){if(v===0)return;let m,g;if(n)m=s,g="drawElementsInstanced";else if(m=e.get("ANGLE_instanced_arrays"),g="drawElementsInstancedANGLE",m===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}m[g](r,p,o,f*l,v),t.update(p,r,v)}function d(f,p,v){if(v===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let g=0;g<v;g++)this.render(f[g]/l,p[g]);else{m.multiDrawElementsWEBGL(r,p,0,o,f,0,v);let g=0;for(let E=0;E<v;E++)g+=p[E];t.update(g,r,1)}}this.setMode=a,this.setIndex=c,this.render=h,this.renderInstances=u,this.renderMultiDraw=d}function hm(s){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(r,a,o){switch(t.calls++,a){case s.TRIANGLES:t.triangles+=o*(r/3);break;case s.LINES:t.lines+=o*(r/2);break;case s.LINE_STRIP:t.lines+=o*(r-1);break;case s.LINE_LOOP:t.lines+=o*r;break;case s.POINTS:t.points+=o*r;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function n(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:n,update:i}}function um(s,e){return s[0]-e[0]}function dm(s,e){return Math.abs(e[1])-Math.abs(s[1])}function fm(s,e,t){const i={},n=new Float32Array(8),r=new WeakMap,a=new Ft,o=[];for(let c=0;c<8;c++)o[c]=[c,0];function l(c,h,u){const d=c.morphTargetInfluences;if(e.isWebGL2===!0){const f=h.morphAttributes.position||h.morphAttributes.normal||h.morphAttributes.color,p=f!==void 0?f.length:0;let v=r.get(h);if(v===void 0||v.count!==p){let D=function(){N.dispose(),r.delete(h),h.removeEventListener("dispose",D)};v!==void 0&&v.texture.dispose();const E=h.morphAttributes.position!==void 0,_=h.morphAttributes.normal!==void 0,T=h.morphAttributes.color!==void 0,b=h.morphAttributes.position||[],R=h.morphAttributes.normal||[],A=h.morphAttributes.color||[];let C=0;E===!0&&(C=1),_===!0&&(C=2),T===!0&&(C=3);let S=h.attributes.position.count*C,y=1;S>e.maxTextureSize&&(y=Math.ceil(S/e.maxTextureSize),S=e.maxTextureSize);const w=new Float32Array(S*y*4*p),N=new el(w,S,y,p);N.type=1015,N.needsUpdate=!0;const Y=C*4;for(let F=0;F<p;F++){const O=b[F],$=R[F],k=A[F],B=S*y*4*F;for(let X=0;X<O.count;X++){const P=X*Y;E===!0&&(a.fromBufferAttribute(O,X),w[B+P+0]=a.x,w[B+P+1]=a.y,w[B+P+2]=a.z,w[B+P+3]=0),_===!0&&(a.fromBufferAttribute($,X),w[B+P+4]=a.x,w[B+P+5]=a.y,w[B+P+6]=a.z,w[B+P+7]=0),T===!0&&(a.fromBufferAttribute(k,X),w[B+P+8]=a.x,w[B+P+9]=a.y,w[B+P+10]=a.z,w[B+P+11]=k.itemSize===4?a.w:1)}}v={count:p,texture:N,size:new nt(S,y)},r.set(h,v),h.addEventListener("dispose",D)}let m=0;for(let E=0;E<d.length;E++)m+=d[E];const g=h.morphTargetsRelative?1:1-m;u.getUniforms().setValue(s,"morphTargetBaseInfluence",g),u.getUniforms().setValue(s,"morphTargetInfluences",d),u.getUniforms().setValue(s,"morphTargetsTexture",v.texture,t),u.getUniforms().setValue(s,"morphTargetsTextureSize",v.size)}else{const f=d===void 0?0:d.length;let p=i[h.id];if(p===void 0||p.length!==f){p=[];for(let _=0;_<f;_++)p[_]=[_,0];i[h.id]=p}for(let _=0;_<f;_++){const T=p[_];T[0]=_,T[1]=d[_]}p.sort(dm);for(let _=0;_<8;_++)_<f&&p[_][1]?(o[_][0]=p[_][0],o[_][1]=p[_][1]):(o[_][0]=Number.MAX_SAFE_INTEGER,o[_][1]=0);o.sort(um);const v=h.morphAttributes.position,m=h.morphAttributes.normal;let g=0;for(let _=0;_<8;_++){const T=o[_],b=T[0],R=T[1];b!==Number.MAX_SAFE_INTEGER&&R?(v&&h.getAttribute("morphTarget"+_)!==v[b]&&h.setAttribute("morphTarget"+_,v[b]),m&&h.getAttribute("morphNormal"+_)!==m[b]&&h.setAttribute("morphNormal"+_,m[b]),n[_]=R,g+=R):(v&&h.hasAttribute("morphTarget"+_)===!0&&h.deleteAttribute("morphTarget"+_),m&&h.hasAttribute("morphNormal"+_)===!0&&h.deleteAttribute("morphNormal"+_),n[_]=0)}const E=h.morphTargetsRelative?1:1-g;u.getUniforms().setValue(s,"morphTargetBaseInfluence",E),u.getUniforms().setValue(s,"morphTargetInfluences",n)}}return{update:l}}function pm(s,e,t,i){let n=new WeakMap;function r(l){const c=i.render.frame,h=l.geometry,u=e.get(l,h);if(n.get(u)!==c&&(e.update(u),n.set(u,c)),l.isInstancedMesh&&(l.hasEventListener("dispose",o)===!1&&l.addEventListener("dispose",o),n.get(l)!==c&&(t.update(l.instanceMatrix,s.ARRAY_BUFFER),l.instanceColor!==null&&t.update(l.instanceColor,s.ARRAY_BUFFER),n.set(l,c))),l.isSkinnedMesh){const d=l.skeleton;n.get(d)!==c&&(d.update(),n.set(d,c))}return u}function a(){n=new WeakMap}function o(l){const c=l.target;c.removeEventListener("dispose",o),t.remove(c.instanceMatrix),c.instanceColor!==null&&t.remove(c.instanceColor)}return{update:r,dispose:a}}class Cl extends Xt{constructor(e,t,i,n,r,a,o,l,c,h){if(h=h!==void 0?h:1026,h!==1026&&h!==1027)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");i===void 0&&h===1026&&(i=1014),i===void 0&&h===1027&&(i=1020),super(null,n,r,a,o,l,h,i,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:1003,this.minFilter=l!==void 0?l:1003,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const wl=new Xt,Dl=new Cl(1,1);Dl.compareFunction=515;const Pl=new el,Fl=new Id,Ol=new xl,Ul=[],Nl=[],kl=new Float32Array(16),Bl=new Float32Array(9),Gl=new Float32Array(4);function Bn(s,e,t){const i=s[0];if(i<=0||i>0)return s;const n=e*t;let r=Ul[n];if(r===void 0&&(r=new Float32Array(n),Ul[n]=r),e!==0){i.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,s[a].toArray(r,o)}return r}function yt(s,e){if(s.length!==e.length)return!1;for(let t=0,i=s.length;t<i;t++)if(s[t]!==e[t])return!1;return!0}function Tt(s,e){for(let t=0,i=e.length;t<i;t++)s[t]=e[t]}function ir(s,e){let t=Nl[e];t===void 0&&(t=new Int32Array(e),Nl[e]=t);for(let i=0;i!==e;++i)t[i]=s.allocateTextureUnit();return t}function mm(s,e){const t=this.cache;t[0]!==e&&(s.uniform1f(this.addr,e),t[0]=e)}function gm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2fv(this.addr,e),Tt(t,e)}}function vm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(s.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(yt(t,e))return;s.uniform3fv(this.addr,e),Tt(t,e)}}function _m(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4fv(this.addr,e),Tt(t,e)}}function Em(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix2fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;Gl.set(i),s.uniformMatrix2fv(this.addr,!1,Gl),Tt(t,i)}}function xm(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix3fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;Bl.set(i),s.uniformMatrix3fv(this.addr,!1,Bl),Tt(t,i)}}function Sm(s,e){const t=this.cache,i=e.elements;if(i===void 0){if(yt(t,e))return;s.uniformMatrix4fv(this.addr,!1,e),Tt(t,e)}else{if(yt(t,i))return;kl.set(i),s.uniformMatrix4fv(this.addr,!1,kl),Tt(t,i)}}function ym(s,e){const t=this.cache;t[0]!==e&&(s.uniform1i(this.addr,e),t[0]=e)}function Tm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2iv(this.addr,e),Tt(t,e)}}function Am(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(yt(t,e))return;s.uniform3iv(this.addr,e),Tt(t,e)}}function bm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4iv(this.addr,e),Tt(t,e)}}function Rm(s,e){const t=this.cache;t[0]!==e&&(s.uniform1ui(this.addr,e),t[0]=e)}function Mm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(yt(t,e))return;s.uniform2uiv(this.addr,e),Tt(t,e)}}function Lm(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(yt(t,e))return;s.uniform3uiv(this.addr,e),Tt(t,e)}}function Im(s,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(yt(t,e))return;s.uniform4uiv(this.addr,e),Tt(t,e)}}function Cm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n);const r=this.type===s.SAMPLER_2D_SHADOW?Dl:wl;t.setTexture2D(e||r,n)}function wm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(e||Fl,n)}function Dm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(e||Ol,n)}function Pm(s,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(s.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(e||Pl,n)}function Fm(s){switch(s){case 5126:return mm;case 35664:return gm;case 35665:return vm;case 35666:return _m;case 35674:return Em;case 35675:return xm;case 35676:return Sm;case 5124:case 35670:return ym;case 35667:case 35671:return Tm;case 35668:case 35672:return Am;case 35669:case 35673:return bm;case 5125:return Rm;case 36294:return Mm;case 36295:return Lm;case 36296:return Im;case 35678:case 36198:case 36298:case 36306:case 35682:return Cm;case 35679:case 36299:case 36307:return wm;case 35680:case 36300:case 36308:case 36293:return Dm;case 36289:case 36303:case 36311:case 36292:return Pm}}function Om(s,e){s.uniform1fv(this.addr,e)}function Um(s,e){const t=Bn(e,this.size,2);s.uniform2fv(this.addr,t)}function Nm(s,e){const t=Bn(e,this.size,3);s.uniform3fv(this.addr,t)}function km(s,e){const t=Bn(e,this.size,4);s.uniform4fv(this.addr,t)}function Bm(s,e){const t=Bn(e,this.size,4);s.uniformMatrix2fv(this.addr,!1,t)}function Gm(s,e){const t=Bn(e,this.size,9);s.uniformMatrix3fv(this.addr,!1,t)}function Vm(s,e){const t=Bn(e,this.size,16);s.uniformMatrix4fv(this.addr,!1,t)}function Hm(s,e){s.uniform1iv(this.addr,e)}function $m(s,e){s.uniform2iv(this.addr,e)}function zm(s,e){s.uniform3iv(this.addr,e)}function Wm(s,e){s.uniform4iv(this.addr,e)}function Km(s,e){s.uniform1uiv(this.addr,e)}function Xm(s,e){s.uniform2uiv(this.addr,e)}function Ym(s,e){s.uniform3uiv(this.addr,e)}function qm(s,e){s.uniform4uiv(this.addr,e)}function jm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture2D(e[a]||wl,r[a])}function Qm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture3D(e[a]||Fl,r[a])}function Zm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTextureCube(e[a]||Ol,r[a])}function Jm(s,e,t){const i=this.cache,n=e.length,r=ir(t,n);yt(i,r)||(s.uniform1iv(this.addr,r),Tt(i,r));for(let a=0;a!==n;++a)t.setTexture2DArray(e[a]||Pl,r[a])}function eg(s){switch(s){case 5126:return Om;case 35664:return Um;case 35665:return Nm;case 35666:return km;case 35674:return Bm;case 35675:return Gm;case 35676:return Vm;case 5124:case 35670:return Hm;case 35667:case 35671:return $m;case 35668:case 35672:return zm;case 35669:case 35673:return Wm;case 5125:return Km;case 36294:return Xm;case 36295:return Ym;case 36296:return qm;case 35678:case 36198:case 36298:case 36306:case 35682:return jm;case 35679:case 36299:case 36307:return Qm;case 35680:case 36300:case 36308:case 36293:return Zm;case 36289:case 36303:case 36311:case 36292:return Jm}}class tg{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=Fm(t.type)}}class ig{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=eg(t.type)}}class ng{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let r=0,a=n.length;r!==a;++r){const o=n[r];o.setValue(e,t[o.id],i)}}}const Aa=/(\w+)(\])?(\[|\.)?/g;function Vl(s,e){s.seq.push(e),s.map[e.id]=e}function sg(s,e,t){const i=s.name,n=i.length;for(Aa.lastIndex=0;;){const r=Aa.exec(i),a=Aa.lastIndex;let o=r[1];const l=r[2]==="]",c=r[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===n){Vl(t,c===void 0?new tg(o,s,e):new ig(o,s,e));break}else{let u=t.map[o];u===void 0&&(u=new ng(o),Vl(t,u)),t=u}}}class nr{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const r=e.getActiveUniform(t,n),a=e.getUniformLocation(t,r.name);sg(r,a,this)}}setValue(e,t,i,n){const r=this.map[t];r!==void 0&&r.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];n!==void 0&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let r=0,a=t.length;r!==a;++r){const o=t[r],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,r=e.length;n!==r;++n){const a=e[n];a.id in t&&i.push(a)}return i}}function Hl(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}const rg=37297;let ag=0;function og(s,e){const t=s.split(`
|
|
3628
3628
|
`),i=[],n=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let a=n;a<r;a++){const o=a+1;i.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return i.join(`
|
|
3629
3629
|
`)}function lg(s){const e=st.getPrimaries(st.workingColorSpace),t=st.getPrimaries(s);let i;switch(e===t?i="":e===Is&&t===Ls?i="LinearDisplayP3ToLinearSRGB":e===Ls&&t===Is&&(i="LinearSRGBToLinearDisplayP3"),s){case Ci:case Rs:return[i,"LinearTransferOETF"];case Mt:case jr:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",s),[i,"LinearTransferOETF"]}}function $l(s,e,t){const i=s.getShaderParameter(e,s.COMPILE_STATUS),n=s.getShaderInfoLog(e).trim();if(i&&n==="")return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const a=parseInt(r[1]);return t.toUpperCase()+`
|
|
3630
3630
|
|
|
@@ -3651,11 +3651,11 @@ precision `+s.precision+" int;";return s.precision==="highp"?e+=`
|
|
|
3651
3651
|
`)+`
|
|
3652
3652
|
`+g,E=["precision mediump sampler2DArray;","#define varying in",t.glslVersion===Ko?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Ko?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
|
|
3653
3653
|
`)+`
|
|
3654
|
-
`+E);const T=_+g+a,b=_+E+o,R=Hl(n,n.VERTEX_SHADER,T),A=Hl(n,n.FRAGMENT_SHADER,b);n.attachShader(m,R),n.attachShader(m,A),t.index0AttributeName!==void 0?n.bindAttribLocation(m,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(m,0,"position"),n.linkProgram(m);function C(
|
|
3654
|
+
`+E);const T=_+g+a,b=_+E+o,R=Hl(n,n.VERTEX_SHADER,T),A=Hl(n,n.FRAGMENT_SHADER,b);n.attachShader(m,R),n.attachShader(m,A),t.index0AttributeName!==void 0?n.bindAttribLocation(m,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(m,0,"position"),n.linkProgram(m);function C(N){if(s.debug.checkShaderErrors){const Y=n.getProgramInfoLog(m).trim(),D=n.getShaderInfoLog(R).trim(),F=n.getShaderInfoLog(A).trim();let O=!0,$=!0;if(n.getProgramParameter(m,n.LINK_STATUS)===!1)if(O=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(n,m,R,A);else{const k=$l(n,R,"vertex"),B=$l(n,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(m,n.VALIDATE_STATUS)+`
|
|
3655
3655
|
|
|
3656
|
-
Program Info Log: `+
|
|
3657
|
-
`+
|
|
3658
|
-
`+B)}else X!==""?console.warn("THREE.WebGLProgram: Program Info Log:",X):(P===""||F==="")&&(k=!1);k&&(U.diagnostics={runnable:D,programLog:X,vertexShader:{log:P,prefix:g},fragmentShader:{log:F,prefix:E}})}n.deleteShader(R),n.deleteShader(A),S=new nr(n,m),y=pg(n,m)}let S;this.getUniforms=function(){return S===void 0&&C(this),S};let y;this.getAttributes=function(){return y===void 0&&C(this),y};let w=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return w===!1&&(w=n.getProgramParameter(m,rg)),w},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=ag++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=R,this.fragmentShader=A,this}let Rg=0;class Mg{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),r=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Lg(e),t.set(e,i)),i}}class Lg{constructor(e){this.id=Rg++,this.code=e,this.usedTimes=0}}function Ig(s,e,t,i,n,r,a){const o=new sl,l=new Mg,c=[],h=n.isWebGL2,u=n.logarithmicDepthBuffer,d=n.vertexTextures;let f=n.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(S){return S===0?"uv":`uv${S}`}function m(S,y,w,U,X){const P=U.fog,F=X.geometry,D=S.isMeshStandardMaterial?U.environment:null,k=(S.isMeshStandardMaterial?t:e).get(S.envMap||D),N=k&&k.mapping===306?k.image.height:null,B=p[S.type];S.precision!==null&&(f=n.getMaxPrecision(S.precision),f!==S.precision&&console.warn("THREE.WebGLProgram.getParameters:",S.precision,"not supported, using",f,"instead."));const q=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,V=q!==void 0?q.length:0;let W=0;F.morphAttributes.position!==void 0&&(W=1),F.morphAttributes.normal!==void 0&&(W=2),F.morphAttributes.color!==void 0&&(W=3);let $,ee,ie,oe;if(B){const $t=Si[B];$=$t.vertexShader,ee=$t.fragmentShader}else $=S.vertexShader,ee=S.fragmentShader,l.update(S),ie=l.getVertexShaderID(S),oe=l.getFragmentShaderID(S);const me=s.getRenderTarget(),Se=X.isInstancedMesh===!0,be=X.isBatchedMesh===!0,Te=!!S.map,Ge=!!S.matcap,Y=!!k,Rt=!!S.aoMap,Re=!!S.lightMap,Ue=!!S.bumpMap,le=!!S.normalMap,$e=!!S.displacementMap,Me=!!S.emissiveMap,I=!!S.metalnessMap,M=!!S.roughnessMap,K=S.anisotropy>0,ne=S.clearcoat>0,re=S.iridescence>0,ae=S.sheen>0,ye=S.transmission>0,ue=K&&!!S.anisotropyMap,_e=ne&&!!S.clearcoatMap,Ie=ne&&!!S.clearcoatNormalMap,ke=ne&&!!S.clearcoatRoughnessMap,se=re&&!!S.iridescenceMap,Ze=re&&!!S.iridescenceThicknessMap,Qe=ae&&!!S.sheenColorMap,Ne=ae&&!!S.sheenRoughnessMap,Le=!!S.specularMap,xe=!!S.specularColorMap,ze=!!S.specularIntensityMap,it=ye&&!!S.transmissionMap,vt=ye&&!!S.thicknessMap,qe=!!S.gradientMap,he=!!S.alphaMap,O=S.alphaTest>0,fe=!!S.alphaHash,pe=!!S.extensions,Pe=!!F.attributes.uv1,Ce=!!F.attributes.uv2,ct=!!F.attributes.uv3;let ht=0;return S.toneMapped&&(me===null||me.isXRRenderTarget===!0)&&(ht=s.toneMapping),{isWebGL2:h,shaderID:B,shaderType:S.type,shaderName:S.name,vertexShader:$,fragmentShader:ee,defines:S.defines,customVertexShaderID:ie,customFragmentShaderID:oe,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:f,batching:be,instancing:Se,instancingColor:Se&&X.instanceColor!==null,supportsVertexTextures:d,outputColorSpace:me===null?s.outputColorSpace:me.isXRRenderTarget===!0?me.texture.colorSpace:Ci,map:Te,matcap:Ge,envMap:Y,envMapMode:Y&&k.mapping,envMapCubeUVHeight:N,aoMap:Rt,lightMap:Re,bumpMap:Ue,normalMap:le,displacementMap:d&&$e,emissiveMap:Me,normalMapObjectSpace:le&&S.normalMapType===1,normalMapTangentSpace:le&&S.normalMapType===0,metalnessMap:I,roughnessMap:M,anisotropy:K,anisotropyMap:ue,clearcoat:ne,clearcoatMap:_e,clearcoatNormalMap:Ie,clearcoatRoughnessMap:ke,iridescence:re,iridescenceMap:se,iridescenceThicknessMap:Ze,sheen:ae,sheenColorMap:Qe,sheenRoughnessMap:Ne,specularMap:Le,specularColorMap:xe,specularIntensityMap:ze,transmission:ye,transmissionMap:it,thicknessMap:vt,gradientMap:qe,opaque:S.transparent===!1&&S.blending===1,alphaMap:he,alphaTest:O,alphaHash:fe,combine:S.combine,mapUv:Te&&v(S.map.channel),aoMapUv:Rt&&v(S.aoMap.channel),lightMapUv:Re&&v(S.lightMap.channel),bumpMapUv:Ue&&v(S.bumpMap.channel),normalMapUv:le&&v(S.normalMap.channel),displacementMapUv:$e&&v(S.displacementMap.channel),emissiveMapUv:Me&&v(S.emissiveMap.channel),metalnessMapUv:I&&v(S.metalnessMap.channel),roughnessMapUv:M&&v(S.roughnessMap.channel),anisotropyMapUv:ue&&v(S.anisotropyMap.channel),clearcoatMapUv:_e&&v(S.clearcoatMap.channel),clearcoatNormalMapUv:Ie&&v(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ke&&v(S.clearcoatRoughnessMap.channel),iridescenceMapUv:se&&v(S.iridescenceMap.channel),iridescenceThicknessMapUv:Ze&&v(S.iridescenceThicknessMap.channel),sheenColorMapUv:Qe&&v(S.sheenColorMap.channel),sheenRoughnessMapUv:Ne&&v(S.sheenRoughnessMap.channel),specularMapUv:Le&&v(S.specularMap.channel),specularColorMapUv:xe&&v(S.specularColorMap.channel),specularIntensityMapUv:ze&&v(S.specularIntensityMap.channel),transmissionMapUv:it&&v(S.transmissionMap.channel),thicknessMapUv:vt&&v(S.thicknessMap.channel),alphaMapUv:he&&v(S.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(le||K),vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,vertexUv1s:Pe,vertexUv2s:Ce,vertexUv3s:ct,pointsUvs:X.isPoints===!0&&!!F.attributes.uv&&(Te||he),fog:!!P,useFog:S.fog===!0,fogExp2:P&&P.isFogExp2,flatShading:S.flatShading===!0,sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:X.isSkinnedMesh===!0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:V,morphTextureStride:W,numDirLights:y.directional.length,numPointLights:y.point.length,numSpotLights:y.spot.length,numSpotLightMaps:y.spotLightMap.length,numRectAreaLights:y.rectArea.length,numHemiLights:y.hemi.length,numDirLightShadows:y.directionalShadowMap.length,numPointLightShadows:y.pointShadowMap.length,numSpotLightShadows:y.spotShadowMap.length,numSpotLightShadowsWithMaps:y.numSpotLightShadowsWithMaps,numLightProbes:y.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:S.dithering,shadowMapEnabled:s.shadowMap.enabled&&w.length>0,shadowMapType:s.shadowMap.type,toneMapping:ht,useLegacyLights:s._useLegacyLights,decodeVideoTexture:Te&&S.map.isVideoTexture===!0&&st.getTransfer(S.map.colorSpace)===dt,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===2,flipSided:S.side===1,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionDerivatives:pe&&S.extensions.derivatives===!0,extensionFragDepth:pe&&S.extensions.fragDepth===!0,extensionDrawBuffers:pe&&S.extensions.drawBuffers===!0,extensionShaderTextureLOD:pe&&S.extensions.shaderTextureLOD===!0,extensionClipCullDistance:pe&&S.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),rendererExtensionFragDepth:h||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||i.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()}}function g(S){const y=[];if(S.shaderID?y.push(S.shaderID):(y.push(S.customVertexShaderID),y.push(S.customFragmentShaderID)),S.defines!==void 0)for(const w in S.defines)y.push(w),y.push(S.defines[w]);return S.isRawShaderMaterial===!1&&(E(y,S),_(y,S),y.push(s.outputColorSpace)),y.push(S.customProgramCacheKey),y.join()}function E(S,y){S.push(y.precision),S.push(y.outputColorSpace),S.push(y.envMapMode),S.push(y.envMapCubeUVHeight),S.push(y.mapUv),S.push(y.alphaMapUv),S.push(y.lightMapUv),S.push(y.aoMapUv),S.push(y.bumpMapUv),S.push(y.normalMapUv),S.push(y.displacementMapUv),S.push(y.emissiveMapUv),S.push(y.metalnessMapUv),S.push(y.roughnessMapUv),S.push(y.anisotropyMapUv),S.push(y.clearcoatMapUv),S.push(y.clearcoatNormalMapUv),S.push(y.clearcoatRoughnessMapUv),S.push(y.iridescenceMapUv),S.push(y.iridescenceThicknessMapUv),S.push(y.sheenColorMapUv),S.push(y.sheenRoughnessMapUv),S.push(y.specularMapUv),S.push(y.specularColorMapUv),S.push(y.specularIntensityMapUv),S.push(y.transmissionMapUv),S.push(y.thicknessMapUv),S.push(y.combine),S.push(y.fogExp2),S.push(y.sizeAttenuation),S.push(y.morphTargetsCount),S.push(y.morphAttributeCount),S.push(y.numDirLights),S.push(y.numPointLights),S.push(y.numSpotLights),S.push(y.numSpotLightMaps),S.push(y.numHemiLights),S.push(y.numRectAreaLights),S.push(y.numDirLightShadows),S.push(y.numPointLightShadows),S.push(y.numSpotLightShadows),S.push(y.numSpotLightShadowsWithMaps),S.push(y.numLightProbes),S.push(y.shadowMapType),S.push(y.toneMapping),S.push(y.numClippingPlanes),S.push(y.numClipIntersection),S.push(y.depthPacking)}function _(S,y){o.disableAll(),y.isWebGL2&&o.enable(0),y.supportsVertexTextures&&o.enable(1),y.instancing&&o.enable(2),y.instancingColor&&o.enable(3),y.matcap&&o.enable(4),y.envMap&&o.enable(5),y.normalMapObjectSpace&&o.enable(6),y.normalMapTangentSpace&&o.enable(7),y.clearcoat&&o.enable(8),y.iridescence&&o.enable(9),y.alphaTest&&o.enable(10),y.vertexColors&&o.enable(11),y.vertexAlphas&&o.enable(12),y.vertexUv1s&&o.enable(13),y.vertexUv2s&&o.enable(14),y.vertexUv3s&&o.enable(15),y.vertexTangents&&o.enable(16),y.anisotropy&&o.enable(17),y.alphaHash&&o.enable(18),y.batching&&o.enable(19),S.push(o.mask),o.disableAll(),y.fog&&o.enable(0),y.useFog&&o.enable(1),y.flatShading&&o.enable(2),y.logarithmicDepthBuffer&&o.enable(3),y.skinning&&o.enable(4),y.morphTargets&&o.enable(5),y.morphNormals&&o.enable(6),y.morphColors&&o.enable(7),y.premultipliedAlpha&&o.enable(8),y.shadowMapEnabled&&o.enable(9),y.useLegacyLights&&o.enable(10),y.doubleSided&&o.enable(11),y.flipSided&&o.enable(12),y.useDepthPacking&&o.enable(13),y.dithering&&o.enable(14),y.transmission&&o.enable(15),y.sheen&&o.enable(16),y.opaque&&o.enable(17),y.pointsUvs&&o.enable(18),y.decodeVideoTexture&&o.enable(19),S.push(o.mask)}function T(S){const y=p[S.type];let w;if(y){const U=Si[y];w=$d.clone(U.uniforms)}else w=S.uniforms;return w}function b(S,y){let w;for(let U=0,X=c.length;U<X;U++){const P=c[U];if(P.cacheKey===y){w=P,++w.usedTimes;break}}return w===void 0&&(w=new bg(s,y,S,r),c.push(w)),w}function R(S){if(--S.usedTimes===0){const y=c.indexOf(S);c[y]=c[c.length-1],c.pop(),S.destroy()}}function A(S){l.remove(S)}function C(){l.dispose()}return{getParameters:m,getProgramCacheKey:g,getUniforms:T,acquireProgram:b,releaseProgram:R,releaseShaderCache:A,programs:c,dispose:C}}function Cg(){let s=new WeakMap;function e(r){let a=s.get(r);return a===void 0&&(a={},s.set(r,a)),a}function t(r){s.delete(r)}function i(r,a,o){s.get(r)[a]=o}function n(){s=new WeakMap}return{get:e,remove:t,update:i,dispose:n}}function wg(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.material.id!==e.material.id?s.material.id-e.material.id:s.z!==e.z?s.z-e.z:s.id-e.id}function Yl(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.z!==e.z?e.z-s.z:s.id-e.id}function ql(){const s=[];let e=0;const t=[],i=[],n=[];function r(){e=0,t.length=0,i.length=0,n.length=0}function a(u,d,f,p,v,m){let g=s[e];return g===void 0?(g={id:u.id,object:u,geometry:d,material:f,groupOrder:p,renderOrder:u.renderOrder,z:v,group:m},s[e]=g):(g.id=u.id,g.object=u,g.geometry=d,g.material=f,g.groupOrder=p,g.renderOrder=u.renderOrder,g.z=v,g.group=m),e++,g}function o(u,d,f,p,v,m){const g=a(u,d,f,p,v,m);f.transmission>0?i.push(g):f.transparent===!0?n.push(g):t.push(g)}function l(u,d,f,p,v,m){const g=a(u,d,f,p,v,m);f.transmission>0?i.unshift(g):f.transparent===!0?n.unshift(g):t.unshift(g)}function c(u,d){t.length>1&&t.sort(u||wg),i.length>1&&i.sort(d||Yl),n.length>1&&n.sort(d||Yl)}function h(){for(let u=e,d=s.length;u<d;u++){const f=s[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:n,init:r,push:o,unshift:l,finish:h,sort:c}}function Dg(){let s=new WeakMap;function e(i,n){const r=s.get(i);let a;return r===void 0?(a=new ql,s.set(i,[a])):n>=r.length?(a=new ql,r.push(a)):a=r[n],a}function t(){s=new WeakMap}return{get:e,dispose:t}}function Pg(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new Q,color:new rt};break;case"SpotLight":t={position:new Q,direction:new Q,color:new rt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new Q,color:new rt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new Q,skyColor:new rt,groundColor:new rt};break;case"RectAreaLight":t={color:new rt,position:new Q,halfWidth:new Q,halfHeight:new Q};break}return s[e.id]=t,t}}}function Fg(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let Og=0;function Ug(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function Ng(s,e){const t=new Pg,i=Fg(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)n.probe.push(new Q);const r=new Q,a=new Ot,o=new Ot;function l(h,u){let d=0,f=0,p=0;for(let U=0;U<9;U++)n.probe[U].set(0,0,0);let v=0,m=0,g=0,E=0,_=0,T=0,b=0,R=0,A=0,C=0,S=0;h.sort(Ug);const y=u===!0?Math.PI:1;for(let U=0,X=h.length;U<X;U++){const P=h[U],F=P.color,D=P.intensity,k=P.distance,N=P.shadow&&P.shadow.map?P.shadow.map.texture:null;if(P.isAmbientLight)d+=F.r*D*y,f+=F.g*D*y,p+=F.b*D*y;else if(P.isLightProbe){for(let B=0;B<9;B++)n.probe[B].addScaledVector(P.sh.coefficients[B],D);S++}else if(P.isDirectionalLight){const B=t.get(P);if(B.color.copy(P.color).multiplyScalar(P.intensity*y),P.castShadow){const q=P.shadow,V=i.get(P);V.shadowBias=q.bias,V.shadowNormalBias=q.normalBias,V.shadowRadius=q.radius,V.shadowMapSize=q.mapSize,n.directionalShadow[v]=V,n.directionalShadowMap[v]=N,n.directionalShadowMatrix[v]=P.shadow.matrix,T++}n.directional[v]=B,v++}else if(P.isSpotLight){const B=t.get(P);B.position.setFromMatrixPosition(P.matrixWorld),B.color.copy(F).multiplyScalar(D*y),B.distance=k,B.coneCos=Math.cos(P.angle),B.penumbraCos=Math.cos(P.angle*(1-P.penumbra)),B.decay=P.decay,n.spot[g]=B;const q=P.shadow;if(P.map&&(n.spotLightMap[A]=P.map,A++,q.updateMatrices(P),P.castShadow&&C++),n.spotLightMatrix[g]=q.matrix,P.castShadow){const V=i.get(P);V.shadowBias=q.bias,V.shadowNormalBias=q.normalBias,V.shadowRadius=q.radius,V.shadowMapSize=q.mapSize,n.spotShadow[g]=V,n.spotShadowMap[g]=N,R++}g++}else if(P.isRectAreaLight){const B=t.get(P);B.color.copy(F).multiplyScalar(D),B.halfWidth.set(P.width*.5,0,0),B.halfHeight.set(0,P.height*.5,0),n.rectArea[E]=B,E++}else if(P.isPointLight){const B=t.get(P);if(B.color.copy(P.color).multiplyScalar(P.intensity*y),B.distance=P.distance,B.decay=P.decay,P.castShadow){const q=P.shadow,V=i.get(P);V.shadowBias=q.bias,V.shadowNormalBias=q.normalBias,V.shadowRadius=q.radius,V.shadowMapSize=q.mapSize,V.shadowCameraNear=q.camera.near,V.shadowCameraFar=q.camera.far,n.pointShadow[m]=V,n.pointShadowMap[m]=N,n.pointShadowMatrix[m]=P.shadow.matrix,b++}n.point[m]=B,m++}else if(P.isHemisphereLight){const B=t.get(P);B.skyColor.copy(P.color).multiplyScalar(D*y),B.groundColor.copy(P.groundColor).multiplyScalar(D*y),n.hemi[_]=B,_++}}E>0&&(e.isWebGL2?s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_FLOAT_1,n.rectAreaLTC2=ce.LTC_FLOAT_2):(n.rectAreaLTC1=ce.LTC_HALF_1,n.rectAreaLTC2=ce.LTC_HALF_2):s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_FLOAT_1,n.rectAreaLTC2=ce.LTC_FLOAT_2):s.has("OES_texture_half_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_HALF_1,n.rectAreaLTC2=ce.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),n.ambient[0]=d,n.ambient[1]=f,n.ambient[2]=p;const w=n.hash;(w.directionalLength!==v||w.pointLength!==m||w.spotLength!==g||w.rectAreaLength!==E||w.hemiLength!==_||w.numDirectionalShadows!==T||w.numPointShadows!==b||w.numSpotShadows!==R||w.numSpotMaps!==A||w.numLightProbes!==S)&&(n.directional.length=v,n.spot.length=g,n.rectArea.length=E,n.point.length=m,n.hemi.length=_,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=b,n.pointShadowMap.length=b,n.spotShadow.length=R,n.spotShadowMap.length=R,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=b,n.spotLightMatrix.length=R+A-C,n.spotLightMap.length=A,n.numSpotLightShadowsWithMaps=C,n.numLightProbes=S,w.directionalLength=v,w.pointLength=m,w.spotLength=g,w.rectAreaLength=E,w.hemiLength=_,w.numDirectionalShadows=T,w.numPointShadows=b,w.numSpotShadows=R,w.numSpotMaps=A,w.numLightProbes=S,n.version=Og++)}function c(h,u){let d=0,f=0,p=0,v=0,m=0;const g=u.matrixWorldInverse;for(let E=0,_=h.length;E<_;E++){const T=h[E];if(T.isDirectionalLight){const b=n.directional[d];b.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),b.direction.sub(r),b.direction.transformDirection(g),d++}else if(T.isSpotLight){const b=n.spot[p];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),b.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),b.direction.sub(r),b.direction.transformDirection(g),p++}else if(T.isRectAreaLight){const b=n.rectArea[v];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),o.identity(),a.copy(T.matrixWorld),a.premultiply(g),o.extractRotation(a),b.halfWidth.set(T.width*.5,0,0),b.halfHeight.set(0,T.height*.5,0),b.halfWidth.applyMatrix4(o),b.halfHeight.applyMatrix4(o),v++}else if(T.isPointLight){const b=n.point[f];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),f++}else if(T.isHemisphereLight){const b=n.hemi[m];b.direction.setFromMatrixPosition(T.matrixWorld),b.direction.transformDirection(g),m++}}}return{setup:l,setupView:c,state:n}}function jl(s,e){const t=new Ng(s,e),i=[],n=[];function r(){i.length=0,n.length=0}function a(u){i.push(u)}function o(u){n.push(u)}function l(u){t.setup(i,u)}function c(u){t.setupView(i,u)}return{init:r,state:{lightsArray:i,shadowsArray:n,lights:t},setupLights:l,setupLightsView:c,pushLight:a,pushShadow:o}}function kg(s,e){let t=new WeakMap;function i(r,a=0){const o=t.get(r);let l;return o===void 0?(l=new jl(s,e),t.set(r,[l])):a>=o.length?(l=new jl(s,e),o.push(l)):l=o[a],l}function n(){t=new WeakMap}return{get:i,dispose:n}}class Bg extends Hs{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Gg extends Hs{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const Vg=`void main() {
|
|
3656
|
+
Program Info Log: `+Y+`
|
|
3657
|
+
`+k+`
|
|
3658
|
+
`+B)}else Y!==""?console.warn("THREE.WebGLProgram: Program Info Log:",Y):(D===""||F==="")&&($=!1);$&&(N.diagnostics={runnable:O,programLog:Y,vertexShader:{log:D,prefix:g},fragmentShader:{log:F,prefix:E}})}n.deleteShader(R),n.deleteShader(A),S=new nr(n,m),y=pg(n,m)}let S;this.getUniforms=function(){return S===void 0&&C(this),S};let y;this.getAttributes=function(){return y===void 0&&C(this),y};let w=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return w===!1&&(w=n.getProgramParameter(m,rg)),w},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=ag++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=R,this.fragmentShader=A,this}let Rg=0;class Mg{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),r=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Lg(e),t.set(e,i)),i}}class Lg{constructor(e){this.id=Rg++,this.code=e,this.usedTimes=0}}function Ig(s,e,t,i,n,r,a){const o=new sl,l=new Mg,c=[],h=n.isWebGL2,u=n.logarithmicDepthBuffer,d=n.vertexTextures;let f=n.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(S){return S===0?"uv":`uv${S}`}function m(S,y,w,N,Y){const D=N.fog,F=Y.geometry,O=S.isMeshStandardMaterial?N.environment:null,$=(S.isMeshStandardMaterial?t:e).get(S.envMap||O),k=$&&$.mapping===306?$.image.height:null,B=p[S.type];S.precision!==null&&(f=n.getMaxPrecision(S.precision),f!==S.precision&&console.warn("THREE.WebGLProgram.getParameters:",S.precision,"not supported, using",f,"instead."));const X=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,P=X!==void 0?X.length:0;let V=0;F.morphAttributes.position!==void 0&&(V=1),F.morphAttributes.normal!==void 0&&(V=2),F.morphAttributes.color!==void 0&&(V=3);let G,J,ie,oe;if(B){const $t=Si[B];G=$t.vertexShader,J=$t.fragmentShader}else G=S.vertexShader,J=S.fragmentShader,l.update(S),ie=l.getVertexShaderID(S),oe=l.getFragmentShaderID(S);const me=s.getRenderTarget(),Se=Y.isInstancedMesh===!0,be=Y.isBatchedMesh===!0,Te=!!S.map,Ge=!!S.matcap,q=!!$,Rt=!!S.aoMap,Re=!!S.lightMap,Ue=!!S.bumpMap,le=!!S.normalMap,$e=!!S.displacementMap,Me=!!S.emissiveMap,I=!!S.metalnessMap,M=!!S.roughnessMap,K=S.anisotropy>0,ne=S.clearcoat>0,re=S.iridescence>0,ae=S.sheen>0,ye=S.transmission>0,ue=K&&!!S.anisotropyMap,_e=ne&&!!S.clearcoatMap,Ie=ne&&!!S.clearcoatNormalMap,ke=ne&&!!S.clearcoatRoughnessMap,se=re&&!!S.iridescenceMap,Ze=re&&!!S.iridescenceThicknessMap,Qe=ae&&!!S.sheenColorMap,Ne=ae&&!!S.sheenRoughnessMap,Le=!!S.specularMap,xe=!!S.specularColorMap,ze=!!S.specularIntensityMap,it=ye&&!!S.transmissionMap,vt=ye&&!!S.thicknessMap,qe=!!S.gradientMap,he=!!S.alphaMap,U=S.alphaTest>0,fe=!!S.alphaHash,pe=!!S.extensions,Pe=!!F.attributes.uv1,Ce=!!F.attributes.uv2,ct=!!F.attributes.uv3;let ht=0;return S.toneMapped&&(me===null||me.isXRRenderTarget===!0)&&(ht=s.toneMapping),{isWebGL2:h,shaderID:B,shaderType:S.type,shaderName:S.name,vertexShader:G,fragmentShader:J,defines:S.defines,customVertexShaderID:ie,customFragmentShaderID:oe,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:f,batching:be,instancing:Se,instancingColor:Se&&Y.instanceColor!==null,supportsVertexTextures:d,outputColorSpace:me===null?s.outputColorSpace:me.isXRRenderTarget===!0?me.texture.colorSpace:Ci,map:Te,matcap:Ge,envMap:q,envMapMode:q&&$.mapping,envMapCubeUVHeight:k,aoMap:Rt,lightMap:Re,bumpMap:Ue,normalMap:le,displacementMap:d&&$e,emissiveMap:Me,normalMapObjectSpace:le&&S.normalMapType===1,normalMapTangentSpace:le&&S.normalMapType===0,metalnessMap:I,roughnessMap:M,anisotropy:K,anisotropyMap:ue,clearcoat:ne,clearcoatMap:_e,clearcoatNormalMap:Ie,clearcoatRoughnessMap:ke,iridescence:re,iridescenceMap:se,iridescenceThicknessMap:Ze,sheen:ae,sheenColorMap:Qe,sheenRoughnessMap:Ne,specularMap:Le,specularColorMap:xe,specularIntensityMap:ze,transmission:ye,transmissionMap:it,thicknessMap:vt,gradientMap:qe,opaque:S.transparent===!1&&S.blending===1,alphaMap:he,alphaTest:U,alphaHash:fe,combine:S.combine,mapUv:Te&&v(S.map.channel),aoMapUv:Rt&&v(S.aoMap.channel),lightMapUv:Re&&v(S.lightMap.channel),bumpMapUv:Ue&&v(S.bumpMap.channel),normalMapUv:le&&v(S.normalMap.channel),displacementMapUv:$e&&v(S.displacementMap.channel),emissiveMapUv:Me&&v(S.emissiveMap.channel),metalnessMapUv:I&&v(S.metalnessMap.channel),roughnessMapUv:M&&v(S.roughnessMap.channel),anisotropyMapUv:ue&&v(S.anisotropyMap.channel),clearcoatMapUv:_e&&v(S.clearcoatMap.channel),clearcoatNormalMapUv:Ie&&v(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ke&&v(S.clearcoatRoughnessMap.channel),iridescenceMapUv:se&&v(S.iridescenceMap.channel),iridescenceThicknessMapUv:Ze&&v(S.iridescenceThicknessMap.channel),sheenColorMapUv:Qe&&v(S.sheenColorMap.channel),sheenRoughnessMapUv:Ne&&v(S.sheenRoughnessMap.channel),specularMapUv:Le&&v(S.specularMap.channel),specularColorMapUv:xe&&v(S.specularColorMap.channel),specularIntensityMapUv:ze&&v(S.specularIntensityMap.channel),transmissionMapUv:it&&v(S.transmissionMap.channel),thicknessMapUv:vt&&v(S.thicknessMap.channel),alphaMapUv:he&&v(S.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(le||K),vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,vertexUv1s:Pe,vertexUv2s:Ce,vertexUv3s:ct,pointsUvs:Y.isPoints===!0&&!!F.attributes.uv&&(Te||he),fog:!!D,useFog:S.fog===!0,fogExp2:D&&D.isFogExp2,flatShading:S.flatShading===!0,sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:Y.isSkinnedMesh===!0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:P,morphTextureStride:V,numDirLights:y.directional.length,numPointLights:y.point.length,numSpotLights:y.spot.length,numSpotLightMaps:y.spotLightMap.length,numRectAreaLights:y.rectArea.length,numHemiLights:y.hemi.length,numDirLightShadows:y.directionalShadowMap.length,numPointLightShadows:y.pointShadowMap.length,numSpotLightShadows:y.spotShadowMap.length,numSpotLightShadowsWithMaps:y.numSpotLightShadowsWithMaps,numLightProbes:y.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:S.dithering,shadowMapEnabled:s.shadowMap.enabled&&w.length>0,shadowMapType:s.shadowMap.type,toneMapping:ht,useLegacyLights:s._useLegacyLights,decodeVideoTexture:Te&&S.map.isVideoTexture===!0&&st.getTransfer(S.map.colorSpace)===dt,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===2,flipSided:S.side===1,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionDerivatives:pe&&S.extensions.derivatives===!0,extensionFragDepth:pe&&S.extensions.fragDepth===!0,extensionDrawBuffers:pe&&S.extensions.drawBuffers===!0,extensionShaderTextureLOD:pe&&S.extensions.shaderTextureLOD===!0,extensionClipCullDistance:pe&&S.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),rendererExtensionFragDepth:h||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||i.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()}}function g(S){const y=[];if(S.shaderID?y.push(S.shaderID):(y.push(S.customVertexShaderID),y.push(S.customFragmentShaderID)),S.defines!==void 0)for(const w in S.defines)y.push(w),y.push(S.defines[w]);return S.isRawShaderMaterial===!1&&(E(y,S),_(y,S),y.push(s.outputColorSpace)),y.push(S.customProgramCacheKey),y.join()}function E(S,y){S.push(y.precision),S.push(y.outputColorSpace),S.push(y.envMapMode),S.push(y.envMapCubeUVHeight),S.push(y.mapUv),S.push(y.alphaMapUv),S.push(y.lightMapUv),S.push(y.aoMapUv),S.push(y.bumpMapUv),S.push(y.normalMapUv),S.push(y.displacementMapUv),S.push(y.emissiveMapUv),S.push(y.metalnessMapUv),S.push(y.roughnessMapUv),S.push(y.anisotropyMapUv),S.push(y.clearcoatMapUv),S.push(y.clearcoatNormalMapUv),S.push(y.clearcoatRoughnessMapUv),S.push(y.iridescenceMapUv),S.push(y.iridescenceThicknessMapUv),S.push(y.sheenColorMapUv),S.push(y.sheenRoughnessMapUv),S.push(y.specularMapUv),S.push(y.specularColorMapUv),S.push(y.specularIntensityMapUv),S.push(y.transmissionMapUv),S.push(y.thicknessMapUv),S.push(y.combine),S.push(y.fogExp2),S.push(y.sizeAttenuation),S.push(y.morphTargetsCount),S.push(y.morphAttributeCount),S.push(y.numDirLights),S.push(y.numPointLights),S.push(y.numSpotLights),S.push(y.numSpotLightMaps),S.push(y.numHemiLights),S.push(y.numRectAreaLights),S.push(y.numDirLightShadows),S.push(y.numPointLightShadows),S.push(y.numSpotLightShadows),S.push(y.numSpotLightShadowsWithMaps),S.push(y.numLightProbes),S.push(y.shadowMapType),S.push(y.toneMapping),S.push(y.numClippingPlanes),S.push(y.numClipIntersection),S.push(y.depthPacking)}function _(S,y){o.disableAll(),y.isWebGL2&&o.enable(0),y.supportsVertexTextures&&o.enable(1),y.instancing&&o.enable(2),y.instancingColor&&o.enable(3),y.matcap&&o.enable(4),y.envMap&&o.enable(5),y.normalMapObjectSpace&&o.enable(6),y.normalMapTangentSpace&&o.enable(7),y.clearcoat&&o.enable(8),y.iridescence&&o.enable(9),y.alphaTest&&o.enable(10),y.vertexColors&&o.enable(11),y.vertexAlphas&&o.enable(12),y.vertexUv1s&&o.enable(13),y.vertexUv2s&&o.enable(14),y.vertexUv3s&&o.enable(15),y.vertexTangents&&o.enable(16),y.anisotropy&&o.enable(17),y.alphaHash&&o.enable(18),y.batching&&o.enable(19),S.push(o.mask),o.disableAll(),y.fog&&o.enable(0),y.useFog&&o.enable(1),y.flatShading&&o.enable(2),y.logarithmicDepthBuffer&&o.enable(3),y.skinning&&o.enable(4),y.morphTargets&&o.enable(5),y.morphNormals&&o.enable(6),y.morphColors&&o.enable(7),y.premultipliedAlpha&&o.enable(8),y.shadowMapEnabled&&o.enable(9),y.useLegacyLights&&o.enable(10),y.doubleSided&&o.enable(11),y.flipSided&&o.enable(12),y.useDepthPacking&&o.enable(13),y.dithering&&o.enable(14),y.transmission&&o.enable(15),y.sheen&&o.enable(16),y.opaque&&o.enable(17),y.pointsUvs&&o.enable(18),y.decodeVideoTexture&&o.enable(19),S.push(o.mask)}function T(S){const y=p[S.type];let w;if(y){const N=Si[y];w=$d.clone(N.uniforms)}else w=S.uniforms;return w}function b(S,y){let w;for(let N=0,Y=c.length;N<Y;N++){const D=c[N];if(D.cacheKey===y){w=D,++w.usedTimes;break}}return w===void 0&&(w=new bg(s,y,S,r),c.push(w)),w}function R(S){if(--S.usedTimes===0){const y=c.indexOf(S);c[y]=c[c.length-1],c.pop(),S.destroy()}}function A(S){l.remove(S)}function C(){l.dispose()}return{getParameters:m,getProgramCacheKey:g,getUniforms:T,acquireProgram:b,releaseProgram:R,releaseShaderCache:A,programs:c,dispose:C}}function Cg(){let s=new WeakMap;function e(r){let a=s.get(r);return a===void 0&&(a={},s.set(r,a)),a}function t(r){s.delete(r)}function i(r,a,o){s.get(r)[a]=o}function n(){s=new WeakMap}return{get:e,remove:t,update:i,dispose:n}}function wg(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.material.id!==e.material.id?s.material.id-e.material.id:s.z!==e.z?s.z-e.z:s.id-e.id}function Yl(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.z!==e.z?e.z-s.z:s.id-e.id}function ql(){const s=[];let e=0;const t=[],i=[],n=[];function r(){e=0,t.length=0,i.length=0,n.length=0}function a(u,d,f,p,v,m){let g=s[e];return g===void 0?(g={id:u.id,object:u,geometry:d,material:f,groupOrder:p,renderOrder:u.renderOrder,z:v,group:m},s[e]=g):(g.id=u.id,g.object=u,g.geometry=d,g.material=f,g.groupOrder=p,g.renderOrder=u.renderOrder,g.z=v,g.group=m),e++,g}function o(u,d,f,p,v,m){const g=a(u,d,f,p,v,m);f.transmission>0?i.push(g):f.transparent===!0?n.push(g):t.push(g)}function l(u,d,f,p,v,m){const g=a(u,d,f,p,v,m);f.transmission>0?i.unshift(g):f.transparent===!0?n.unshift(g):t.unshift(g)}function c(u,d){t.length>1&&t.sort(u||wg),i.length>1&&i.sort(d||Yl),n.length>1&&n.sort(d||Yl)}function h(){for(let u=e,d=s.length;u<d;u++){const f=s[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:n,init:r,push:o,unshift:l,finish:h,sort:c}}function Dg(){let s=new WeakMap;function e(i,n){const r=s.get(i);let a;return r===void 0?(a=new ql,s.set(i,[a])):n>=r.length?(a=new ql,r.push(a)):a=r[n],a}function t(){s=new WeakMap}return{get:e,dispose:t}}function Pg(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new Q,color:new rt};break;case"SpotLight":t={position:new Q,direction:new Q,color:new rt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new Q,color:new rt,distance:0,decay:0};break;case"HemisphereLight":t={direction:new Q,skyColor:new rt,groundColor:new rt};break;case"RectAreaLight":t={color:new rt,position:new Q,halfWidth:new Q,halfHeight:new Q};break}return s[e.id]=t,t}}}function Fg(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new nt,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let Og=0;function Ug(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function Ng(s,e){const t=new Pg,i=Fg(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)n.probe.push(new Q);const r=new Q,a=new Ot,o=new Ot;function l(h,u){let d=0,f=0,p=0;for(let N=0;N<9;N++)n.probe[N].set(0,0,0);let v=0,m=0,g=0,E=0,_=0,T=0,b=0,R=0,A=0,C=0,S=0;h.sort(Ug);const y=u===!0?Math.PI:1;for(let N=0,Y=h.length;N<Y;N++){const D=h[N],F=D.color,O=D.intensity,$=D.distance,k=D.shadow&&D.shadow.map?D.shadow.map.texture:null;if(D.isAmbientLight)d+=F.r*O*y,f+=F.g*O*y,p+=F.b*O*y;else if(D.isLightProbe){for(let B=0;B<9;B++)n.probe[B].addScaledVector(D.sh.coefficients[B],O);S++}else if(D.isDirectionalLight){const B=t.get(D);if(B.color.copy(D.color).multiplyScalar(D.intensity*y),D.castShadow){const X=D.shadow,P=i.get(D);P.shadowBias=X.bias,P.shadowNormalBias=X.normalBias,P.shadowRadius=X.radius,P.shadowMapSize=X.mapSize,n.directionalShadow[v]=P,n.directionalShadowMap[v]=k,n.directionalShadowMatrix[v]=D.shadow.matrix,T++}n.directional[v]=B,v++}else if(D.isSpotLight){const B=t.get(D);B.position.setFromMatrixPosition(D.matrixWorld),B.color.copy(F).multiplyScalar(O*y),B.distance=$,B.coneCos=Math.cos(D.angle),B.penumbraCos=Math.cos(D.angle*(1-D.penumbra)),B.decay=D.decay,n.spot[g]=B;const X=D.shadow;if(D.map&&(n.spotLightMap[A]=D.map,A++,X.updateMatrices(D),D.castShadow&&C++),n.spotLightMatrix[g]=X.matrix,D.castShadow){const P=i.get(D);P.shadowBias=X.bias,P.shadowNormalBias=X.normalBias,P.shadowRadius=X.radius,P.shadowMapSize=X.mapSize,n.spotShadow[g]=P,n.spotShadowMap[g]=k,R++}g++}else if(D.isRectAreaLight){const B=t.get(D);B.color.copy(F).multiplyScalar(O),B.halfWidth.set(D.width*.5,0,0),B.halfHeight.set(0,D.height*.5,0),n.rectArea[E]=B,E++}else if(D.isPointLight){const B=t.get(D);if(B.color.copy(D.color).multiplyScalar(D.intensity*y),B.distance=D.distance,B.decay=D.decay,D.castShadow){const X=D.shadow,P=i.get(D);P.shadowBias=X.bias,P.shadowNormalBias=X.normalBias,P.shadowRadius=X.radius,P.shadowMapSize=X.mapSize,P.shadowCameraNear=X.camera.near,P.shadowCameraFar=X.camera.far,n.pointShadow[m]=P,n.pointShadowMap[m]=k,n.pointShadowMatrix[m]=D.shadow.matrix,b++}n.point[m]=B,m++}else if(D.isHemisphereLight){const B=t.get(D);B.skyColor.copy(D.color).multiplyScalar(O*y),B.groundColor.copy(D.groundColor).multiplyScalar(O*y),n.hemi[_]=B,_++}}E>0&&(e.isWebGL2?s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_FLOAT_1,n.rectAreaLTC2=ce.LTC_FLOAT_2):(n.rectAreaLTC1=ce.LTC_HALF_1,n.rectAreaLTC2=ce.LTC_HALF_2):s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_FLOAT_1,n.rectAreaLTC2=ce.LTC_FLOAT_2):s.has("OES_texture_half_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_HALF_1,n.rectAreaLTC2=ce.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),n.ambient[0]=d,n.ambient[1]=f,n.ambient[2]=p;const w=n.hash;(w.directionalLength!==v||w.pointLength!==m||w.spotLength!==g||w.rectAreaLength!==E||w.hemiLength!==_||w.numDirectionalShadows!==T||w.numPointShadows!==b||w.numSpotShadows!==R||w.numSpotMaps!==A||w.numLightProbes!==S)&&(n.directional.length=v,n.spot.length=g,n.rectArea.length=E,n.point.length=m,n.hemi.length=_,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=b,n.pointShadowMap.length=b,n.spotShadow.length=R,n.spotShadowMap.length=R,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=b,n.spotLightMatrix.length=R+A-C,n.spotLightMap.length=A,n.numSpotLightShadowsWithMaps=C,n.numLightProbes=S,w.directionalLength=v,w.pointLength=m,w.spotLength=g,w.rectAreaLength=E,w.hemiLength=_,w.numDirectionalShadows=T,w.numPointShadows=b,w.numSpotShadows=R,w.numSpotMaps=A,w.numLightProbes=S,n.version=Og++)}function c(h,u){let d=0,f=0,p=0,v=0,m=0;const g=u.matrixWorldInverse;for(let E=0,_=h.length;E<_;E++){const T=h[E];if(T.isDirectionalLight){const b=n.directional[d];b.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),b.direction.sub(r),b.direction.transformDirection(g),d++}else if(T.isSpotLight){const b=n.spot[p];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),b.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),b.direction.sub(r),b.direction.transformDirection(g),p++}else if(T.isRectAreaLight){const b=n.rectArea[v];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),o.identity(),a.copy(T.matrixWorld),a.premultiply(g),o.extractRotation(a),b.halfWidth.set(T.width*.5,0,0),b.halfHeight.set(0,T.height*.5,0),b.halfWidth.applyMatrix4(o),b.halfHeight.applyMatrix4(o),v++}else if(T.isPointLight){const b=n.point[f];b.position.setFromMatrixPosition(T.matrixWorld),b.position.applyMatrix4(g),f++}else if(T.isHemisphereLight){const b=n.hemi[m];b.direction.setFromMatrixPosition(T.matrixWorld),b.direction.transformDirection(g),m++}}}return{setup:l,setupView:c,state:n}}function jl(s,e){const t=new Ng(s,e),i=[],n=[];function r(){i.length=0,n.length=0}function a(u){i.push(u)}function o(u){n.push(u)}function l(u){t.setup(i,u)}function c(u){t.setupView(i,u)}return{init:r,state:{lightsArray:i,shadowsArray:n,lights:t},setupLights:l,setupLightsView:c,pushLight:a,pushShadow:o}}function kg(s,e){let t=new WeakMap;function i(r,a=0){const o=t.get(r);let l;return o===void 0?(l=new jl(s,e),t.set(r,[l])):a>=o.length?(l=new jl(s,e),o.push(l)):l=o[a],l}function n(){t=new WeakMap}return{get:i,dispose:n}}class Bg extends Hs{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Gg extends Hs{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const Vg=`void main() {
|
|
3659
3659
|
gl_Position = vec4( position, 1.0 );
|
|
3660
3660
|
}`,Hg=`uniform sampler2D shadow_pass;
|
|
3661
3661
|
uniform vec2 resolution;
|
|
@@ -3683,7 +3683,7 @@ void main() {
|
|
|
3683
3683
|
squared_mean = squared_mean / samples;
|
|
3684
3684
|
float std_dev = sqrt( squared_mean - mean * mean );
|
|
3685
3685
|
gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
|
|
3686
|
-
}`;function $g(s,e,t){let i=new Sl;const n=new nt,r=new nt,a=new Ft,o=new Bg({depthPacking:3201}),l=new Gg,c={},h=t.maxTextureSize,u={0:1,1:0,2:2},d=new on({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new nt},radius:{value:4}},vertexShader:Vg,fragmentShader:Hg}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new ji;p.setAttribute("position",new Ei(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new mi(p,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let g=this.type;this.render=function(R,A,C){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||R.length===0)return;const S=s.getRenderTarget(),y=s.getActiveCubeFace(),w=s.getActiveMipmapLevel(),U=s.state;U.setBlending(0),U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const X=g!==3&&this.type===3,P=g===3&&this.type!==3;for(let F=0,D=R.length;F<D;F++){const k=R[F],N=k.shadow;if(N===void 0){console.warn("THREE.WebGLShadowMap:",k,"has no shadow.");continue}if(N.autoUpdate===!1&&N.needsUpdate===!1)continue;n.copy(N.mapSize);const B=N.getFrameExtents();if(n.multiply(B),r.copy(N.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(r.x=Math.floor(h/B.x),n.x=r.x*B.x,N.mapSize.x=r.x),n.y>h&&(r.y=Math.floor(h/B.y),n.y=r.y*B.y,N.mapSize.y=r.y)),N.map===null||X===!0||P===!0){const V=this.type!==3?{minFilter:1003,magFilter:1003}:{};N.map!==null&&N.map.dispose(),N.map=new nn(n.x,n.y,V),N.map.texture.name=k.name+".shadowMap",N.camera.updateProjectionMatrix()}s.setRenderTarget(N.map),s.clear();const q=N.getViewportCount();for(let V=0;V<q;V++){const W=N.getViewport(V);a.set(r.x*W.x,r.y*W.y,r.x*W.z,r.y*W.w),U.viewport(a),N.updateMatrices(k,V),i=N.getFrustum(),T(A,C,N.camera,k,this.type)}N.isPointLightShadow!==!0&&this.type===3&&E(N,C),N.needsUpdate=!1}g=this.type,m.needsUpdate=!1,s.setRenderTarget(S,y,w)};function E(R,A){const C=e.update(v);d.defines.VSM_SAMPLES!==R.blurSamples&&(d.defines.VSM_SAMPLES=R.blurSamples,f.defines.VSM_SAMPLES=R.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),R.mapPass===null&&(R.mapPass=new nn(n.x,n.y)),d.uniforms.shadow_pass.value=R.map.texture,d.uniforms.resolution.value=R.mapSize,d.uniforms.radius.value=R.radius,s.setRenderTarget(R.mapPass),s.clear(),s.renderBufferDirect(A,null,C,d,v,null),f.uniforms.shadow_pass.value=R.mapPass.texture,f.uniforms.resolution.value=R.mapSize,f.uniforms.radius.value=R.radius,s.setRenderTarget(R.map),s.clear(),s.renderBufferDirect(A,null,C,f,v,null)}function _(R,A,C,S){let y=null;const w=C.isPointLight===!0?R.customDistanceMaterial:R.customDepthMaterial;if(w!==void 0)y=w;else if(y=C.isPointLight===!0?l:o,s.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0){const U=y.uuid,X=A.uuid;let P=c[U];P===void 0&&(P={},c[U]=P);let F=P[X];F===void 0&&(F=y.clone(),P[X]=F,A.addEventListener("dispose",b)),y=F}if(y.visible=A.visible,y.wireframe=A.wireframe,S===3?y.side=A.shadowSide!==null?A.shadowSide:A.side:y.side=A.shadowSide!==null?A.shadowSide:u[A.side],y.alphaMap=A.alphaMap,y.alphaTest=A.alphaTest,y.map=A.map,y.clipShadows=A.clipShadows,y.clippingPlanes=A.clippingPlanes,y.clipIntersection=A.clipIntersection,y.displacementMap=A.displacementMap,y.displacementScale=A.displacementScale,y.displacementBias=A.displacementBias,y.wireframeLinewidth=A.wireframeLinewidth,y.linewidth=A.linewidth,C.isPointLight===!0&&y.isMeshDistanceMaterial===!0){const U=s.properties.get(y);U.light=C}return y}function T(R,A,C,S,y){if(R.visible===!1)return;if(R.layers.test(A.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&y===3)&&(!R.frustumCulled||i.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,R.matrixWorld);const X=e.update(R),P=R.material;if(Array.isArray(P)){const F=X.groups;for(let D=0,k=F.length;D<k;D++){const N=F[D],B=P[N.materialIndex];if(B&&B.visible){const q=_(R,B,S,y);R.onBeforeShadow(s,R,A,C,X,q,N),s.renderBufferDirect(C,null,X,q,R,N),R.onAfterShadow(s,R,A,C,X,q,N)}}}else if(P.visible){const F=_(R,P,S,y);R.onBeforeShadow(s,R,A,C,X,F,null),s.renderBufferDirect(C,null,X,F,R,null),R.onAfterShadow(s,R,A,C,X,F,null)}}const U=R.children;for(let X=0,P=U.length;X<P;X++)T(U[X],A,C,S,y)}function b(R){R.target.removeEventListener("dispose",b);for(const C in c){const S=c[C],y=R.target.uuid;y in S&&(S[y].dispose(),delete S[y])}}}function zg(s,e,t){const i=t.isWebGL2;function n(){let O=!1;const fe=new Ft;let pe=null;const Pe=new Ft(0,0,0,0);return{setMask:function(Ce){pe!==Ce&&!O&&(s.colorMask(Ce,Ce,Ce,Ce),pe=Ce)},setLocked:function(Ce){O=Ce},setClear:function(Ce,ct,ht,Dt,$t){$t===!0&&(Ce*=Dt,ct*=Dt,ht*=Dt),fe.set(Ce,ct,ht,Dt),Pe.equals(fe)===!1&&(s.clearColor(Ce,ct,ht,Dt),Pe.copy(fe))},reset:function(){O=!1,pe=null,Pe.set(-1,0,0,0)}}}function r(){let O=!1,fe=null,pe=null,Pe=null;return{setTest:function(Ce){Ce?be(s.DEPTH_TEST):Te(s.DEPTH_TEST)},setMask:function(Ce){fe!==Ce&&!O&&(s.depthMask(Ce),fe=Ce)},setFunc:function(Ce){if(pe!==Ce){switch(Ce){case 0:s.depthFunc(s.NEVER);break;case 1:s.depthFunc(s.ALWAYS);break;case 2:s.depthFunc(s.LESS);break;case 3:s.depthFunc(s.LEQUAL);break;case 4:s.depthFunc(s.EQUAL);break;case 5:s.depthFunc(s.GEQUAL);break;case 6:s.depthFunc(s.GREATER);break;case 7:s.depthFunc(s.NOTEQUAL);break;default:s.depthFunc(s.LEQUAL)}pe=Ce}},setLocked:function(Ce){O=Ce},setClear:function(Ce){Pe!==Ce&&(s.clearDepth(Ce),Pe=Ce)},reset:function(){O=!1,fe=null,pe=null,Pe=null}}}function a(){let O=!1,fe=null,pe=null,Pe=null,Ce=null,ct=null,ht=null,Dt=null,$t=null;return{setTest:function(ut){O||(ut?be(s.STENCIL_TEST):Te(s.STENCIL_TEST))},setMask:function(ut){fe!==ut&&!O&&(s.stencilMask(ut),fe=ut)},setFunc:function(ut,zt,Ii){(pe!==ut||Pe!==zt||Ce!==Ii)&&(s.stencilFunc(ut,zt,Ii),pe=ut,Pe=zt,Ce=Ii)},setOp:function(ut,zt,Ii){(ct!==ut||ht!==zt||Dt!==Ii)&&(s.stencilOp(ut,zt,Ii),ct=ut,ht=zt,Dt=Ii)},setLocked:function(ut){O=ut},setClear:function(ut){$t!==ut&&(s.clearStencil(ut),$t=ut)},reset:function(){O=!1,fe=null,pe=null,Pe=null,Ce=null,ct=null,ht=null,Dt=null,$t=null}}}const o=new n,l=new r,c=new a,h=new WeakMap,u=new WeakMap;let d={},f={},p=new WeakMap,v=[],m=null,g=!1,E=null,_=null,T=null,b=null,R=null,A=null,C=null,S=new rt(0,0,0),y=0,w=!1,U=null,X=null,P=null,F=null,D=null;const k=s.getParameter(s.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let N=!1,B=0;const q=s.getParameter(s.VERSION);q.indexOf("WebGL")!==-1?(B=parseFloat(/^WebGL (\d)/.exec(q)[1]),N=B>=1):q.indexOf("OpenGL ES")!==-1&&(B=parseFloat(/^OpenGL ES (\d)/.exec(q)[1]),N=B>=2);let V=null,W={};const $=s.getParameter(s.SCISSOR_BOX),ee=s.getParameter(s.VIEWPORT),ie=new Ft().fromArray($),oe=new Ft().fromArray(ee);function me(O,fe,pe,Pe){const Ce=new Uint8Array(4),ct=s.createTexture();s.bindTexture(O,ct),s.texParameteri(O,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(O,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let ht=0;ht<pe;ht++)i&&(O===s.TEXTURE_3D||O===s.TEXTURE_2D_ARRAY)?s.texImage3D(fe,0,s.RGBA,1,1,Pe,0,s.RGBA,s.UNSIGNED_BYTE,Ce):s.texImage2D(fe+ht,0,s.RGBA,1,1,0,s.RGBA,s.UNSIGNED_BYTE,Ce);return ct}const Se={};Se[s.TEXTURE_2D]=me(s.TEXTURE_2D,s.TEXTURE_2D,1),Se[s.TEXTURE_CUBE_MAP]=me(s.TEXTURE_CUBE_MAP,s.TEXTURE_CUBE_MAP_POSITIVE_X,6),i&&(Se[s.TEXTURE_2D_ARRAY]=me(s.TEXTURE_2D_ARRAY,s.TEXTURE_2D_ARRAY,1,1),Se[s.TEXTURE_3D]=me(s.TEXTURE_3D,s.TEXTURE_3D,1,1)),o.setClear(0,0,0,1),l.setClear(1),c.setClear(0),be(s.DEPTH_TEST),l.setFunc(3),Me(!1),I(1),be(s.CULL_FACE),le(0);function be(O){d[O]!==!0&&(s.enable(O),d[O]=!0)}function Te(O){d[O]!==!1&&(s.disable(O),d[O]=!1)}function Ge(O,fe){return f[O]!==fe?(s.bindFramebuffer(O,fe),f[O]=fe,i&&(O===s.DRAW_FRAMEBUFFER&&(f[s.FRAMEBUFFER]=fe),O===s.FRAMEBUFFER&&(f[s.DRAW_FRAMEBUFFER]=fe)),!0):!1}function Y(O,fe){let pe=v,Pe=!1;if(O)if(pe=p.get(fe),pe===void 0&&(pe=[],p.set(fe,pe)),O.isWebGLMultipleRenderTargets){const Ce=O.texture;if(pe.length!==Ce.length||pe[0]!==s.COLOR_ATTACHMENT0){for(let ct=0,ht=Ce.length;ct<ht;ct++)pe[ct]=s.COLOR_ATTACHMENT0+ct;pe.length=Ce.length,Pe=!0}}else pe[0]!==s.COLOR_ATTACHMENT0&&(pe[0]=s.COLOR_ATTACHMENT0,Pe=!0);else pe[0]!==s.BACK&&(pe[0]=s.BACK,Pe=!0);Pe&&(t.isWebGL2?s.drawBuffers(pe):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(pe))}function Rt(O){return m!==O?(s.useProgram(O),m=O,!0):!1}const Re={100:s.FUNC_ADD,101:s.FUNC_SUBTRACT,102:s.FUNC_REVERSE_SUBTRACT};if(i)Re[103]=s.MIN,Re[104]=s.MAX;else{const O=e.get("EXT_blend_minmax");O!==null&&(Re[103]=O.MIN_EXT,Re[104]=O.MAX_EXT)}const Ue={200:s.ZERO,201:s.ONE,202:s.SRC_COLOR,204:s.SRC_ALPHA,210:s.SRC_ALPHA_SATURATE,208:s.DST_COLOR,206:s.DST_ALPHA,203:s.ONE_MINUS_SRC_COLOR,205:s.ONE_MINUS_SRC_ALPHA,209:s.ONE_MINUS_DST_COLOR,207:s.ONE_MINUS_DST_ALPHA,211:s.CONSTANT_COLOR,212:s.ONE_MINUS_CONSTANT_COLOR,213:s.CONSTANT_ALPHA,214:s.ONE_MINUS_CONSTANT_ALPHA};function le(O,fe,pe,Pe,Ce,ct,ht,Dt,$t,ut){if(O===0){g===!0&&(Te(s.BLEND),g=!1);return}if(g===!1&&(be(s.BLEND),g=!0),O!==5){if(O!==E||ut!==w){if((_!==100||R!==100)&&(s.blendEquation(s.FUNC_ADD),_=100,R=100),ut)switch(O){case 1:s.blendFuncSeparate(s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:s.blendFunc(s.ONE,s.ONE);break;case 3:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:s.blendFuncSeparate(s.ZERO,s.SRC_COLOR,s.ZERO,s.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",O);break}else switch(O){case 1:s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:s.blendFunc(s.SRC_ALPHA,s.ONE);break;case 3:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:s.blendFunc(s.ZERO,s.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",O);break}T=null,b=null,A=null,C=null,S.set(0,0,0),y=0,E=O,w=ut}return}Ce=Ce||fe,ct=ct||pe,ht=ht||Pe,(fe!==_||Ce!==R)&&(s.blendEquationSeparate(Re[fe],Re[Ce]),_=fe,R=Ce),(pe!==T||Pe!==b||ct!==A||ht!==C)&&(s.blendFuncSeparate(Ue[pe],Ue[Pe],Ue[ct],Ue[ht]),T=pe,b=Pe,A=ct,C=ht),(Dt.equals(S)===!1||$t!==y)&&(s.blendColor(Dt.r,Dt.g,Dt.b,$t),S.copy(Dt),y=$t),E=O,w=!1}function $e(O,fe){O.side===2?Te(s.CULL_FACE):be(s.CULL_FACE);let pe=O.side===1;fe&&(pe=!pe),Me(pe),O.blending===1&&O.transparent===!1?le(0):le(O.blending,O.blendEquation,O.blendSrc,O.blendDst,O.blendEquationAlpha,O.blendSrcAlpha,O.blendDstAlpha,O.blendColor,O.blendAlpha,O.premultipliedAlpha),l.setFunc(O.depthFunc),l.setTest(O.depthTest),l.setMask(O.depthWrite),o.setMask(O.colorWrite);const Pe=O.stencilWrite;c.setTest(Pe),Pe&&(c.setMask(O.stencilWriteMask),c.setFunc(O.stencilFunc,O.stencilRef,O.stencilFuncMask),c.setOp(O.stencilFail,O.stencilZFail,O.stencilZPass)),K(O.polygonOffset,O.polygonOffsetFactor,O.polygonOffsetUnits),O.alphaToCoverage===!0?be(s.SAMPLE_ALPHA_TO_COVERAGE):Te(s.SAMPLE_ALPHA_TO_COVERAGE)}function Me(O){U!==O&&(O?s.frontFace(s.CW):s.frontFace(s.CCW),U=O)}function I(O){O!==0?(be(s.CULL_FACE),O!==X&&(O===1?s.cullFace(s.BACK):O===2?s.cullFace(s.FRONT):s.cullFace(s.FRONT_AND_BACK))):Te(s.CULL_FACE),X=O}function M(O){O!==P&&(N&&s.lineWidth(O),P=O)}function K(O,fe,pe){O?(be(s.POLYGON_OFFSET_FILL),(F!==fe||D!==pe)&&(s.polygonOffset(fe,pe),F=fe,D=pe)):Te(s.POLYGON_OFFSET_FILL)}function ne(O){O?be(s.SCISSOR_TEST):Te(s.SCISSOR_TEST)}function re(O){O===void 0&&(O=s.TEXTURE0+k-1),V!==O&&(s.activeTexture(O),V=O)}function ae(O,fe,pe){pe===void 0&&(V===null?pe=s.TEXTURE0+k-1:pe=V);let Pe=W[pe];Pe===void 0&&(Pe={type:void 0,texture:void 0},W[pe]=Pe),(Pe.type!==O||Pe.texture!==fe)&&(V!==pe&&(s.activeTexture(pe),V=pe),s.bindTexture(O,fe||Se[O]),Pe.type=O,Pe.texture=fe)}function ye(){const O=W[V];O!==void 0&&O.type!==void 0&&(s.bindTexture(O.type,null),O.type=void 0,O.texture=void 0)}function ue(){try{s.compressedTexImage2D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function _e(){try{s.compressedTexImage3D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function Ie(){try{s.texSubImage2D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function ke(){try{s.texSubImage3D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function se(){try{s.compressedTexSubImage2D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function Ze(){try{s.compressedTexSubImage3D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function Qe(){try{s.texStorage2D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function Ne(){try{s.texStorage3D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function Le(){try{s.texImage2D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function xe(){try{s.texImage3D.apply(s,arguments)}catch(O){console.error("THREE.WebGLState:",O)}}function ze(O){ie.equals(O)===!1&&(s.scissor(O.x,O.y,O.z,O.w),ie.copy(O))}function it(O){oe.equals(O)===!1&&(s.viewport(O.x,O.y,O.z,O.w),oe.copy(O))}function vt(O,fe){let pe=u.get(fe);pe===void 0&&(pe=new WeakMap,u.set(fe,pe));let Pe=pe.get(O);Pe===void 0&&(Pe=s.getUniformBlockIndex(fe,O.name),pe.set(O,Pe))}function qe(O,fe){const Pe=u.get(fe).get(O);h.get(fe)!==Pe&&(s.uniformBlockBinding(fe,Pe,O.__bindingPointIndex),h.set(fe,Pe))}function he(){s.disable(s.BLEND),s.disable(s.CULL_FACE),s.disable(s.DEPTH_TEST),s.disable(s.POLYGON_OFFSET_FILL),s.disable(s.SCISSOR_TEST),s.disable(s.STENCIL_TEST),s.disable(s.SAMPLE_ALPHA_TO_COVERAGE),s.blendEquation(s.FUNC_ADD),s.blendFunc(s.ONE,s.ZERO),s.blendFuncSeparate(s.ONE,s.ZERO,s.ONE,s.ZERO),s.blendColor(0,0,0,0),s.colorMask(!0,!0,!0,!0),s.clearColor(0,0,0,0),s.depthMask(!0),s.depthFunc(s.LESS),s.clearDepth(1),s.stencilMask(4294967295),s.stencilFunc(s.ALWAYS,0,4294967295),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),s.clearStencil(0),s.cullFace(s.BACK),s.frontFace(s.CCW),s.polygonOffset(0,0),s.activeTexture(s.TEXTURE0),s.bindFramebuffer(s.FRAMEBUFFER,null),i===!0&&(s.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),s.bindFramebuffer(s.READ_FRAMEBUFFER,null)),s.useProgram(null),s.lineWidth(1),s.scissor(0,0,s.canvas.width,s.canvas.height),s.viewport(0,0,s.canvas.width,s.canvas.height),d={},V=null,W={},f={},p=new WeakMap,v=[],m=null,g=!1,E=null,_=null,T=null,b=null,R=null,A=null,C=null,S=new rt(0,0,0),y=0,w=!1,U=null,X=null,P=null,F=null,D=null,ie.set(0,0,s.canvas.width,s.canvas.height),oe.set(0,0,s.canvas.width,s.canvas.height),o.reset(),l.reset(),c.reset()}return{buffers:{color:o,depth:l,stencil:c},enable:be,disable:Te,bindFramebuffer:Ge,drawBuffers:Y,useProgram:Rt,setBlending:le,setMaterial:$e,setFlipSided:Me,setCullFace:I,setLineWidth:M,setPolygonOffset:K,setScissorTest:ne,activeTexture:re,bindTexture:ae,unbindTexture:ye,compressedTexImage2D:ue,compressedTexImage3D:_e,texImage2D:Le,texImage3D:xe,updateUBOMapping:vt,uniformBlockBinding:qe,texStorage2D:Qe,texStorage3D:Ne,texSubImage2D:Ie,texSubImage3D:ke,compressedTexSubImage2D:se,compressedTexSubImage3D:Ze,scissor:ze,viewport:it,reset:he}}function Wg(s,e,t,i,n,r,a){const o=n.isWebGL2,l=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new WeakMap;let u;const d=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,M){return f?new OffscreenCanvas(I,M):Cs("canvas")}function v(I,M,K,ne){let re=1;if((I.width>ne||I.height>ne)&&(re=ne/Math.max(I.width,I.height)),re<1||M===!0)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap){const ae=M?ea:Math.floor,ye=ae(re*I.width),ue=ae(re*I.height);u===void 0&&(u=p(ye,ue));const _e=K?p(ye,ue):u;return _e.width=ye,_e.height=ue,_e.getContext("2d").drawImage(I,0,0,ye,ue),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+I.width+"x"+I.height+") to ("+ye+"x"+ue+")."),_e}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+I.width+"x"+I.height+")."),I;return I}function m(I){return Xo(I.width)&&Xo(I.height)}function g(I){return o?!1:I.wrapS!==1001||I.wrapT!==1001||I.minFilter!==1003&&I.minFilter!==1006}function E(I,M){return I.generateMipmaps&&M&&I.minFilter!==1003&&I.minFilter!==1006}function _(I){s.generateMipmap(I)}function T(I,M,K,ne,re=!1){if(o===!1)return M;if(I!==null){if(s[I]!==void 0)return s[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ae=M;if(M===s.RED&&(K===s.FLOAT&&(ae=s.R32F),K===s.HALF_FLOAT&&(ae=s.R16F),K===s.UNSIGNED_BYTE&&(ae=s.R8)),M===s.RED_INTEGER&&(K===s.UNSIGNED_BYTE&&(ae=s.R8UI),K===s.UNSIGNED_SHORT&&(ae=s.R16UI),K===s.UNSIGNED_INT&&(ae=s.R32UI),K===s.BYTE&&(ae=s.R8I),K===s.SHORT&&(ae=s.R16I),K===s.INT&&(ae=s.R32I)),M===s.RG&&(K===s.FLOAT&&(ae=s.RG32F),K===s.HALF_FLOAT&&(ae=s.RG16F),K===s.UNSIGNED_BYTE&&(ae=s.RG8)),M===s.RGBA){const ye=re?Ms:st.getTransfer(ne);K===s.FLOAT&&(ae=s.RGBA32F),K===s.HALF_FLOAT&&(ae=s.RGBA16F),K===s.UNSIGNED_BYTE&&(ae=ye===dt?s.SRGB8_ALPHA8:s.RGBA8),K===s.UNSIGNED_SHORT_4_4_4_4&&(ae=s.RGBA4),K===s.UNSIGNED_SHORT_5_5_5_1&&(ae=s.RGB5_A1)}return(ae===s.R16F||ae===s.R32F||ae===s.RG16F||ae===s.RG32F||ae===s.RGBA16F||ae===s.RGBA32F)&&e.get("EXT_color_buffer_float"),ae}function b(I,M,K){return E(I,K)===!0||I.isFramebufferTexture&&I.minFilter!==1003&&I.minFilter!==1006?Math.log2(Math.max(M.width,M.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?M.mipmaps.length:1}function R(I){return I===1003||I===1004||I===1005?s.NEAREST:s.LINEAR}function A(I){const M=I.target;M.removeEventListener("dispose",A),S(M),M.isVideoTexture&&h.delete(M)}function C(I){const M=I.target;M.removeEventListener("dispose",C),w(M)}function S(I){const M=i.get(I);if(M.__webglInit===void 0)return;const K=I.source,ne=d.get(K);if(ne){const re=ne[M.__cacheKey];re.usedTimes--,re.usedTimes===0&&y(I),Object.keys(ne).length===0&&d.delete(K)}i.remove(I)}function y(I){const M=i.get(I);s.deleteTexture(M.__webglTexture);const K=I.source,ne=d.get(K);delete ne[M.__cacheKey],a.memory.textures--}function w(I){const M=I.texture,K=i.get(I),ne=i.get(M);if(ne.__webglTexture!==void 0&&(s.deleteTexture(ne.__webglTexture),a.memory.textures--),I.depthTexture&&I.depthTexture.dispose(),I.isWebGLCubeRenderTarget)for(let re=0;re<6;re++){if(Array.isArray(K.__webglFramebuffer[re]))for(let ae=0;ae<K.__webglFramebuffer[re].length;ae++)s.deleteFramebuffer(K.__webglFramebuffer[re][ae]);else s.deleteFramebuffer(K.__webglFramebuffer[re]);K.__webglDepthbuffer&&s.deleteRenderbuffer(K.__webglDepthbuffer[re])}else{if(Array.isArray(K.__webglFramebuffer))for(let re=0;re<K.__webglFramebuffer.length;re++)s.deleteFramebuffer(K.__webglFramebuffer[re]);else s.deleteFramebuffer(K.__webglFramebuffer);if(K.__webglDepthbuffer&&s.deleteRenderbuffer(K.__webglDepthbuffer),K.__webglMultisampledFramebuffer&&s.deleteFramebuffer(K.__webglMultisampledFramebuffer),K.__webglColorRenderbuffer)for(let re=0;re<K.__webglColorRenderbuffer.length;re++)K.__webglColorRenderbuffer[re]&&s.deleteRenderbuffer(K.__webglColorRenderbuffer[re]);K.__webglDepthRenderbuffer&&s.deleteRenderbuffer(K.__webglDepthRenderbuffer)}if(I.isWebGLMultipleRenderTargets)for(let re=0,ae=M.length;re<ae;re++){const ye=i.get(M[re]);ye.__webglTexture&&(s.deleteTexture(ye.__webglTexture),a.memory.textures--),i.remove(M[re])}i.remove(M),i.remove(I)}let U=0;function X(){U=0}function P(){const I=U;return I>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+n.maxTextures),U+=1,I}function F(I){const M=[];return M.push(I.wrapS),M.push(I.wrapT),M.push(I.wrapR||0),M.push(I.magFilter),M.push(I.minFilter),M.push(I.anisotropy),M.push(I.internalFormat),M.push(I.format),M.push(I.type),M.push(I.generateMipmaps),M.push(I.premultiplyAlpha),M.push(I.flipY),M.push(I.unpackAlignment),M.push(I.colorSpace),M.join()}function D(I,M){const K=i.get(I);if(I.isVideoTexture&&$e(I),I.isRenderTargetTexture===!1&&I.version>0&&K.__version!==I.version){const ne=I.image;if(ne===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ne.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{ie(K,I,M);return}}t.bindTexture(s.TEXTURE_2D,K.__webglTexture,s.TEXTURE0+M)}function k(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){ie(K,I,M);return}t.bindTexture(s.TEXTURE_2D_ARRAY,K.__webglTexture,s.TEXTURE0+M)}function N(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){ie(K,I,M);return}t.bindTexture(s.TEXTURE_3D,K.__webglTexture,s.TEXTURE0+M)}function B(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){oe(K,I,M);return}t.bindTexture(s.TEXTURE_CUBE_MAP,K.__webglTexture,s.TEXTURE0+M)}const q={1e3:s.REPEAT,1001:s.CLAMP_TO_EDGE,1002:s.MIRRORED_REPEAT},V={1003:s.NEAREST,1004:s.NEAREST_MIPMAP_NEAREST,1005:s.NEAREST_MIPMAP_LINEAR,1006:s.LINEAR,1007:s.LINEAR_MIPMAP_NEAREST,1008:s.LINEAR_MIPMAP_LINEAR},W={512:s.NEVER,519:s.ALWAYS,513:s.LESS,515:s.LEQUAL,514:s.EQUAL,518:s.GEQUAL,516:s.GREATER,517:s.NOTEQUAL};function $(I,M,K){if(K?(s.texParameteri(I,s.TEXTURE_WRAP_S,q[M.wrapS]),s.texParameteri(I,s.TEXTURE_WRAP_T,q[M.wrapT]),(I===s.TEXTURE_3D||I===s.TEXTURE_2D_ARRAY)&&s.texParameteri(I,s.TEXTURE_WRAP_R,q[M.wrapR]),s.texParameteri(I,s.TEXTURE_MAG_FILTER,V[M.magFilter]),s.texParameteri(I,s.TEXTURE_MIN_FILTER,V[M.minFilter])):(s.texParameteri(I,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(I,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),(I===s.TEXTURE_3D||I===s.TEXTURE_2D_ARRAY)&&s.texParameteri(I,s.TEXTURE_WRAP_R,s.CLAMP_TO_EDGE),(M.wrapS!==1001||M.wrapT!==1001)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),s.texParameteri(I,s.TEXTURE_MAG_FILTER,R(M.magFilter)),s.texParameteri(I,s.TEXTURE_MIN_FILTER,R(M.minFilter)),M.minFilter!==1003&&M.minFilter!==1006&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),M.compareFunction&&(s.texParameteri(I,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(I,s.TEXTURE_COMPARE_FUNC,W[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const ne=e.get("EXT_texture_filter_anisotropic");if(M.magFilter===1003||M.minFilter!==1005&&M.minFilter!==1008||M.type===1015&&e.has("OES_texture_float_linear")===!1||o===!1&&M.type===1016&&e.has("OES_texture_half_float_linear")===!1)return;(M.anisotropy>1||i.get(M).__currentAnisotropy)&&(s.texParameterf(I,ne.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,n.getMaxAnisotropy())),i.get(M).__currentAnisotropy=M.anisotropy)}}function ee(I,M){let K=!1;I.__webglInit===void 0&&(I.__webglInit=!0,M.addEventListener("dispose",A));const ne=M.source;let re=d.get(ne);re===void 0&&(re={},d.set(ne,re));const ae=F(M);if(ae!==I.__cacheKey){re[ae]===void 0&&(re[ae]={texture:s.createTexture(),usedTimes:0},a.memory.textures++,K=!0),re[ae].usedTimes++;const ye=re[I.__cacheKey];ye!==void 0&&(re[I.__cacheKey].usedTimes--,ye.usedTimes===0&&y(M)),I.__cacheKey=ae,I.__webglTexture=re[ae].texture}return K}function ie(I,M,K){let ne=s.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(ne=s.TEXTURE_2D_ARRAY),M.isData3DTexture&&(ne=s.TEXTURE_3D);const re=ee(I,M),ae=M.source;t.bindTexture(ne,I.__webglTexture,s.TEXTURE0+K);const ye=i.get(ae);if(ae.version!==ye.__version||re===!0){t.activeTexture(s.TEXTURE0+K);const ue=st.getPrimaries(st.workingColorSpace),_e=M.colorSpace===ri?null:st.getPrimaries(M.colorSpace),Ie=M.colorSpace===ri||ue===_e?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,M.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,M.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ie);const ke=g(M)&&m(M.image)===!1;let se=v(M.image,ke,!1,n.maxTextureSize);se=Me(M,se);const Ze=m(se)||o,Qe=r.convert(M.format,M.colorSpace);let Ne=r.convert(M.type),Le=T(M.internalFormat,Qe,Ne,M.colorSpace,M.isVideoTexture);$(ne,M,Ze);let xe;const ze=M.mipmaps,it=o&&M.isVideoTexture!==!0&&Le!==36196,vt=ye.__version===void 0||re===!0,qe=b(M,se,Ze);if(M.isDepthTexture)Le=s.DEPTH_COMPONENT,o?M.type===1015?Le=s.DEPTH_COMPONENT32F:M.type===1014?Le=s.DEPTH_COMPONENT24:M.type===1020?Le=s.DEPTH24_STENCIL8:Le=s.DEPTH_COMPONENT16:M.type===1015&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),M.format===1026&&Le===s.DEPTH_COMPONENT&&M.type!==1012&&M.type!==1014&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),M.type=1014,Ne=r.convert(M.type)),M.format===1027&&Le===s.DEPTH_COMPONENT&&(Le=s.DEPTH_STENCIL,M.type!==1020&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),M.type=1020,Ne=r.convert(M.type))),vt&&(it?t.texStorage2D(s.TEXTURE_2D,1,Le,se.width,se.height):t.texImage2D(s.TEXTURE_2D,0,Le,se.width,se.height,0,Qe,Ne,null));else if(M.isDataTexture)if(ze.length>0&&Ze){it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,O=ze.length;he<O;he++)xe=ze[he],it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,Ne,xe.data):t.texImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,Qe,Ne,xe.data);M.generateMipmaps=!1}else it?(vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height),t.texSubImage2D(s.TEXTURE_2D,0,0,0,se.width,se.height,Qe,Ne,se.data)):t.texImage2D(s.TEXTURE_2D,0,Le,se.width,se.height,0,Qe,Ne,se.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){it&&vt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,qe,Le,ze[0].width,ze[0].height,se.depth);for(let he=0,O=ze.length;he<O;he++)xe=ze[he],M.format!==1023?Qe!==null?it?t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,he,0,0,0,xe.width,xe.height,se.depth,Qe,xe.data,0,0):t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,he,Le,xe.width,xe.height,se.depth,0,xe.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):it?t.texSubImage3D(s.TEXTURE_2D_ARRAY,he,0,0,0,xe.width,xe.height,se.depth,Qe,Ne,xe.data):t.texImage3D(s.TEXTURE_2D_ARRAY,he,Le,xe.width,xe.height,se.depth,0,Qe,Ne,xe.data)}else{it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,O=ze.length;he<O;he++)xe=ze[he],M.format!==1023?Qe!==null?it?t.compressedTexSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,xe.data):t.compressedTexImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,xe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,Ne,xe.data):t.texImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,Qe,Ne,xe.data)}else if(M.isDataArrayTexture)it?(vt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,qe,Le,se.width,se.height,se.depth),t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,se.width,se.height,se.depth,Qe,Ne,se.data)):t.texImage3D(s.TEXTURE_2D_ARRAY,0,Le,se.width,se.height,se.depth,0,Qe,Ne,se.data);else if(M.isData3DTexture)it?(vt&&t.texStorage3D(s.TEXTURE_3D,qe,Le,se.width,se.height,se.depth),t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,se.width,se.height,se.depth,Qe,Ne,se.data)):t.texImage3D(s.TEXTURE_3D,0,Le,se.width,se.height,se.depth,0,Qe,Ne,se.data);else if(M.isFramebufferTexture){if(vt)if(it)t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height);else{let he=se.width,O=se.height;for(let fe=0;fe<qe;fe++)t.texImage2D(s.TEXTURE_2D,fe,Le,he,O,0,Qe,Ne,null),he>>=1,O>>=1}}else if(ze.length>0&&Ze){it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,O=ze.length;he<O;he++)xe=ze[he],it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,Qe,Ne,xe):t.texImage2D(s.TEXTURE_2D,he,Le,Qe,Ne,xe);M.generateMipmaps=!1}else it?(vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height),t.texSubImage2D(s.TEXTURE_2D,0,0,0,Qe,Ne,se)):t.texImage2D(s.TEXTURE_2D,0,Le,Qe,Ne,se);E(M,Ze)&&_(ne),ye.__version=ae.version,M.onUpdate&&M.onUpdate(M)}I.__version=M.version}function oe(I,M,K){if(M.image.length!==6)return;const ne=ee(I,M),re=M.source;t.bindTexture(s.TEXTURE_CUBE_MAP,I.__webglTexture,s.TEXTURE0+K);const ae=i.get(re);if(re.version!==ae.__version||ne===!0){t.activeTexture(s.TEXTURE0+K);const ye=st.getPrimaries(st.workingColorSpace),ue=M.colorSpace===ri?null:st.getPrimaries(M.colorSpace),_e=M.colorSpace===ri||ye===ue?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,M.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,M.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,_e);const Ie=M.isCompressedTexture||M.image[0].isCompressedTexture,ke=M.image[0]&&M.image[0].isDataTexture,se=[];for(let he=0;he<6;he++)!Ie&&!ke?se[he]=v(M.image[he],!1,!0,n.maxCubemapSize):se[he]=ke?M.image[he].image:M.image[he],se[he]=Me(M,se[he]);const Ze=se[0],Qe=m(Ze)||o,Ne=r.convert(M.format,M.colorSpace),Le=r.convert(M.type),xe=T(M.internalFormat,Ne,Le,M.colorSpace),ze=o&&M.isVideoTexture!==!0,it=ae.__version===void 0||ne===!0;let vt=b(M,Ze,Qe);$(s.TEXTURE_CUBE_MAP,M,Qe);let qe;if(Ie){ze&&it&&t.texStorage2D(s.TEXTURE_CUBE_MAP,vt,xe,Ze.width,Ze.height);for(let he=0;he<6;he++){qe=se[he].mipmaps;for(let O=0;O<qe.length;O++){const fe=qe[O];M.format!==1023?Ne!==null?ze?t.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O,0,0,fe.width,fe.height,Ne,fe.data):t.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O,xe,fe.width,fe.height,0,fe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O,0,0,fe.width,fe.height,Ne,Le,fe.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O,xe,fe.width,fe.height,0,Ne,Le,fe.data)}}}else{qe=M.mipmaps,ze&&it&&(qe.length>0&&vt++,t.texStorage2D(s.TEXTURE_CUBE_MAP,vt,xe,se[0].width,se[0].height));for(let he=0;he<6;he++)if(ke){ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,0,0,se[he].width,se[he].height,Ne,Le,se[he].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,xe,se[he].width,se[he].height,0,Ne,Le,se[he].data);for(let O=0;O<qe.length;O++){const pe=qe[O].image[he].image;ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O+1,0,0,pe.width,pe.height,Ne,Le,pe.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O+1,xe,pe.width,pe.height,0,Ne,Le,pe.data)}}else{ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,0,0,Ne,Le,se[he]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,xe,Ne,Le,se[he]);for(let O=0;O<qe.length;O++){const fe=qe[O];ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O+1,0,0,Ne,Le,fe.image[he]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,O+1,xe,Ne,Le,fe.image[he])}}}E(M,Qe)&&_(s.TEXTURE_CUBE_MAP),ae.__version=re.version,M.onUpdate&&M.onUpdate(M)}I.__version=M.version}function me(I,M,K,ne,re,ae){const ye=r.convert(K.format,K.colorSpace),ue=r.convert(K.type),_e=T(K.internalFormat,ye,ue,K.colorSpace);if(!i.get(M).__hasExternalTextures){const ke=Math.max(1,M.width>>ae),se=Math.max(1,M.height>>ae);re===s.TEXTURE_3D||re===s.TEXTURE_2D_ARRAY?t.texImage3D(re,ae,_e,ke,se,M.depth,0,ye,ue,null):t.texImage2D(re,ae,_e,ke,se,0,ye,ue,null)}t.bindFramebuffer(s.FRAMEBUFFER,I),le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,ne,re,i.get(K).__webglTexture,0,Ue(M)):(re===s.TEXTURE_2D||re>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&re<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,ne,re,i.get(K).__webglTexture,ae),t.bindFramebuffer(s.FRAMEBUFFER,null)}function Se(I,M,K){if(s.bindRenderbuffer(s.RENDERBUFFER,I),M.depthBuffer&&!M.stencilBuffer){let ne=o===!0?s.DEPTH_COMPONENT24:s.DEPTH_COMPONENT16;if(K||le(M)){const re=M.depthTexture;re&&re.isDepthTexture&&(re.type===1015?ne=s.DEPTH_COMPONENT32F:re.type===1014&&(ne=s.DEPTH_COMPONENT24));const ae=Ue(M);le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ae,ne,M.width,M.height):s.renderbufferStorageMultisample(s.RENDERBUFFER,ae,ne,M.width,M.height)}else s.renderbufferStorage(s.RENDERBUFFER,ne,M.width,M.height);s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,I)}else if(M.depthBuffer&&M.stencilBuffer){const ne=Ue(M);K&&le(M)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,ne,s.DEPTH24_STENCIL8,M.width,M.height):le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ne,s.DEPTH24_STENCIL8,M.width,M.height):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,M.width,M.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,I)}else{const ne=M.isWebGLMultipleRenderTargets===!0?M.texture:[M.texture];for(let re=0;re<ne.length;re++){const ae=ne[re],ye=r.convert(ae.format,ae.colorSpace),ue=r.convert(ae.type),_e=T(ae.internalFormat,ye,ue,ae.colorSpace),Ie=Ue(M);K&&le(M)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,Ie,_e,M.width,M.height):le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,Ie,_e,M.width,M.height):s.renderbufferStorage(s.RENDERBUFFER,_e,M.width,M.height)}}s.bindRenderbuffer(s.RENDERBUFFER,null)}function be(I,M){if(M&&M.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(s.FRAMEBUFFER,I),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!i.get(M.depthTexture).__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),D(M.depthTexture,0);const ne=i.get(M.depthTexture).__webglTexture,re=Ue(M);if(M.depthTexture.format===1026)le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,ne,0,re):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,ne,0);else if(M.depthTexture.format===1027)le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,ne,0,re):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,ne,0);else throw new Error("Unknown depthTexture format")}function Te(I){const M=i.get(I),K=I.isWebGLCubeRenderTarget===!0;if(I.depthTexture&&!M.__autoAllocateDepthBuffer){if(K)throw new Error("target.depthTexture not supported in Cube render targets");be(M.__webglFramebuffer,I)}else if(K){M.__webglDepthbuffer=[];for(let ne=0;ne<6;ne++)t.bindFramebuffer(s.FRAMEBUFFER,M.__webglFramebuffer[ne]),M.__webglDepthbuffer[ne]=s.createRenderbuffer(),Se(M.__webglDepthbuffer[ne],I,!1)}else t.bindFramebuffer(s.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer=s.createRenderbuffer(),Se(M.__webglDepthbuffer,I,!1);t.bindFramebuffer(s.FRAMEBUFFER,null)}function Ge(I,M,K){const ne=i.get(I);M!==void 0&&me(ne.__webglFramebuffer,I,I.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),K!==void 0&&Te(I)}function Y(I){const M=I.texture,K=i.get(I),ne=i.get(M);I.addEventListener("dispose",C),I.isWebGLMultipleRenderTargets!==!0&&(ne.__webglTexture===void 0&&(ne.__webglTexture=s.createTexture()),ne.__version=M.version,a.memory.textures++);const re=I.isWebGLCubeRenderTarget===!0,ae=I.isWebGLMultipleRenderTargets===!0,ye=m(I)||o;if(re){K.__webglFramebuffer=[];for(let ue=0;ue<6;ue++)if(o&&M.mipmaps&&M.mipmaps.length>0){K.__webglFramebuffer[ue]=[];for(let _e=0;_e<M.mipmaps.length;_e++)K.__webglFramebuffer[ue][_e]=s.createFramebuffer()}else K.__webglFramebuffer[ue]=s.createFramebuffer()}else{if(o&&M.mipmaps&&M.mipmaps.length>0){K.__webglFramebuffer=[];for(let ue=0;ue<M.mipmaps.length;ue++)K.__webglFramebuffer[ue]=s.createFramebuffer()}else K.__webglFramebuffer=s.createFramebuffer();if(ae)if(n.drawBuffers){const ue=I.texture;for(let _e=0,Ie=ue.length;_e<Ie;_e++){const ke=i.get(ue[_e]);ke.__webglTexture===void 0&&(ke.__webglTexture=s.createTexture(),a.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");if(o&&I.samples>0&&le(I)===!1){const ue=ae?M:[M];K.__webglMultisampledFramebuffer=s.createFramebuffer(),K.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,K.__webglMultisampledFramebuffer);for(let _e=0;_e<ue.length;_e++){const Ie=ue[_e];K.__webglColorRenderbuffer[_e]=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,K.__webglColorRenderbuffer[_e]);const ke=r.convert(Ie.format,Ie.colorSpace),se=r.convert(Ie.type),Ze=T(Ie.internalFormat,ke,se,Ie.colorSpace,I.isXRRenderTarget===!0),Qe=Ue(I);s.renderbufferStorageMultisample(s.RENDERBUFFER,Qe,Ze,I.width,I.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+_e,s.RENDERBUFFER,K.__webglColorRenderbuffer[_e])}s.bindRenderbuffer(s.RENDERBUFFER,null),I.depthBuffer&&(K.__webglDepthRenderbuffer=s.createRenderbuffer(),Se(K.__webglDepthRenderbuffer,I,!0)),t.bindFramebuffer(s.FRAMEBUFFER,null)}}if(re){t.bindTexture(s.TEXTURE_CUBE_MAP,ne.__webglTexture),$(s.TEXTURE_CUBE_MAP,M,ye);for(let ue=0;ue<6;ue++)if(o&&M.mipmaps&&M.mipmaps.length>0)for(let _e=0;_e<M.mipmaps.length;_e++)me(K.__webglFramebuffer[ue][_e],I,M,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+ue,_e);else me(K.__webglFramebuffer[ue],I,M,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0);E(M,ye)&&_(s.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ae){const ue=I.texture;for(let _e=0,Ie=ue.length;_e<Ie;_e++){const ke=ue[_e],se=i.get(ke);t.bindTexture(s.TEXTURE_2D,se.__webglTexture),$(s.TEXTURE_2D,ke,ye),me(K.__webglFramebuffer,I,ke,s.COLOR_ATTACHMENT0+_e,s.TEXTURE_2D,0),E(ke,ye)&&_(s.TEXTURE_2D)}t.unbindTexture()}else{let ue=s.TEXTURE_2D;if((I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(o?ue=I.isWebGL3DRenderTarget?s.TEXTURE_3D:s.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),t.bindTexture(ue,ne.__webglTexture),$(ue,M,ye),o&&M.mipmaps&&M.mipmaps.length>0)for(let _e=0;_e<M.mipmaps.length;_e++)me(K.__webglFramebuffer[_e],I,M,s.COLOR_ATTACHMENT0,ue,_e);else me(K.__webglFramebuffer,I,M,s.COLOR_ATTACHMENT0,ue,0);E(M,ye)&&_(ue),t.unbindTexture()}I.depthBuffer&&Te(I)}function Rt(I){const M=m(I)||o,K=I.isWebGLMultipleRenderTargets===!0?I.texture:[I.texture];for(let ne=0,re=K.length;ne<re;ne++){const ae=K[ne];if(E(ae,M)){const ye=I.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D,ue=i.get(ae).__webglTexture;t.bindTexture(ye,ue),_(ye),t.unbindTexture()}}}function Re(I){if(o&&I.samples>0&&le(I)===!1){const M=I.isWebGLMultipleRenderTargets?I.texture:[I.texture],K=I.width,ne=I.height;let re=s.COLOR_BUFFER_BIT;const ae=[],ye=I.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,ue=i.get(I),_e=I.isWebGLMultipleRenderTargets===!0;if(_e)for(let Ie=0;Ie<M.length;Ie++)t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.RENDERBUFFER,null),t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.TEXTURE_2D,null,0);t.bindFramebuffer(s.READ_FRAMEBUFFER,ue.__webglMultisampledFramebuffer),t.bindFramebuffer(s.DRAW_FRAMEBUFFER,ue.__webglFramebuffer);for(let Ie=0;Ie<M.length;Ie++){ae.push(s.COLOR_ATTACHMENT0+Ie),I.depthBuffer&&ae.push(ye);const ke=ue.__ignoreDepthValues!==void 0?ue.__ignoreDepthValues:!1;if(ke===!1&&(I.depthBuffer&&(re|=s.DEPTH_BUFFER_BIT),I.stencilBuffer&&(re|=s.STENCIL_BUFFER_BIT)),_e&&s.framebufferRenderbuffer(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,ue.__webglColorRenderbuffer[Ie]),ke===!0&&(s.invalidateFramebuffer(s.READ_FRAMEBUFFER,[ye]),s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,[ye])),_e){const se=i.get(M[Ie]).__webglTexture;s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,se,0)}s.blitFramebuffer(0,0,K,ne,0,0,K,ne,re,s.NEAREST),c&&s.invalidateFramebuffer(s.READ_FRAMEBUFFER,ae)}if(t.bindFramebuffer(s.READ_FRAMEBUFFER,null),t.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),_e)for(let Ie=0;Ie<M.length;Ie++){t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.RENDERBUFFER,ue.__webglColorRenderbuffer[Ie]);const ke=i.get(M[Ie]).__webglTexture;t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.TEXTURE_2D,ke,0)}t.bindFramebuffer(s.DRAW_FRAMEBUFFER,ue.__webglMultisampledFramebuffer)}}function Ue(I){return Math.min(n.maxSamples,I.samples)}function le(I){const M=i.get(I);return o&&I.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function $e(I){const M=a.render.frame;h.get(I)!==M&&(h.set(I,M),I.update())}function Me(I,M){const K=I.colorSpace,ne=I.format,re=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||I.format===1035||K!==Ci&&K!==ri&&(st.getTransfer(K)===dt?o===!1?e.has("EXT_sRGB")===!0&&ne===1023?(I.format=1035,I.minFilter=1006,I.generateMipmaps=!1):M=Zo.sRGBToLinear(M):(ne!==1023||re!==1009)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",K)),M}this.allocateTextureUnit=P,this.resetTextureUnits=X,this.setTexture2D=D,this.setTexture2DArray=k,this.setTexture3D=N,this.setTextureCube=B,this.rebindTextures=Ge,this.setupRenderTarget=Y,this.updateRenderTargetMipmap=Rt,this.updateMultisampleRenderTarget=Re,this.setupDepthRenderbuffer=Te,this.setupFrameBufferTexture=me,this.useMultisampledRTT=le}function Kg(s,e,t){const i=t.isWebGL2;function n(r,a=ri){let o;const l=st.getTransfer(a);if(r===1009)return s.UNSIGNED_BYTE;if(r===1017)return s.UNSIGNED_SHORT_4_4_4_4;if(r===1018)return s.UNSIGNED_SHORT_5_5_5_1;if(r===1010)return s.BYTE;if(r===1011)return s.SHORT;if(r===1012)return s.UNSIGNED_SHORT;if(r===1013)return s.INT;if(r===1014)return s.UNSIGNED_INT;if(r===1015)return s.FLOAT;if(r===1016)return i?s.HALF_FLOAT:(o=e.get("OES_texture_half_float"),o!==null?o.HALF_FLOAT_OES:null);if(r===1021)return s.ALPHA;if(r===1023)return s.RGBA;if(r===1024)return s.LUMINANCE;if(r===1025)return s.LUMINANCE_ALPHA;if(r===1026)return s.DEPTH_COMPONENT;if(r===1027)return s.DEPTH_STENCIL;if(r===1035)return o=e.get("EXT_sRGB"),o!==null?o.SRGB_ALPHA_EXT:null;if(r===1028)return s.RED;if(r===1029)return s.RED_INTEGER;if(r===1030)return s.RG;if(r===1031)return s.RG_INTEGER;if(r===1033)return s.RGBA_INTEGER;if(r===33776||r===33777||r===33778||r===33779)if(l===dt)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(r===33776)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===33777)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===33778)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===33779)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(r===33776)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===33777)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===33778)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===33779)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===35840||r===35841||r===35842||r===35843)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(r===35840)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===35841)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===35842)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===35843)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===36196)return o=e.get("WEBGL_compressed_texture_etc1"),o!==null?o.COMPRESSED_RGB_ETC1_WEBGL:null;if(r===37492||r===37496)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(r===37492)return l===dt?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(r===37496)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===37808||r===37809||r===37810||r===37811||r===37812||r===37813||r===37814||r===37815||r===37816||r===37817||r===37818||r===37819||r===37820||r===37821)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(r===37808)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===37809)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===37810)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===37811)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===37812)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===37813)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===37814)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===37815)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===37816)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===37817)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===37818)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===37819)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===37820)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===37821)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===36492||r===36494||r===36495)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(r===36492)return l===dt?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===36494)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===36495)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===36283||r===36284||r===36285||r===36286)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(r===36492)return o.COMPRESSED_RED_RGTC1_EXT;if(r===36284)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===36285)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===36286)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===1020?i?s.UNSIGNED_INT_24_8:(o=e.get("WEBGL_depth_texture"),o!==null?o.UNSIGNED_INT_24_8_WEBGL:null):s[r]!==void 0?s[r]:null}return{convert:n}}class Xg extends oi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class sr extends Jt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Yg={type:"move"};class Ra{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new sr,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new sr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Q,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Q),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new sr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Q,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Q),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let n=null,r=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,i),g=this._getHandJoint(c,v);m!==null&&(g.matrix.fromArray(m.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=m.radius),g.visible=m!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;c.inputState.pinching&&d>f+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&r!==null&&(n=r),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Yg)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new sr;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class qg extends xn{constructor(e,t){super();const i=this;let n=null,r=1,a=null,o="local-floor",l=1,c=null,h=null,u=null,d=null,f=null,p=null;const v=t.getContextAttributes();let m=null,g=null;const E=[],_=[],T=new nt;let b=null;const R=new oi;R.layers.enable(1),R.viewport=new Ft;const A=new oi;A.layers.enable(2),A.viewport=new Ft;const C=[R,A],S=new Xg;S.layers.enable(1),S.layers.enable(2);let y=null,w=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function($){let ee=E[$];return ee===void 0&&(ee=new Ra,E[$]=ee),ee.getTargetRaySpace()},this.getControllerGrip=function($){let ee=E[$];return ee===void 0&&(ee=new Ra,E[$]=ee),ee.getGripSpace()},this.getHand=function($){let ee=E[$];return ee===void 0&&(ee=new Ra,E[$]=ee),ee.getHandSpace()};function U($){const ee=_.indexOf($.inputSource);if(ee===-1)return;const ie=E[ee];ie!==void 0&&(ie.update($.inputSource,$.frame,c||a),ie.dispatchEvent({type:$.type,data:$.inputSource}))}function X(){n.removeEventListener("select",U),n.removeEventListener("selectstart",U),n.removeEventListener("selectend",U),n.removeEventListener("squeeze",U),n.removeEventListener("squeezestart",U),n.removeEventListener("squeezeend",U),n.removeEventListener("end",X),n.removeEventListener("inputsourceschange",P);for(let $=0;$<E.length;$++){const ee=_[$];ee!==null&&(_[$]=null,E[$].disconnect(ee))}y=null,w=null,e.setRenderTarget(m),f=null,d=null,u=null,n=null,g=null,W.stop(),i.isPresenting=!1,e.setPixelRatio(b),e.setSize(T.width,T.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function($){r=$,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function($){o=$,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function($){c=$},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function($){if(n=$,n!==null){if(m=e.getRenderTarget(),n.addEventListener("select",U),n.addEventListener("selectstart",U),n.addEventListener("selectend",U),n.addEventListener("squeeze",U),n.addEventListener("squeezestart",U),n.addEventListener("squeezeend",U),n.addEventListener("end",X),n.addEventListener("inputsourceschange",P),v.xrCompatible!==!0&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(T),n.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const ee={antialias:n.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(n,t,ee),n.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),g=new nn(f.framebufferWidth,f.framebufferHeight,{format:1023,type:1009,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let ee=null,ie=null,oe=null;v.depth&&(oe=v.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ee=v.stencil?1027:1026,ie=v.stencil?1020:1014);const me={colorFormat:t.RGBA8,depthFormat:oe,scaleFactor:r};u=new XRWebGLBinding(n,t),d=u.createProjectionLayer(me),n.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),g=new nn(d.textureWidth,d.textureHeight,{format:1023,type:1009,depthTexture:new Cl(d.textureWidth,d.textureHeight,ie,void 0,void 0,void 0,void 0,void 0,void 0,ee),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const Se=e.properties.get(g);Se.__ignoreDepthValues=d.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await n.requestReferenceSpace(o),W.setContext(n),W.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode};function P($){for(let ee=0;ee<$.removed.length;ee++){const ie=$.removed[ee],oe=_.indexOf(ie);oe>=0&&(_[oe]=null,E[oe].disconnect(ie))}for(let ee=0;ee<$.added.length;ee++){const ie=$.added[ee];let oe=_.indexOf(ie);if(oe===-1){for(let Se=0;Se<E.length;Se++)if(Se>=_.length){_.push(ie),oe=Se;break}else if(_[Se]===null){_[Se]=ie,oe=Se;break}if(oe===-1)break}const me=E[oe];me&&me.connect(ie)}}const F=new Q,D=new Q;function k($,ee,ie){F.setFromMatrixPosition(ee.matrixWorld),D.setFromMatrixPosition(ie.matrixWorld);const oe=F.distanceTo(D),me=ee.projectionMatrix.elements,Se=ie.projectionMatrix.elements,be=me[14]/(me[10]-1),Te=me[14]/(me[10]+1),Ge=(me[9]+1)/me[5],Y=(me[9]-1)/me[5],Rt=(me[8]-1)/me[0],Re=(Se[8]+1)/Se[0],Ue=be*Rt,le=be*Re,$e=oe/(-Rt+Re),Me=$e*-Rt;ee.matrixWorld.decompose($.position,$.quaternion,$.scale),$.translateX(Me),$.translateZ($e),$.matrixWorld.compose($.position,$.quaternion,$.scale),$.matrixWorldInverse.copy($.matrixWorld).invert();const I=be+$e,M=Te+$e,K=Ue-Me,ne=le+(oe-Me),re=Ge*Te/M*I,ae=Y*Te/M*I;$.projectionMatrix.makePerspective(K,ne,re,ae,I,M),$.projectionMatrixInverse.copy($.projectionMatrix).invert()}function N($,ee){ee===null?$.matrixWorld.copy($.matrix):$.matrixWorld.multiplyMatrices(ee.matrixWorld,$.matrix),$.matrixWorldInverse.copy($.matrixWorld).invert()}this.updateCamera=function($){if(n===null)return;S.near=A.near=R.near=$.near,S.far=A.far=R.far=$.far,(y!==S.near||w!==S.far)&&(n.updateRenderState({depthNear:S.near,depthFar:S.far}),y=S.near,w=S.far);const ee=$.parent,ie=S.cameras;N(S,ee);for(let oe=0;oe<ie.length;oe++)N(ie[oe],ee);ie.length===2?k(S,R,A):S.projectionMatrix.copy(R.projectionMatrix),B($,S,ee)};function B($,ee,ie){ie===null?$.matrix.copy(ee.matrixWorld):($.matrix.copy(ie.matrixWorld),$.matrix.invert(),$.matrix.multiply(ee.matrixWorld)),$.matrix.decompose($.position,$.quaternion,$.scale),$.updateMatrixWorld(!0),$.projectionMatrix.copy(ee.projectionMatrix),$.projectionMatrixInverse.copy(ee.projectionMatrixInverse),$.isPerspectiveCamera&&($.fov=Zr*2*Math.atan(1/$.projectionMatrix.elements[5]),$.zoom=1)}this.getCamera=function(){return S},this.getFoveation=function(){if(!(d===null&&f===null))return l},this.setFoveation=function($){l=$,d!==null&&(d.fixedFoveation=$),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=$)};let q=null;function V($,ee){if(h=ee.getViewerPose(c||a),p=ee,h!==null){const ie=h.views;f!==null&&(e.setRenderTargetFramebuffer(g,f.framebuffer),e.setRenderTarget(g));let oe=!1;ie.length!==S.cameras.length&&(S.cameras.length=0,oe=!0);for(let me=0;me<ie.length;me++){const Se=ie[me];let be=null;if(f!==null)be=f.getViewport(Se);else{const Ge=u.getViewSubImage(d,Se);be=Ge.viewport,me===0&&(e.setRenderTargetTextures(g,Ge.colorTexture,d.ignoreDepthValues?void 0:Ge.depthStencilTexture),e.setRenderTarget(g))}let Te=C[me];Te===void 0&&(Te=new oi,Te.layers.enable(me),Te.viewport=new Ft,C[me]=Te),Te.matrix.fromArray(Se.transform.matrix),Te.matrix.decompose(Te.position,Te.quaternion,Te.scale),Te.projectionMatrix.fromArray(Se.projectionMatrix),Te.projectionMatrixInverse.copy(Te.projectionMatrix).invert(),Te.viewport.set(be.x,be.y,be.width,be.height),me===0&&(S.matrix.copy(Te.matrix),S.matrix.decompose(S.position,S.quaternion,S.scale)),oe===!0&&S.cameras.push(Te)}}for(let ie=0;ie<E.length;ie++){const oe=_[ie],me=E[ie];oe!==null&&me!==void 0&&me.update(oe,ee,c||a)}q&&q($,ee),ee.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ee}),p=null}const W=new yl;W.setAnimationLoop(V),this.setAnimationLoop=function($){q=$},this.dispose=function(){}}}function jg(s,e){function t(m,g){m.matrixAutoUpdate===!0&&m.updateMatrix(),g.value.copy(m.matrix)}function i(m,g){g.color.getRGB(m.fogColor.value,_l(s)),g.isFog?(m.fogNear.value=g.near,m.fogFar.value=g.far):g.isFogExp2&&(m.fogDensity.value=g.density)}function n(m,g,E,_,T){g.isMeshBasicMaterial||g.isMeshLambertMaterial?r(m,g):g.isMeshToonMaterial?(r(m,g),u(m,g)):g.isMeshPhongMaterial?(r(m,g),h(m,g)):g.isMeshStandardMaterial?(r(m,g),d(m,g),g.isMeshPhysicalMaterial&&f(m,g,T)):g.isMeshMatcapMaterial?(r(m,g),p(m,g)):g.isMeshDepthMaterial?r(m,g):g.isMeshDistanceMaterial?(r(m,g),v(m,g)):g.isMeshNormalMaterial?r(m,g):g.isLineBasicMaterial?(a(m,g),g.isLineDashedMaterial&&o(m,g)):g.isPointsMaterial?l(m,g,E,_):g.isSpriteMaterial?c(m,g):g.isShadowMaterial?(m.color.value.copy(g.color),m.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function r(m,g){m.opacity.value=g.opacity,g.color&&m.diffuse.value.copy(g.color),g.emissive&&m.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(m.map.value=g.map,t(g.map,m.mapTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.bumpMap&&(m.bumpMap.value=g.bumpMap,t(g.bumpMap,m.bumpMapTransform),m.bumpScale.value=g.bumpScale,g.side===1&&(m.bumpScale.value*=-1)),g.normalMap&&(m.normalMap.value=g.normalMap,t(g.normalMap,m.normalMapTransform),m.normalScale.value.copy(g.normalScale),g.side===1&&m.normalScale.value.negate()),g.displacementMap&&(m.displacementMap.value=g.displacementMap,t(g.displacementMap,m.displacementMapTransform),m.displacementScale.value=g.displacementScale,m.displacementBias.value=g.displacementBias),g.emissiveMap&&(m.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,m.emissiveMapTransform)),g.specularMap&&(m.specularMap.value=g.specularMap,t(g.specularMap,m.specularMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest);const E=e.get(g).envMap;if(E&&(m.envMap.value=E,m.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=g.reflectivity,m.ior.value=g.ior,m.refractionRatio.value=g.refractionRatio),g.lightMap){m.lightMap.value=g.lightMap;const _=s._useLegacyLights===!0?Math.PI:1;m.lightMapIntensity.value=g.lightMapIntensity*_,t(g.lightMap,m.lightMapTransform)}g.aoMap&&(m.aoMap.value=g.aoMap,m.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,m.aoMapTransform))}function a(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform))}function o(m,g){m.dashSize.value=g.dashSize,m.totalSize.value=g.dashSize+g.gapSize,m.scale.value=g.scale}function l(m,g,E,_){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.size.value=g.size*E,m.scale.value=_*.5,g.map&&(m.map.value=g.map,t(g.map,m.uvTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function c(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.rotation.value=g.rotation,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function h(m,g){m.specular.value.copy(g.specular),m.shininess.value=Math.max(g.shininess,1e-4)}function u(m,g){g.gradientMap&&(m.gradientMap.value=g.gradientMap)}function d(m,g){m.metalness.value=g.metalness,g.metalnessMap&&(m.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,m.metalnessMapTransform)),m.roughness.value=g.roughness,g.roughnessMap&&(m.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,m.roughnessMapTransform)),e.get(g).envMap&&(m.envMapIntensity.value=g.envMapIntensity)}function f(m,g,E){m.ior.value=g.ior,g.sheen>0&&(m.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),m.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(m.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,m.sheenColorMapTransform)),g.sheenRoughnessMap&&(m.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,m.sheenRoughnessMapTransform))),g.clearcoat>0&&(m.clearcoat.value=g.clearcoat,m.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(m.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,m.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(m.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===1&&m.clearcoatNormalScale.value.negate())),g.iridescence>0&&(m.iridescence.value=g.iridescence,m.iridescenceIOR.value=g.iridescenceIOR,m.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(m.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,m.iridescenceMapTransform)),g.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),g.transmission>0&&(m.transmission.value=g.transmission,m.transmissionSamplerMap.value=E.texture,m.transmissionSamplerSize.value.set(E.width,E.height),g.transmissionMap&&(m.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,m.transmissionMapTransform)),m.thickness.value=g.thickness,g.thicknessMap&&(m.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=g.attenuationDistance,m.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(m.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(m.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=g.specularIntensity,m.specularColor.value.copy(g.specularColor),g.specularColorMap&&(m.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,m.specularColorMapTransform)),g.specularIntensityMap&&(m.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,m.specularIntensityMapTransform))}function p(m,g){g.matcap&&(m.matcap.value=g.matcap)}function v(m,g){const E=e.get(g).light;m.referencePosition.value.setFromMatrixPosition(E.matrixWorld),m.nearDistance.value=E.shadow.camera.near,m.farDistance.value=E.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function Qg(s,e,t,i){let n={},r={},a=[];const o=t.isWebGL2?s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(E,_){const T=_.program;i.uniformBlockBinding(E,T)}function c(E,_){let T=n[E.id];T===void 0&&(p(E),T=h(E),n[E.id]=T,E.addEventListener("dispose",m));const b=_.program;i.updateUBOMapping(E,b);const R=e.render.frame;r[E.id]!==R&&(d(E),r[E.id]=R)}function h(E){const _=u();E.__bindingPointIndex=_;const T=s.createBuffer(),b=E.__size,R=E.usage;return s.bindBuffer(s.UNIFORM_BUFFER,T),s.bufferData(s.UNIFORM_BUFFER,b,R),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,_,T),T}function u(){for(let E=0;E<o;E++)if(a.indexOf(E)===-1)return a.push(E),E;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(E){const _=n[E.id],T=E.uniforms,b=E.__cache;s.bindBuffer(s.UNIFORM_BUFFER,_);for(let R=0,A=T.length;R<A;R++){const C=Array.isArray(T[R])?T[R]:[T[R]];for(let S=0,y=C.length;S<y;S++){const w=C[S];if(f(w,R,S,b)===!0){const U=w.__offset,X=Array.isArray(w.value)?w.value:[w.value];let P=0;for(let F=0;F<X.length;F++){const D=X[F],k=v(D);typeof D=="number"||typeof D=="boolean"?(w.__data[0]=D,s.bufferSubData(s.UNIFORM_BUFFER,U+P,w.__data)):D.isMatrix3?(w.__data[0]=D.elements[0],w.__data[1]=D.elements[1],w.__data[2]=D.elements[2],w.__data[3]=0,w.__data[4]=D.elements[3],w.__data[5]=D.elements[4],w.__data[6]=D.elements[5],w.__data[7]=0,w.__data[8]=D.elements[6],w.__data[9]=D.elements[7],w.__data[10]=D.elements[8],w.__data[11]=0):(D.toArray(w.__data,P),P+=k.storage/Float32Array.BYTES_PER_ELEMENT)}s.bufferSubData(s.UNIFORM_BUFFER,U,w.__data)}}}s.bindBuffer(s.UNIFORM_BUFFER,null)}function f(E,_,T,b){const R=E.value,A=_+"_"+T;if(b[A]===void 0)return typeof R=="number"||typeof R=="boolean"?b[A]=R:b[A]=R.clone(),!0;{const C=b[A];if(typeof R=="number"||typeof R=="boolean"){if(C!==R)return b[A]=R,!0}else if(C.equals(R)===!1)return C.copy(R),!0}return!1}function p(E){const _=E.uniforms;let T=0;const b=16;for(let A=0,C=_.length;A<C;A++){const S=Array.isArray(_[A])?_[A]:[_[A]];for(let y=0,w=S.length;y<w;y++){const U=S[y],X=Array.isArray(U.value)?U.value:[U.value];for(let P=0,F=X.length;P<F;P++){const D=X[P],k=v(D),N=T%b;N!==0&&b-N<k.boundary&&(T+=b-N),U.__data=new Float32Array(k.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=T,T+=k.storage}}}const R=T%b;return R>0&&(T+=b-R),E.__size=T,E.__cache={},this}function v(E){const _={boundary:0,storage:0};return typeof E=="number"||typeof E=="boolean"?(_.boundary=4,_.storage=4):E.isVector2?(_.boundary=8,_.storage=8):E.isVector3||E.isColor?(_.boundary=16,_.storage=12):E.isVector4?(_.boundary=16,_.storage=16):E.isMatrix3?(_.boundary=48,_.storage=48):E.isMatrix4?(_.boundary=64,_.storage=64):E.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",E),_}function m(E){const _=E.target;_.removeEventListener("dispose",m);const T=a.indexOf(_.__bindingPointIndex);a.splice(T,1),s.deleteBuffer(n[_.id]),delete n[_.id],delete r[_.id]}function g(){for(const E in n)s.deleteBuffer(n[E]);a=[],n={},r={}}return{bind:l,update:c,dispose:g}}class Ql{constructor(e={}){const{canvas:t=Ad(),context:i=null,depth:n=!0,stencil:r=!0,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=e;this.isWebGLRenderer=!0;let d;i!==null?d=i.getContextAttributes().alpha:d=a;const f=new Uint32Array(4),p=new Int32Array(4);let v=null,m=null;const g=[],E=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Mt,this._useLegacyLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const _=this;let T=!1,b=0,R=0,A=null,C=-1,S=null;const y=new Ft,w=new Ft;let U=null;const X=new rt(0);let P=0,F=t.width,D=t.height,k=1,N=null,B=null;const q=new Ft(0,0,F,D),V=new Ft(0,0,F,D);let W=!1;const $=new Sl;let ee=!1,ie=!1,oe=null;const me=new Ot,Se=new nt,be=new Q,Te={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Ge(){return A===null?k:1}let Y=i;function Rt(L,z){for(let Z=0;Z<L.length;Z++){const J=L[Z],j=t.getContext(J,z);if(j!==null)return j}return null}try{const L={alpha:!0,depth:n,stencil:r,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${qr}`),t.addEventListener("webglcontextlost",he,!1),t.addEventListener("webglcontextrestored",O,!1),t.addEventListener("webglcontextcreationerror",fe,!1),Y===null){const z=["webgl2","webgl","experimental-webgl"];if(_.isWebGL1Renderer===!0&&z.shift(),Y=Rt(z,L),Y===null)throw Rt(z)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&Y instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),Y.getShaderPrecisionFormat===void 0&&(Y.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(L){throw console.error("THREE.WebGLRenderer: "+L.message),L}let Re,Ue,le,$e,Me,I,M,K,ne,re,ae,ye,ue,_e,Ie,ke,se,Ze,Qe,Ne,Le,xe,ze,it;function vt(){Re=new om(Y),Ue=new em(Y,Re,e),Re.init(Ue),xe=new Kg(Y,Re,Ue),le=new zg(Y,Re,Ue),$e=new hm(Y),Me=new Cg,I=new Wg(Y,Re,le,Me,Ue,xe,$e),M=new im(_),K=new am(_),ne=new jd(Y,Ue),ze=new Zp(Y,Re,ne,Ue),re=new lm(Y,ne,$e,ze),ae=new pm(Y,re,ne,$e),Qe=new fm(Y,Ue,I),ke=new tm(Me),ye=new Ig(_,M,K,Re,Ue,ze,ke),ue=new jg(_,Me),_e=new Dg,Ie=new kg(Re,Ue),Ze=new Qp(_,M,K,le,ae,d,l),se=new $g(_,ae,Ue),it=new Qg(Y,$e,Ue,le),Ne=new Jp(Y,Re,$e,Ue),Le=new cm(Y,Re,$e,Ue),$e.programs=ye.programs,_.capabilities=Ue,_.extensions=Re,_.properties=Me,_.renderLists=_e,_.shadowMap=se,_.state=le,_.info=$e}vt();const qe=new qg(_,Y);this.xr=qe,this.getContext=function(){return Y},this.getContextAttributes=function(){return Y.getContextAttributes()},this.forceContextLoss=function(){const L=Re.get("WEBGL_lose_context");L&&L.loseContext()},this.forceContextRestore=function(){const L=Re.get("WEBGL_lose_context");L&&L.restoreContext()},this.getPixelRatio=function(){return k},this.setPixelRatio=function(L){L!==void 0&&(k=L,this.setSize(F,D,!1))},this.getSize=function(L){return L.set(F,D)},this.setSize=function(L,z,Z=!0){if(qe.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=L,D=z,t.width=Math.floor(L*k),t.height=Math.floor(z*k),Z===!0&&(t.style.width=L+"px",t.style.height=z+"px"),this.setViewport(0,0,L,z)},this.getDrawingBufferSize=function(L){return L.set(F*k,D*k).floor()},this.setDrawingBufferSize=function(L,z,Z){F=L,D=z,k=Z,t.width=Math.floor(L*Z),t.height=Math.floor(z*Z),this.setViewport(0,0,L,z)},this.getCurrentViewport=function(L){return L.copy(y)},this.getViewport=function(L){return L.copy(q)},this.setViewport=function(L,z,Z,J){L.isVector4?q.set(L.x,L.y,L.z,L.w):q.set(L,z,Z,J),le.viewport(y.copy(q).multiplyScalar(k).floor())},this.getScissor=function(L){return L.copy(V)},this.setScissor=function(L,z,Z,J){L.isVector4?V.set(L.x,L.y,L.z,L.w):V.set(L,z,Z,J),le.scissor(w.copy(V).multiplyScalar(k).floor())},this.getScissorTest=function(){return W},this.setScissorTest=function(L){le.setScissorTest(W=L)},this.setOpaqueSort=function(L){N=L},this.setTransparentSort=function(L){B=L},this.getClearColor=function(L){return L.copy(Ze.getClearColor())},this.setClearColor=function(){Ze.setClearColor.apply(Ze,arguments)},this.getClearAlpha=function(){return Ze.getClearAlpha()},this.setClearAlpha=function(){Ze.setClearAlpha.apply(Ze,arguments)},this.clear=function(L=!0,z=!0,Z=!0){let J=0;if(L){let j=!1;if(A!==null){const ve=A.texture.format;j=ve===1033||ve===1031||ve===1029}if(j){const ve=A.texture.type,Ae=ve===1009||ve===1014||ve===1012||ve===1020||ve===1017||ve===1018,we=Ze.getClearColor(),Oe=Ze.getClearAlpha(),Ke=we.r,Be=we.g,Ve=we.b;Ae?(f[0]=Ke,f[1]=Be,f[2]=Ve,f[3]=Oe,Y.clearBufferuiv(Y.COLOR,0,f)):(p[0]=Ke,p[1]=Be,p[2]=Ve,p[3]=Oe,Y.clearBufferiv(Y.COLOR,0,p))}else J|=Y.COLOR_BUFFER_BIT}z&&(J|=Y.DEPTH_BUFFER_BIT),Z&&(J|=Y.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Y.clear(J)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",he,!1),t.removeEventListener("webglcontextrestored",O,!1),t.removeEventListener("webglcontextcreationerror",fe,!1),_e.dispose(),Ie.dispose(),Me.dispose(),M.dispose(),K.dispose(),ae.dispose(),ze.dispose(),it.dispose(),ye.dispose(),qe.dispose(),qe.removeEventListener("sessionstart",$t),qe.removeEventListener("sessionend",ut),oe&&(oe.dispose(),oe=null),zt.stop()};function he(L){L.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function O(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const L=$e.autoReset,z=se.enabled,Z=se.autoUpdate,J=se.needsUpdate,j=se.type;vt(),$e.autoReset=L,se.enabled=z,se.autoUpdate=Z,se.needsUpdate=J,se.type=j}function fe(L){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",L.statusMessage)}function pe(L){const z=L.target;z.removeEventListener("dispose",pe),Pe(z)}function Pe(L){Ce(L),Me.remove(L)}function Ce(L){const z=Me.get(L).programs;z!==void 0&&(z.forEach(function(Z){ye.releaseProgram(Z)}),L.isShaderMaterial&&ye.releaseShaderCache(L))}this.renderBufferDirect=function(L,z,Z,J,j,ve){z===null&&(z=Te);const Ae=j.isMesh&&j.matrixWorld.determinant()<0,we=zx(L,z,Z,J,j);le.setMaterial(J,Ae);let Oe=Z.index,Ke=1;if(J.wireframe===!0){if(Oe=re.getWireframeAttribute(Z),Oe===void 0)return;Ke=2}const Be=Z.drawRange,Ve=Z.attributes.position;let xt=Be.start*Ke,si=(Be.start+Be.count)*Ke;ve!==null&&(xt=Math.max(xt,ve.start*Ke),si=Math.min(si,(ve.start+ve.count)*Ke)),Oe!==null?(xt=Math.max(xt,0),si=Math.min(si,Oe.count)):Ve!=null&&(xt=Math.max(xt,0),si=Math.min(si,Ve.count));const Pt=si-xt;if(Pt<0||Pt===1/0)return;ze.setup(j,J,we,Z,Oe);let zi,mt=Ne;if(Oe!==null&&(zi=ne.get(Oe),mt=Le,mt.setIndex(zi)),j.isMesh)J.wireframe===!0?(le.setLineWidth(J.wireframeLinewidth*Ge()),mt.setMode(Y.LINES)):mt.setMode(Y.TRIANGLES);else if(j.isLine){let je=J.linewidth;je===void 0&&(je=1),le.setLineWidth(je*Ge()),j.isLineSegments?mt.setMode(Y.LINES):j.isLineLoop?mt.setMode(Y.LINE_LOOP):mt.setMode(Y.LINE_STRIP)}else j.isPoints?mt.setMode(Y.POINTS):j.isSprite&&mt.setMode(Y.TRIANGLES);if(j.isBatchedMesh)mt.renderMultiDraw(j._multiDrawStarts,j._multiDrawCounts,j._multiDrawCount);else if(j.isInstancedMesh)mt.renderInstances(xt,Pt,j.count);else if(Z.isInstancedBufferGeometry){const je=Z._maxInstanceCount!==void 0?Z._maxInstanceCount:1/0,Ho=Math.min(Z.instanceCount,je);mt.renderInstances(xt,Pt,Ho)}else mt.render(xt,Pt)};function ct(L,z,Z){L.transparent===!0&&L.side===2&&L.forceSinglePass===!1?(L.side=1,L.needsUpdate=!0,Yr(L,z,Z),L.side=0,L.needsUpdate=!0,Yr(L,z,Z),L.side=2):Yr(L,z,Z)}this.compile=function(L,z,Z=null){Z===null&&(Z=L),m=Ie.get(Z),m.init(),E.push(m),Z.traverseVisible(function(j){j.isLight&&j.layers.test(z.layers)&&(m.pushLight(j),j.castShadow&&m.pushShadow(j))}),L!==Z&&L.traverseVisible(function(j){j.isLight&&j.layers.test(z.layers)&&(m.pushLight(j),j.castShadow&&m.pushShadow(j))}),m.setupLights(_._useLegacyLights);const J=new Set;return L.traverse(function(j){const ve=j.material;if(ve)if(Array.isArray(ve))for(let Ae=0;Ae<ve.length;Ae++){const we=ve[Ae];ct(we,Z,j),J.add(we)}else ct(ve,Z,j),J.add(ve)}),E.pop(),m=null,J},this.compileAsync=function(L,z,Z=null){const J=this.compile(L,z,Z);return new Promise(j=>{function ve(){if(J.forEach(function(Ae){Me.get(Ae).currentProgram.isReady()&&J.delete(Ae)}),J.size===0){j(L);return}setTimeout(ve,10)}Re.get("KHR_parallel_shader_compile")!==null?ve():setTimeout(ve,10)})};let ht=null;function Dt(L){ht&&ht(L)}function $t(){zt.stop()}function ut(){zt.start()}const zt=new yl;zt.setAnimationLoop(Dt),typeof self<"u"&&zt.setContext(self),this.setAnimationLoop=function(L){ht=L,qe.setAnimationLoop(L),L===null?zt.stop():zt.start()},qe.addEventListener("sessionstart",$t),qe.addEventListener("sessionend",ut),this.render=function(L,z){if(z!==void 0&&z.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),z.parent===null&&z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),qe.enabled===!0&&qe.isPresenting===!0&&(qe.cameraAutoUpdate===!0&&qe.updateCamera(z),z=qe.getCamera()),L.isScene===!0&&L.onBeforeRender(_,L,z,A),m=Ie.get(L,E.length),m.init(),E.push(m),me.multiplyMatrices(z.projectionMatrix,z.matrixWorldInverse),$.setFromProjectionMatrix(me),ie=this.localClippingEnabled,ee=ke.init(this.clippingPlanes,ie),v=_e.get(L,g.length),v.init(),g.push(v),Ii(L,z,0,_.sortObjects),v.finish(),_.sortObjects===!0&&v.sort(N,B),this.info.render.frame++,ee===!0&&ke.beginShadows();const Z=m.state.shadowsArray;if(se.render(Z,L,z),ee===!0&&ke.endShadows(),this.info.autoReset===!0&&this.info.reset(),Ze.render(v,L),m.setupLights(_._useLegacyLights),z.isArrayCamera){const J=z.cameras;for(let j=0,ve=J.length;j<ve;j++){const Ae=J[j];vd(v,L,Ae,Ae.viewport)}}else vd(v,L,z);A!==null&&(I.updateMultisampleRenderTarget(A),I.updateRenderTargetMipmap(A)),L.isScene===!0&&L.onAfterRender(_,L,z),ze.resetDefaultState(),C=-1,S=null,E.pop(),E.length>0?m=E[E.length-1]:m=null,g.pop(),g.length>0?v=g[g.length-1]:v=null};function Ii(L,z,Z,J){if(L.visible===!1)return;if(L.layers.test(z.layers)){if(L.isGroup)Z=L.renderOrder;else if(L.isLOD)L.autoUpdate===!0&&L.update(z);else if(L.isLight)m.pushLight(L),L.castShadow&&m.pushShadow(L);else if(L.isSprite){if(!L.frustumCulled||$.intersectsSprite(L)){J&&be.setFromMatrixPosition(L.matrixWorld).applyMatrix4(me);const Ae=ae.update(L),we=L.material;we.visible&&v.push(L,Ae,we,Z,be.z,null)}}else if((L.isMesh||L.isLine||L.isPoints)&&(!L.frustumCulled||$.intersectsObject(L))){const Ae=ae.update(L),we=L.material;if(J&&(L.boundingSphere!==void 0?(L.boundingSphere===null&&L.computeBoundingSphere(),be.copy(L.boundingSphere.center)):(Ae.boundingSphere===null&&Ae.computeBoundingSphere(),be.copy(Ae.boundingSphere.center)),be.applyMatrix4(L.matrixWorld).applyMatrix4(me)),Array.isArray(we)){const Oe=Ae.groups;for(let Ke=0,Be=Oe.length;Ke<Be;Ke++){const Ve=Oe[Ke],xt=we[Ve.materialIndex];xt&&xt.visible&&v.push(L,Ae,xt,Z,be.z,Ve)}}else we.visible&&v.push(L,Ae,we,Z,be.z,null)}}const ve=L.children;for(let Ae=0,we=ve.length;Ae<we;Ae++)Ii(ve[Ae],z,Z,J)}function vd(L,z,Z,J){const j=L.opaque,ve=L.transmissive,Ae=L.transparent;m.setupLightsView(Z),ee===!0&&ke.setGlobalState(_.clippingPlanes,Z),ve.length>0&&$x(j,ve,z,Z),J&&le.viewport(y.copy(J)),j.length>0&&Xr(j,z,Z),ve.length>0&&Xr(ve,z,Z),Ae.length>0&&Xr(Ae,z,Z),le.buffers.depth.setTest(!0),le.buffers.depth.setMask(!0),le.buffers.color.setMask(!0),le.setPolygonOffset(!1)}function $x(L,z,Z,J){if((Z.isScene===!0?Z.overrideMaterial:null)!==null)return;const ve=Ue.isWebGL2;oe===null&&(oe=new nn(1,1,{generateMipmaps:!0,type:Re.has("EXT_color_buffer_half_float")?1016:1009,minFilter:1008,samples:ve?4:0})),_.getDrawingBufferSize(Se),ve?oe.setSize(Se.x,Se.y):oe.setSize(ea(Se.x),ea(Se.y));const Ae=_.getRenderTarget();_.setRenderTarget(oe),_.getClearColor(X),P=_.getClearAlpha(),P<1&&_.setClearColor(16777215,.5),_.clear();const we=_.toneMapping;_.toneMapping=0,Xr(L,Z,J),I.updateMultisampleRenderTarget(oe),I.updateRenderTargetMipmap(oe);let Oe=!1;for(let Ke=0,Be=z.length;Ke<Be;Ke++){const Ve=z[Ke],xt=Ve.object,si=Ve.geometry,Pt=Ve.material,zi=Ve.group;if(Pt.side===2&&xt.layers.test(J.layers)){const mt=Pt.side;Pt.side=1,Pt.needsUpdate=!0,_d(xt,Z,J,si,Pt,zi),Pt.side=mt,Pt.needsUpdate=!0,Oe=!0}}Oe===!0&&(I.updateMultisampleRenderTarget(oe),I.updateRenderTargetMipmap(oe)),_.setRenderTarget(Ae),_.setClearColor(X,P),_.toneMapping=we}function Xr(L,z,Z){const J=z.isScene===!0?z.overrideMaterial:null;for(let j=0,ve=L.length;j<ve;j++){const Ae=L[j],we=Ae.object,Oe=Ae.geometry,Ke=J===null?Ae.material:J,Be=Ae.group;we.layers.test(Z.layers)&&_d(we,z,Z,Oe,Ke,Be)}}function _d(L,z,Z,J,j,ve){L.onBeforeRender(_,z,Z,J,j,ve),L.modelViewMatrix.multiplyMatrices(Z.matrixWorldInverse,L.matrixWorld),L.normalMatrix.getNormalMatrix(L.modelViewMatrix),j.onBeforeRender(_,z,Z,J,L,ve),j.transparent===!0&&j.side===2&&j.forceSinglePass===!1?(j.side=1,j.needsUpdate=!0,_.renderBufferDirect(Z,z,J,j,L,ve),j.side=0,j.needsUpdate=!0,_.renderBufferDirect(Z,z,J,j,L,ve),j.side=2):_.renderBufferDirect(Z,z,J,j,L,ve),L.onAfterRender(_,z,Z,J,j,ve)}function Yr(L,z,Z){z.isScene!==!0&&(z=Te);const J=Me.get(L),j=m.state.lights,ve=m.state.shadowsArray,Ae=j.state.version,we=ye.getParameters(L,j.state,ve,z,Z),Oe=ye.getProgramCacheKey(we);let Ke=J.programs;J.environment=L.isMeshStandardMaterial?z.environment:null,J.fog=z.fog,J.envMap=(L.isMeshStandardMaterial?K:M).get(L.envMap||J.environment),Ke===void 0&&(L.addEventListener("dispose",pe),Ke=new Map,J.programs=Ke);let Be=Ke.get(Oe);if(Be!==void 0){if(J.currentProgram===Be&&J.lightsStateVersion===Ae)return xd(L,we),Be}else we.uniforms=ye.getUniforms(L),L.onBuild(Z,we,_),L.onBeforeCompile(we,_),Be=ye.acquireProgram(we,Oe),Ke.set(Oe,Be),J.uniforms=we.uniforms;const Ve=J.uniforms;return(!L.isShaderMaterial&&!L.isRawShaderMaterial||L.clipping===!0)&&(Ve.clippingPlanes=ke.uniform),xd(L,we),J.needsLights=Kx(L),J.lightsStateVersion=Ae,J.needsLights&&(Ve.ambientLightColor.value=j.state.ambient,Ve.lightProbe.value=j.state.probe,Ve.directionalLights.value=j.state.directional,Ve.directionalLightShadows.value=j.state.directionalShadow,Ve.spotLights.value=j.state.spot,Ve.spotLightShadows.value=j.state.spotShadow,Ve.rectAreaLights.value=j.state.rectArea,Ve.ltc_1.value=j.state.rectAreaLTC1,Ve.ltc_2.value=j.state.rectAreaLTC2,Ve.pointLights.value=j.state.point,Ve.pointLightShadows.value=j.state.pointShadow,Ve.hemisphereLights.value=j.state.hemi,Ve.directionalShadowMap.value=j.state.directionalShadowMap,Ve.directionalShadowMatrix.value=j.state.directionalShadowMatrix,Ve.spotShadowMap.value=j.state.spotShadowMap,Ve.spotLightMatrix.value=j.state.spotLightMatrix,Ve.spotLightMap.value=j.state.spotLightMap,Ve.pointShadowMap.value=j.state.pointShadowMap,Ve.pointShadowMatrix.value=j.state.pointShadowMatrix),J.currentProgram=Be,J.uniformsList=null,Be}function Ed(L){if(L.uniformsList===null){const z=L.currentProgram.getUniforms();L.uniformsList=nr.seqWithValue(z.seq,L.uniforms)}return L.uniformsList}function xd(L,z){const Z=Me.get(L);Z.outputColorSpace=z.outputColorSpace,Z.batching=z.batching,Z.instancing=z.instancing,Z.instancingColor=z.instancingColor,Z.skinning=z.skinning,Z.morphTargets=z.morphTargets,Z.morphNormals=z.morphNormals,Z.morphColors=z.morphColors,Z.morphTargetsCount=z.morphTargetsCount,Z.numClippingPlanes=z.numClippingPlanes,Z.numIntersection=z.numClipIntersection,Z.vertexAlphas=z.vertexAlphas,Z.vertexTangents=z.vertexTangents,Z.toneMapping=z.toneMapping}function zx(L,z,Z,J,j){z.isScene!==!0&&(z=Te),I.resetTextureUnits();const ve=z.fog,Ae=J.isMeshStandardMaterial?z.environment:null,we=A===null?_.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ci,Oe=(J.isMeshStandardMaterial?K:M).get(J.envMap||Ae),Ke=J.vertexColors===!0&&!!Z.attributes.color&&Z.attributes.color.itemSize===4,Be=!!Z.attributes.tangent&&(!!J.normalMap||J.anisotropy>0),Ve=!!Z.morphAttributes.position,xt=!!Z.morphAttributes.normal,si=!!Z.morphAttributes.color;let Pt=0;J.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(Pt=_.toneMapping);const zi=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,mt=zi!==void 0?zi.length:0,je=Me.get(J),Ho=m.state.lights;if(ee===!0&&(ie===!0||L!==S)){const hi=L===S&&J.id===C;ke.setState(J,L,hi)}let _t=!1;J.version===je.__version?(je.needsLights&&je.lightsStateVersion!==Ho.state.version||je.outputColorSpace!==we||j.isBatchedMesh&&je.batching===!1||!j.isBatchedMesh&&je.batching===!0||j.isInstancedMesh&&je.instancing===!1||!j.isInstancedMesh&&je.instancing===!0||j.isSkinnedMesh&&je.skinning===!1||!j.isSkinnedMesh&&je.skinning===!0||j.isInstancedMesh&&je.instancingColor===!0&&j.instanceColor===null||j.isInstancedMesh&&je.instancingColor===!1&&j.instanceColor!==null||je.envMap!==Oe||J.fog===!0&&je.fog!==ve||je.numClippingPlanes!==void 0&&(je.numClippingPlanes!==ke.numPlanes||je.numIntersection!==ke.numIntersection)||je.vertexAlphas!==Ke||je.vertexTangents!==Be||je.morphTargets!==Ve||je.morphNormals!==xt||je.morphColors!==si||je.toneMapping!==Pt||Ue.isWebGL2===!0&&je.morphTargetsCount!==mt)&&(_t=!0):(_t=!0,je.__version=J.version);let _n=je.currentProgram;_t===!0&&(_n=Yr(J,z,j));let Sd=!1,bs=!1,$o=!1;const Bt=_n.getUniforms(),En=je.uniforms;if(le.useProgram(_n.program)&&(Sd=!0,bs=!0,$o=!0),J.id!==C&&(C=J.id,bs=!0),Sd||S!==L){Bt.setValue(Y,"projectionMatrix",L.projectionMatrix),Bt.setValue(Y,"viewMatrix",L.matrixWorldInverse);const hi=Bt.map.cameraPosition;hi!==void 0&&hi.setValue(Y,be.setFromMatrixPosition(L.matrixWorld)),Ue.logarithmicDepthBuffer&&Bt.setValue(Y,"logDepthBufFC",2/(Math.log(L.far+1)/Math.LN2)),(J.isMeshPhongMaterial||J.isMeshToonMaterial||J.isMeshLambertMaterial||J.isMeshBasicMaterial||J.isMeshStandardMaterial||J.isShaderMaterial)&&Bt.setValue(Y,"isOrthographic",L.isOrthographicCamera===!0),S!==L&&(S=L,bs=!0,$o=!0)}if(j.isSkinnedMesh){Bt.setOptional(Y,j,"bindMatrix"),Bt.setOptional(Y,j,"bindMatrixInverse");const hi=j.skeleton;hi&&(Ue.floatVertexTextures?(hi.boneTexture===null&&hi.computeBoneTexture(),Bt.setValue(Y,"boneTexture",hi.boneTexture,I)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}j.isBatchedMesh&&(Bt.setOptional(Y,j,"batchingTexture"),Bt.setValue(Y,"batchingTexture",j._matricesTexture,I));const zo=Z.morphAttributes;if((zo.position!==void 0||zo.normal!==void 0||zo.color!==void 0&&Ue.isWebGL2===!0)&&Qe.update(j,Z,_n),(bs||je.receiveShadow!==j.receiveShadow)&&(je.receiveShadow=j.receiveShadow,Bt.setValue(Y,"receiveShadow",j.receiveShadow)),J.isMeshGouraudMaterial&&J.envMap!==null&&(En.envMap.value=Oe,En.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),bs&&(Bt.setValue(Y,"toneMappingExposure",_.toneMappingExposure),je.needsLights&&Wx(En,$o),ve&&J.fog===!0&&ue.refreshFogUniforms(En,ve),ue.refreshMaterialUniforms(En,J,k,D,oe),nr.upload(Y,Ed(je),En,I)),J.isShaderMaterial&&J.uniformsNeedUpdate===!0&&(nr.upload(Y,Ed(je),En,I),J.uniformsNeedUpdate=!1),J.isSpriteMaterial&&Bt.setValue(Y,"center",j.center),Bt.setValue(Y,"modelViewMatrix",j.modelViewMatrix),Bt.setValue(Y,"normalMatrix",j.normalMatrix),Bt.setValue(Y,"modelMatrix",j.matrixWorld),J.isShaderMaterial||J.isRawShaderMaterial){const hi=J.uniformsGroups;for(let Wo=0,Xx=hi.length;Wo<Xx;Wo++)if(Ue.isWebGL2){const yd=hi[Wo];it.update(yd,_n),it.bind(yd,_n)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return _n}function Wx(L,z){L.ambientLightColor.needsUpdate=z,L.lightProbe.needsUpdate=z,L.directionalLights.needsUpdate=z,L.directionalLightShadows.needsUpdate=z,L.pointLights.needsUpdate=z,L.pointLightShadows.needsUpdate=z,L.spotLights.needsUpdate=z,L.spotLightShadows.needsUpdate=z,L.rectAreaLights.needsUpdate=z,L.hemisphereLights.needsUpdate=z}function Kx(L){return L.isMeshLambertMaterial||L.isMeshToonMaterial||L.isMeshPhongMaterial||L.isMeshStandardMaterial||L.isShadowMaterial||L.isShaderMaterial&&L.lights===!0}this.getActiveCubeFace=function(){return b},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(L,z,Z){Me.get(L.texture).__webglTexture=z,Me.get(L.depthTexture).__webglTexture=Z;const J=Me.get(L);J.__hasExternalTextures=!0,J.__hasExternalTextures&&(J.__autoAllocateDepthBuffer=Z===void 0,J.__autoAllocateDepthBuffer||Re.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),J.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(L,z){const Z=Me.get(L);Z.__webglFramebuffer=z,Z.__useDefaultFramebuffer=z===void 0},this.setRenderTarget=function(L,z=0,Z=0){A=L,b=z,R=Z;let J=!0,j=null,ve=!1,Ae=!1;if(L){const Oe=Me.get(L);Oe.__useDefaultFramebuffer!==void 0?(le.bindFramebuffer(Y.FRAMEBUFFER,null),J=!1):Oe.__webglFramebuffer===void 0?I.setupRenderTarget(L):Oe.__hasExternalTextures&&I.rebindTextures(L,Me.get(L.texture).__webglTexture,Me.get(L.depthTexture).__webglTexture);const Ke=L.texture;(Ke.isData3DTexture||Ke.isDataArrayTexture||Ke.isCompressedArrayTexture)&&(Ae=!0);const Be=Me.get(L).__webglFramebuffer;L.isWebGLCubeRenderTarget?(Array.isArray(Be[z])?j=Be[z][Z]:j=Be[z],ve=!0):Ue.isWebGL2&&L.samples>0&&I.useMultisampledRTT(L)===!1?j=Me.get(L).__webglMultisampledFramebuffer:Array.isArray(Be)?j=Be[Z]:j=Be,y.copy(L.viewport),w.copy(L.scissor),U=L.scissorTest}else y.copy(q).multiplyScalar(k).floor(),w.copy(V).multiplyScalar(k).floor(),U=W;if(le.bindFramebuffer(Y.FRAMEBUFFER,j)&&Ue.drawBuffers&&J&&le.drawBuffers(L,j),le.viewport(y),le.scissor(w),le.setScissorTest(U),ve){const Oe=Me.get(L.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_CUBE_MAP_POSITIVE_X+z,Oe.__webglTexture,Z)}else if(Ae){const Oe=Me.get(L.texture),Ke=z||0;Y.framebufferTextureLayer(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Oe.__webglTexture,Z||0,Ke)}C=-1},this.readRenderTargetPixels=function(L,z,Z,J,j,ve,Ae){if(!(L&&L.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let we=Me.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ae!==void 0&&(we=we[Ae]),we){le.bindFramebuffer(Y.FRAMEBUFFER,we);try{const Oe=L.texture,Ke=Oe.format,Be=Oe.type;if(Ke!==1023&&xe.convert(Ke)!==Y.getParameter(Y.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const Ve=Be===1016&&(Re.has("EXT_color_buffer_half_float")||Ue.isWebGL2&&Re.has("EXT_color_buffer_float"));if(Be!==1009&&xe.convert(Be)!==Y.getParameter(Y.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Be===1015&&(Ue.isWebGL2||Re.has("OES_texture_float")||Re.has("WEBGL_color_buffer_float")))&&!Ve){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}z>=0&&z<=L.width-J&&Z>=0&&Z<=L.height-j&&Y.readPixels(z,Z,J,j,xe.convert(Ke),xe.convert(Be),ve)}finally{const Oe=A!==null?Me.get(A).__webglFramebuffer:null;le.bindFramebuffer(Y.FRAMEBUFFER,Oe)}}},this.copyFramebufferToTexture=function(L,z,Z=0){const J=Math.pow(2,-Z),j=Math.floor(z.image.width*J),ve=Math.floor(z.image.height*J);I.setTexture2D(z,0),Y.copyTexSubImage2D(Y.TEXTURE_2D,Z,0,0,L.x,L.y,j,ve),le.unbindTexture()},this.copyTextureToTexture=function(L,z,Z,J=0){const j=z.image.width,ve=z.image.height,Ae=xe.convert(Z.format),we=xe.convert(Z.type);I.setTexture2D(Z,0),Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,Z.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Z.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,Z.unpackAlignment),z.isDataTexture?Y.texSubImage2D(Y.TEXTURE_2D,J,L.x,L.y,j,ve,Ae,we,z.image.data):z.isCompressedTexture?Y.compressedTexSubImage2D(Y.TEXTURE_2D,J,L.x,L.y,z.mipmaps[0].width,z.mipmaps[0].height,Ae,z.mipmaps[0].data):Y.texSubImage2D(Y.TEXTURE_2D,J,L.x,L.y,Ae,we,z.image),J===0&&Z.generateMipmaps&&Y.generateMipmap(Y.TEXTURE_2D),le.unbindTexture()},this.copyTextureToTexture3D=function(L,z,Z,J,j=0){if(_.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ve=L.max.x-L.min.x+1,Ae=L.max.y-L.min.y+1,we=L.max.z-L.min.z+1,Oe=xe.convert(J.format),Ke=xe.convert(J.type);let Be;if(J.isData3DTexture)I.setTexture3D(J,0),Be=Y.TEXTURE_3D;else if(J.isDataArrayTexture||J.isCompressedArrayTexture)I.setTexture2DArray(J,0),Be=Y.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,J.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,J.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,J.unpackAlignment);const Ve=Y.getParameter(Y.UNPACK_ROW_LENGTH),xt=Y.getParameter(Y.UNPACK_IMAGE_HEIGHT),si=Y.getParameter(Y.UNPACK_SKIP_PIXELS),Pt=Y.getParameter(Y.UNPACK_SKIP_ROWS),zi=Y.getParameter(Y.UNPACK_SKIP_IMAGES),mt=Z.isCompressedTexture?Z.mipmaps[j]:Z.image;Y.pixelStorei(Y.UNPACK_ROW_LENGTH,mt.width),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,mt.height),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,L.min.x),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,L.min.y),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,L.min.z),Z.isDataTexture||Z.isData3DTexture?Y.texSubImage3D(Be,j,z.x,z.y,z.z,ve,Ae,we,Oe,Ke,mt.data):Z.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),Y.compressedTexSubImage3D(Be,j,z.x,z.y,z.z,ve,Ae,we,Oe,mt.data)):Y.texSubImage3D(Be,j,z.x,z.y,z.z,ve,Ae,we,Oe,Ke,mt),Y.pixelStorei(Y.UNPACK_ROW_LENGTH,Ve),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,xt),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,si),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,Pt),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,zi),j===0&&J.generateMipmaps&&Y.generateMipmap(Be),le.unbindTexture()},this.initTexture=function(L){L.isCubeTexture?I.setTextureCube(L,0):L.isData3DTexture?I.setTexture3D(L,0):L.isDataArrayTexture||L.isCompressedArrayTexture?I.setTexture2DArray(L,0):I.setTexture2D(L,0),le.unbindTexture()},this.resetState=function(){b=0,R=0,A=null,le.reset(),ze.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return 2e3}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===jr?"display-p3":"srgb",t.unpackColorSpace=st.workingColorSpace===Rs?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===Mt?3001:3e3}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===3001?Mt:Ci}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class Zg extends Ql{}Zg.prototype.isWebGL1Renderer=!0;class Jg extends Jt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t}}class e0 extends Xt{constructor(e,t,i,n,r,a,o,l,c){super(e,t,i,n,r,a,o,l,c),this.isVideoTexture=!0,this.minFilter=a!==void 0?a:1006,this.magFilter=r!==void 0?r:1006,this.generateMipmaps=!1;const h=this;function u(){h.needsUpdate=!0,e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(u)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class rr extends ji{constructor(e=1,t=32,i=16,n=0,r=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const l=Math.min(a+o,Math.PI);let c=0;const h=[],u=new Q,d=new Q,f=[],p=[],v=[],m=[];for(let g=0;g<=i;g++){const E=[],_=g/i;let T=0;g===0&&a===0?T=.5/t:g===i&&l===Math.PI&&(T=-.5/t);for(let b=0;b<=t;b++){const R=b/t;u.x=-e*Math.cos(n+R*r)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(n+R*r)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),v.push(d.x,d.y,d.z),m.push(R+T,1-_),E.push(c++)}h.push(E)}for(let g=0;g<i;g++)for(let E=0;E<t;E++){const _=h[g][E+1],T=h[g][E],b=h[g+1][E],R=h[g+1][E+1];(g!==0||a>0)&&f.push(_,T,R),(g!==i-1||l<Math.PI)&&f.push(T,b,R)}this.setIndex(f),this.setAttribute("position",new xi(p,3)),this.setAttribute("normal",new xi(v,3)),this.setAttribute("uv",new xi(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new rr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:qr}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=qr);class Vn{static createButton(e){const t=document.createElement("button");function i(){let l=null;async function c(d){d.addEventListener("end",h),await e.xr.setSession(d),t.textContent="EXIT VR",l=d}function h(){l.removeEventListener("end",h),t.textContent="ENTER VR",l=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="ENTER VR";const u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","layers"]};t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){l===null?navigator.xr.requestSession("immersive-vr",u).then(c):(l.end(),navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",u).then(c))},navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",u).then(c)}function n(){t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function r(){n(),t.textContent="VR NOT SUPPORTED"}function a(l){n(),console.warn("Exception when trying to call xr.isSessionSupported",l),t.textContent="VR NOT ALLOWED"}function o(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return t.id="VRButton",t.style.display="none",o(t),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),l&&Vn.xrSessionIsGranted&&t.click()}).catch(a),t;{const l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",o(l),l}}static registerSessionGrantedListener(){if(typeof navigator<"u"&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{Vn.xrSessionIsGranted=!0})}}}Vn.xrSessionIsGranted=!1,Vn.registerSessionGrantedListener();const Ui={"180-sbs":{geom:"sphere180",split:"sbs",stereo:!0},"180-mono":{geom:"sphere180",split:"mono",stereo:!1},"360-mono":{geom:"sphere360",split:"mono",stereo:!1},"360-sbs":{geom:"sphere360",split:"sbs",stereo:!0},"360-tb":{geom:"sphere360",split:"tb",stereo:!0},"flat-2d":{geom:"plane",split:"mono",stereo:!1,flat:!0,aspect:"full"},"flat-sbs-full":{geom:"plane",split:"sbs",stereo:!0,flat:!0,aspect:"per-eye"},"flat-sbs-half":{geom:"plane",split:"sbs",stereo:!0,flat:!0,aspect:"full"}},Zl=[{value:"180-sbs",label:"180° SBS (VR180)"},{value:"180-mono",label:"180° Mono"},{value:"360-mono",label:"360° Mono"},{value:"360-sbs",label:"360° SBS"},{value:"360-tb",label:"360° Top-Bottom"},{value:"flat-2d",label:"Flat 2D (regular movie)"},{value:"flat-sbs-full",label:"Flat 3D — Full SBS"},{value:"flat-sbs-half",label:"Flat 3D — Half SBS"}];function t0(s){var e;return!!((e=Ui[s])!=null&&e.flat)}function Jl(s){const e=String(s).toLowerCase(),t=/(^|[^a-z])(tb|ou|top.?bottom|over.?under)([^a-z]|$)/.test(e),i=/(sbs|side.?by.?side)/.test(e);return e.includes("360")?t?"360-tb":i?"360-sbs":"360-mono":e.includes("180")||e.includes("vr180")?e.includes("mono")?"180-mono":"180-sbs":i?e.includes("half")?"flat-sbs-half":"flat-sbs-full":null}class ec{constructor(e){this.scene=new Jg,this.meshes=[],this.frameCbs=[],this.animate=()=>{for(const l of this.frameCbs)l();this.renderer.render(this.scene,this.camera)},this.resize=()=>{const l=this.w(),c=this.h();this.camera.aspect=l/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(l,c,!1)};const{canvas:t,video:i,projection:n="180-sbs",swapEyes:r=!1,fov:a=70,supersampling:o=1.5}=e;this.canvas=t,this.video=i,this.currentMode=Ui[n]?n:"180-sbs",this.currentSwap=r,this.renderer=new Ql({canvas:t,antialias:!0}),this.renderer.setPixelRatio(this.pixelRatioFor(o)),this.renderer.setSize(this.w(),this.h(),!1),this.renderer.xr.enabled=!0,this.camera=new oi(a,this.w()/this.h(),.1,1e3),this.camera.position.set(0,0,0),this.camera.layers.enable(1),this.maxAnisotropy=this.renderer.capabilities.getMaxAnisotropy(),this.texture=new e0(i),this.texture.colorSpace=Mt,this.texture.minFilter=1006,this.texture.magFilter=1006,this.texture.anisotropy=this.maxAnisotropy,this.applyProjection(this.currentMode,this.currentSwap),i.addEventListener("loadedmetadata",()=>{Ui[this.currentMode].flat&&this.applyProjection(this.currentMode,this.currentSwap)}),this.renderer.setAnimationLoop(this.animate),this.vrButton=Vn.createButton(this.renderer),this.ro=new ResizeObserver(()=>this.resize()),this.ro.observe(t)}w(){return this.canvas.clientWidth||1}h(){return this.canvas.clientHeight||1}pixelRatioFor(e){return Math.min(window.devicePixelRatio*e,4)}planeAspect(e){const t=this.video.videoWidth,i=this.video.videoHeight;return!t||!i?1.7777777777777777:Ui[e].aspect==="per-eye"?t/2/i:t/i}buildGeometry(e){const t=Ui[e].geom;if(t==="sphere180"){const a=new rr(500,60,40,-Math.PI,Math.PI,0,Math.PI);return a.scale(-1,1,1),a}if(t==="sphere360"){const a=new rr(500,60,40);return a.scale(-1,1,1),a}const i=2.4,n=i*this.planeAspect(e),r=new Js(n,i);return r.translate(0,0,-2),r}splitUV(e,t,i){if(t==="mono")return;const n=e.attributes.uv.array;for(let r=0;r<n.length;r+=2)t==="sbs"?n[r]=n[r]*.5+(i==="right"?.5:0):t==="tb"&&(n[r+1]=n[r+1]*.5+(i==="left"?.5:0));e.attributes.uv.needsUpdate=!0}clearMeshes(){for(const e of this.meshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.meshes.length=0}applyProjection(e,t){Ui[e]||(e="180-sbs"),this.clearMeshes();const i=Ui[e];if(i.stereo){const n=this.buildGeometry(e);this.splitUV(n,i.split,"left");const r=this.buildGeometry(e);this.splitUV(r,i.split,"right");const a=new mi(n,new hs({map:this.texture})),o=new mi(r,new hs({map:this.texture}));a.layers.set(t?2:1),o.layers.set(t?1:2),this.scene.add(a,o),this.meshes.push(a,o)}else{const n=new mi(this.buildGeometry(e),new hs({map:this.texture}));n.layers.set(0),this.scene.add(n),this.meshes.push(n)}this.currentMode=e,this.currentSwap=t}setProjection(e){this.applyProjection(e,this.currentSwap)}setSwapEyes(e){this.applyProjection(this.currentMode,e)}setFov(e){this.camera.fov=e,this.camera.updateProjectionMatrix()}setSupersampling(e){this.renderer.setPixelRatio(this.pixelRatioFor(e)),this.renderer.setSize(this.w(),this.h(),!1)}getProjection(){return this.currentMode}isFlat(){return!!Ui[this.currentMode].flat}onFrame(e){this.frameCbs.push(e)}pauseRendering(){this.renderer.setAnimationLoop(null)}resumeRendering(){this.renderer.setAnimationLoop(this.animate)}dispose(){this.ro.disconnect(),this.renderer.setAnimationLoop(null),this.texture.dispose(),this.clearMeshes(),this.renderer.dispose()}}const tc=Math.PI/180;function ic(s,e){return{lon:Math.max(-90,Math.min(90,s)),lat:Math.max(-85,Math.min(85,e))}}class nc{constructor(e,t,i={}){this.camera=e,this.dom=t,this.lon=0,this.lat=0,this.dragging=!1,this.px=0,this.py=0,this.enabled=!0,this.onDown=n=>{this.enabled&&(this.dragging=!0,this.px=n.clientX,this.py=n.clientY,this.capture("setPointerCapture",n.pointerId))},this.onMove=n=>{if(!this.dragging)return;const r=n.clientX-this.px,a=n.clientY-this.py;this.px=n.clientX,this.py=n.clientY,{lon:this.lon,lat:this.lat}=ic(this.lon-r*.15,this.lat+a*.15)},this.onUp=n=>{this.dragging=!1,this.capture("releasePointerCapture",n.pointerId)},this.isPresenting=i.isPresenting??(()=>!1),this.dom.addEventListener("pointerdown",this.onDown),this.dom.addEventListener("pointermove",this.onMove),this.dom.addEventListener("pointerup",this.onUp),this.dom.addEventListener("pointercancel",this.onUp)}capture(e,t){var i,n;try{(n=(i=this.dom)[e])==null||n.call(i,t)}catch{}}update(){if(this.isPresenting()||!this.enabled)return;const e=(90-this.lat)*tc,t=this.lon*tc;this.camera.lookAt(Math.sin(e)*Math.sin(t),Math.cos(e),-Math.sin(e)*Math.cos(t))}reset(){this.lon=0,this.lat=0}setEnabled(e){this.enabled=e,e||(this.lon=0,this.lat=0,this.camera.lookAt(0,0,-1))}getAngles(){return{lon:this.lon,lat:this.lat}}dispose(){this.dom.removeEventListener("pointerdown",this.onDown),this.dom.removeEventListener("pointermove",this.onMove),this.dom.removeEventListener("pointerup",this.onUp),this.dom.removeEventListener("pointercancel",this.onUp)}}class sc{constructor(){this.hls=null}async attach(e,t,i={}){this.dispose();const n=i.crossOrigin===void 0?"anonymous":i.crossOrigin;n===null?e.removeAttribute("crossorigin"):e.crossOrigin=n,e.playsInline=!0;const{url:r,format:a}=t,o=a==="hls"||a==="dash",l=e.canPlayType("application/vnd.apple.mpegurl")!=="";return new Promise((c,h)=>{const u=()=>{e.removeEventListener("loadedmetadata",d),e.removeEventListener("error",f)},d=()=>{u(),c()},f=()=>{u();const p=e.error?e.error.code:"unknown";h(new Error(`Video failed to load (media error ${p}). Is the source reachable and CORS-clean?`))};e.addEventListener("loadedmetadata",d),e.addEventListener("error",f),o&&!l?Promise.resolve().then(()=>Hx).then(({default:p})=>{if(!p.isSupported()){u(),h(new Error("HLS/DASH stream needs hls.js, which is unsupported in this browser."));return}this.hls=new p({enableWorker:!0}),this.hls.on(p.Events.ERROR,(v,m)=>{m.fatal&&(u(),this.dispose(),h(new Error(`HLS fatal error: ${m.type} / ${m.details}`)))}),this.hls.loadSource(r),this.hls.attachMedia(e)}).catch(()=>{u(),h(new Error('This looks like an HLS/DASH stream but hls.js could not be loaded. Install "hls.js".'))}):(e.src=r,e.load())})}dispose(){this.hls&&(this.hls.destroy(),this.hls=null)}}function rc(s){let e=s;try{e=new URL(s).pathname}catch{}const t=e.toLowerCase();return t.endsWith(".m3u8")?"hls":t.endsWith(".mpd")?"dash":"progressive"}const i0={progressive:"/proxy/stream",hls:"/proxy/hls/manifest.m3u8",dash:"/proxy/mpd/manifest.m3u8"};function ac(s,e){const t=rc(s);if(!e||!e.url)return{url:s,format:t};const i=e.url.replace(/\/+$/,""),n=new URLSearchParams;n.set("d",s),e.apiPassword&&n.set("api_password",e.apiPassword);for(const[r,a]of Object.entries(e.headers??{}))a!=null&&a!==""&&n.set(`h_${r}`,a);return{url:`${i}${i0[t]}?${n.toString()}`,format:t}}function oc(s){if(!Number.isFinite(s)||s<0)return"0:00";const e=Math.floor(s%60),t=Math.floor(s/60%60),i=Math.floor(s/3600),n=String(e).padStart(2,"0");return i>0?`${i}:${String(t).padStart(2,"0")}:${n}`:`${t}:${n}`}function Je(s,e={},t=[]){const i=document.createElement(s),{class:n,...r}=e;n&&(i.className=n),Object.assign(i,r);for(const a of t)i.append(a);return i}class n0{constructor(e,t){this.nodes=[],this.disposers=[];const i=t.video,n=Je("button",{class:"tvp-btn tvp-play",title:"Play/Pause",textContent:"▶"}),r=Je("input",{class:"tvp-seek",type:"range",min:"0",max:"1000",value:"0"}),a=Je("span",{class:"tvp-time",textContent:"0:00 / 0:00"}),o=Je("button",{class:"tvp-btn tvp-mute",title:"Volume",textContent:"🔊"}),l=Je("input",{class:"tvp-volume",type:"range",min:"0",max:"1",step:"0.01",value:"1"}),c=Je("div",{class:"tvp-volpopup",hidden:!0},[l]),h=Je("span",{class:"tvp-volwrap"},[o,c]),u=Je("span",{class:"tvp-vrslot"}),d=Je("button",{class:"tvp-btn tvp-projbtn",title:"Projection",textContent:"🌐"}),f=Je("div",{class:"tvp-projmenu",hidden:!0});for(const D of Zl){const k=Je("button",{textContent:D.label});k.dataset.mode=D.value,f.append(k)}const p=Je("span",{class:"tvp-projwrap"},[d,f]),v=Je("button",{class:"tvp-btn tvp-settingsbtn",title:"Settings",textContent:"⚙"}),m=Je("button",{class:"tvp-btn tvp-fullscreen",title:"Fullscreen",textContent:"⛶"}),g=Je("footer",{class:"tvp-controls"},[n,r,a,h,u,p,v,m]),E=Je("input",{type:"checkbox",checked:t.initial.swapEyes}),_=Je("input",{type:"range",min:"30",max:"100",step:"1",value:String(t.initial.fov)}),T=Je("span",{textContent:String(t.initial.fov)}),b=Je("input",{type:"range",min:"1",max:"2",step:"0.25",value:String(t.initial.supersampling)}),R=Je("span",{textContent:String(t.initial.supersampling)}),A=Je("input",{type:"checkbox",checked:t.proxy.enabled}),C=Je("input",{type:"text",value:t.proxy.url,placeholder:"http://localhost:8888",spellcheck:!1}),S=Je("input",{type:"password",value:t.proxy.apiPassword,placeholder:"API password"}),y=Je("section",{class:"tvp-settings"},[Je("label",{class:"row"},[E,"Swap eyes (if depth looks wrong)"]),Je("label",{},[lc("Field of view (zoom): ",T,"°"),_]),Je("label",{},[lc("Supersampling: ",R,"× (sharpness)"),b]),Je("hr",{class:"tvp-sep"}),Je("label",{class:"row"},[A,"Use CORS proxy"]),Je("label",{},["Proxy URL",C]),Je("label",{},["API password",S])]),w=Je("div",{class:"tvp-toast"});this.nodes.push(g,y,w);for(const D of this.nodes)e.append(D);const U=(D,k,N,B)=>{D.addEventListener(k,N,B),this.disposers.push(()=>D.removeEventListener(k,N,B))},X=D=>r.style.setProperty("--seek",`${D}%`);U(n,"click",()=>{i.paused?i.play():i.pause()}),U(i,"play",()=>{n.textContent="⏸"}),U(i,"pause",()=>{n.textContent="▶"}),U(i,"timeupdate",()=>{if(i.duration){const D=i.currentTime/i.duration*100;r.value=String(D*10),X(D),a.textContent=`${oc(i.currentTime)} / ${oc(i.duration)}`}}),U(r,"input",()=>{X(Number(r.value)/10),i.duration&&(i.currentTime=Number(r.value)/1e3*i.duration)}),U(o,"click",D=>{D.stopPropagation(),c.hidden=!c.hidden}),U(l,"input",()=>{i.volume=Number(l.value),i.muted=i.volume===0,o.textContent=i.muted?"🔇":"🔊"});const P=()=>{const D=t.getProjection();let k="Projection";f.querySelectorAll("button").forEach(N=>{const B=N.dataset.mode===D;N.classList.toggle("active",B),B&&(k=`Projection: ${N.textContent}`)}),d.title=k};U(d,"click",D=>{D.stopPropagation(),f.hidden=!f.hidden}),U(f,"click",D=>{const k=D.target.closest("button[data-mode]");k&&(t.setProjection(k.dataset.mode),P(),f.hidden=!0)}),P(),U(v,"click",D=>{D.stopPropagation(),y.classList.toggle("open")}),U(E,"change",()=>t.setSwapEyes(E.checked)),U(_,"input",()=>{const D=Number(_.value);T.textContent=String(D),t.setFov(D)}),U(b,"input",()=>{const D=Number(b.value);R.textContent=String(D),t.setSupersampling(D)});const F=()=>t.setProxy({url:C.value.trim(),apiPassword:S.value,enabled:A.checked});U(A,"change",F),U(C,"change",F),U(S,"change",F),U(t.surface,"wheel",D=>{D.preventDefault();const k=Math.max(30,Math.min(100,Number(_.value)+Math.sign(D.deltaY)*3));_.value=String(k),T.textContent=String(k),t.setFov(k)},{passive:!1}),U(m,"click",()=>{var k,N;const D=t.fullscreenTarget;document.fullscreenElement?(N=document.exitFullscreen)==null||N.call(document):(k=D.requestFullscreen)==null||k.call(D)}),U(document,"click",D=>{const k=D.composedPath();!c.hidden&&!k.includes(c)&&!k.includes(o)&&(c.hidden=!0),!f.hidden&&!k.includes(f)&&!k.includes(d)&&(f.hidden=!0)}),t.vrSupported().then(D=>{D&&(Object.assign(t.vrButton.style,{position:"static",left:"auto",bottom:"auto",transform:"none",margin:"0"}),u.append(t.vrButton))})}dispose(){for(const e of this.disposers)e();for(const e of this.nodes)e.remove()}}function lc(s,e,t){const i=document.createDocumentFragment();return i.append(s,e,t),i}const cc=":host,:host *,.tvp,.tvp *{box-sizing:border-box}.tvp-canvas{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab}.tvp-canvas:active{cursor:grabbing}.tvp-video{display:none}.tvp-controls{position:absolute;left:0;right:0;bottom:0;display:flex;align-items:center;gap:10px;padding:12px;background:linear-gradient(transparent,#000c);z-index:5;font:14px system-ui,Segoe UI,Roboto,sans-serif;color:#e8eaed}.tvp-btn{padding:4px;border:0;background:none;color:#e8eaed;cursor:pointer;font-size:22px;line-height:1}.tvp-btn:hover{opacity:.7}.tvp-seek{flex:1;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:14px;background:transparent;cursor:pointer;margin:0}.tvp-seek::-webkit-slider-runnable-track{height:4px;border-radius:2px;background:linear-gradient(to right,#4f8cff var(--seek,0%),#3a4150 var(--seek,0%))}.tvp-seek::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-top:-4px;width:12px;height:12px;border-radius:50%;background:#fff;cursor:pointer}.tvp-seek::-moz-range-track{height:4px;border-radius:2px;background:#3a4150}.tvp-seek::-moz-range-progress{height:4px;border-radius:2px;background:#4f8cff}.tvp-seek::-moz-range-thumb{width:12px;height:12px;border:0;border-radius:50%;background:#fff;cursor:pointer}.tvp-time{font-variant-numeric:tabular-nums;min-width:96px;text-align:center;color:#cfd6e2}.tvp-volwrap,.tvp-projwrap{position:relative;display:inline-flex}.tvp-volpopup{position:absolute;bottom:calc(100% + 10px);left:50%;transform:translate(-50%);width:40px;height:132px;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:10px;z-index:8;box-shadow:0 8px 24px #0009}.tvp-volpopup[hidden]{display:none}.tvp-volume{position:absolute;top:50%;left:50%;width:104px;height:14px;margin:0;transform:translate(-50%,-50%) rotate(-90deg);-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;cursor:pointer}.tvp-volume::-webkit-slider-runnable-track{height:4px;border-radius:2px;background:#3a4150}.tvp-volume::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-top:-4px;width:12px;height:12px;border-radius:50%;background:#fff;cursor:pointer}.tvp-volume::-moz-range-track{height:4px;border-radius:2px;background:#3a4150}.tvp-volume::-moz-range-thumb{width:12px;height:12px;border:0;border-radius:50%;background:#fff;cursor:pointer}.tvp-projmenu{position:absolute;bottom:calc(100% + 8px);right:0;min-width:210px;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:10px;padding:6px;display:flex;flex-direction:column;gap:2px;z-index:8;box-shadow:0 8px 24px #0009}.tvp-projmenu[hidden]{display:none}.tvp-projmenu button{text-align:left;background:transparent;border:0;color:#e8eaed;padding:8px 10px;border-radius:7px;cursor:pointer;font:inherit;white-space:nowrap}.tvp-projmenu button:hover{background:#252b39}.tvp-projmenu button.active{background:#4f8cff;color:#fff}.tvp-vrslot button{position:static!important}.tvp-settings{position:absolute;bottom:62px;right:10px;width:300px;max-width:calc(100% - 20px);max-height:70%;overflow-y:auto;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:12px;padding:14px;display:none;flex-direction:column;gap:12px;z-index:6;font:14px system-ui,Segoe UI,Roboto,sans-serif;color:#e8eaed}.tvp-settings.open{display:flex}.tvp-settings label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:#aab2c0}.tvp-settings label.row{flex-direction:row;align-items:center;gap:8px;color:#e8eaed;font-size:13px}.tvp-settings input[type=range]{width:100%;accent-color:#4f8cff}.tvp-settings input[type=text],.tvp-settings input[type=password]{width:100%;padding:7px 9px;border-radius:7px;border:1px solid #333;background:#151821;color:#e8eaed;font:inherit}.tvp-sep{width:100%;border:0;border-top:1px solid #2a2f3a;margin:2px 0}.tvp-toast{position:absolute;left:50%;bottom:74px;transform:translate(-50%);max-width:80%;padding:10px 16px;border-radius:10px;background:#1b1f2aed;border:1px solid #2a2f3a;color:#e8eaed;opacity:0;pointer-events:none;transition:opacity .2s;z-index:7;font:13px system-ui}.tvp-toast.show{opacity:1}",hc="three-vr-player:settings";class uc{constructor(e,t={}){var r,a;this.source=new sc,this.listeners=new Map,this.readyEmitted=!1,this.native=!1,this.loading=!1,this.useProxy=!1,this.opts=t,this.proxyConfig=t.proxy,this.useProxy=!!t.proxy;const i=t.persistSettings?this.loadSettings():null;this.view={projection:t.projection??(i==null?void 0:i.projection)??"180-sbs",swapEyes:t.swapEyes??(i==null?void 0:i.swapEyes)??!1,fov:t.fov??(i==null?void 0:i.fov)??70,supersampling:t.supersampling??(i==null?void 0:i.supersampling)??1.5},this.wrap=document.createElement("div"),this.wrap.className="tvp",this.wrap.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;",e.appendChild(this.wrap);let n;if(t.shadowDom!==!1){const o=this.wrap.attachShadow({mode:"open"}),l=document.createElement("style");l.textContent=cc,o.appendChild(l),n=o}else{if(!document.getElementById("tvp-styles")){const o=document.createElement("style");o.id="tvp-styles",o.textContent=cc,document.head.appendChild(o)}n=this.wrap}this.canvas=document.createElement("canvas"),this.canvas.className="tvp-canvas",this.video=document.createElement("video"),this.video.className="tvp-video",this.video.playsInline=!0,t.crossOrigin!==null&&(this.video.crossOrigin=t.crossOrigin??"anonymous"),n.append(this.canvas,this.video),this.scene=new ec({canvas:this.canvas,video:this.video,projection:this.view.projection,swapEyes:this.view.swapEyes,fov:this.view.fov,supersampling:this.view.supersampling}),this.look=new nc(this.scene.camera,this.canvas,{isPresenting:()=>this.scene.renderer.xr.isPresenting}),this.scene.onFrame(()=>this.look.update()),this.look.setEnabled(!this.scene.isFlat()),t.controls!==!1&&(this.ui=new n0(n,{video:this.video,surface:this.canvas,fullscreenTarget:this.wrap,vrButton:this.scene.vrButton,vrSupported:()=>this.vrSupported(),getProjection:()=>this.scene.getProjection(),setProjection:o=>this.setProjection(o),setSwapEyes:o=>this.setSwapEyes(o),setFov:o=>this.setFov(o),setSupersampling:o=>this.setSupersampling(o),initial:{swapEyes:this.view.swapEyes,fov:this.view.fov,supersampling:this.view.supersampling},proxy:{url:((r=this.proxyConfig)==null?void 0:r.url)??"",apiPassword:((a=this.proxyConfig)==null?void 0:a.apiPassword)??"",enabled:this.useProxy},setProxy:o=>this.setProxy(o)})),this.video.addEventListener("play",()=>this.emit("play")),this.video.addEventListener("pause",()=>this.emit("pause")),this.video.addEventListener("ended",()=>this.emit("ended")),this.video.addEventListener("timeupdate",()=>this.emit("timeupdate",this.video.currentTime)),this.video.addEventListener("error",()=>{this.loading||this.emit("error",this.video.error)}),this.video.addEventListener("loadedmetadata",()=>{this.readyEmitted||(this.readyEmitted=!0,this.emit("ready"))}),this.scene.renderer.xr.addEventListener("sessionstart",()=>this.emit("enterxr")),this.scene.renderer.xr.addEventListener("sessionend",()=>this.emit("exitxr")),t.src&&this.load(t.src,{projection:t.projection})}vrSupported(){return this.opts.vrButton===!1||!navigator.xr?Promise.resolve(!1):navigator.xr.isSessionSupported("immersive-vr").catch(()=>!1)}async load(e,t={}){this.currentSrc=e;const i=t.projection??(this.opts.autoDetect!==!1?Jl(e):null);i&&this.setProjection(i);const{url:n,format:r}=ac(e,this.useProxy?this.proxyConfig:void 0),a=this.opts.crossOrigin===void 0?"anonymous":this.opts.crossOrigin;this.loading=!0;try{await this.source.attach(this.video,{url:n,format:r},{crossOrigin:a}),this.setNativeFallback(!1),await this.video.play().catch(()=>{})}catch(o){if(this.opts.nativeFallback!==!1&&r==="progressive"&&a!==null)try{this.setNativeFallback(!0),await this.source.attach(this.video,{url:n,format:r},{crossOrigin:null}),await this.video.play().catch(()=>{}),this.emit("fallback");return}catch(l){throw this.setNativeFallback(!1),this.emit("error",l),l}throw this.setNativeFallback(!1),this.emit("error",o),o}finally{this.loading=!1}}setNativeFallback(e){e!==this.native&&(this.native=e,e?(this.scene.pauseRendering(),this.canvas.style.display="none",Object.assign(this.video.style,{display:"block",position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",background:"#000",zIndex:"1"})):(this.canvas.style.display="",this.video.style.cssText="",this.scene.resumeRendering()))}async play(){await this.video.play()}pause(){this.video.pause()}setProjection(e){this.scene.setProjection(e),this.look.setEnabled(!this.scene.isFlat()),this.look.reset(),this.view.projection=e,this.persist(),this.emit("projectionchange",e)}setSwapEyes(e){this.scene.setSwapEyes(e),this.view.swapEyes=e,this.persist()}setFov(e){this.scene.setFov(e),this.view.fov=e,this.persist()}setSupersampling(e){this.scene.setSupersampling(e),this.view.supersampling=e,this.persist()}setProxy(e){this.proxyConfig=e.url?{url:e.url,apiPassword:e.apiPassword||void 0}:void 0,this.useProxy=e.enabled,this.currentSrc&&this.load(this.currentSrc)}async enterVR(){var t;const e=this.scene.vrButton;(t=e==null?void 0:e.click)==null||t.call(e)}get three(){return{renderer:this.scene.renderer,scene:this.scene.scene,camera:this.scene.camera}}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),this}off(e,t){var i;return(i=this.listeners.get(e))==null||i.delete(t),this}emit(e,t){var i;(i=this.listeners.get(e))==null||i.forEach(n=>n(t))}persist(){if(this.opts.persistSettings)try{localStorage.setItem(hc,JSON.stringify(this.view))}catch{}}loadSettings(){try{const e=localStorage.getItem(hc);return e?JSON.parse(e):null}catch{return null}}dispose(){var e;(e=this.ui)==null||e.dispose(),this.look.dispose(),this.source.dispose(),this.scene.dispose(),this.video.remove(),this.canvas.remove(),this.wrap.remove(),this.listeners.clear()}}class dc extends HTMLElement{static get observedAttributes(){return["src","projection"]}connectedCallback(){this.player||(this.style.display||(this.style.display="block"),this.player=new uc(this,{src:this.getAttribute("src")??void 0,projection:this.getAttribute("projection")??void 0,controls:this.hasAttribute("controls"),swapEyes:this.hasAttribute("swap-eyes"),autoDetect:this.getAttribute("auto-detect")!=="false",fov:this.numAttr("fov"),supersampling:this.numAttr("supersampling"),proxy:this.getAttribute("proxy-url")?{url:this.getAttribute("proxy-url"),apiPassword:this.getAttribute("proxy-password")??void 0}:void 0}))}attributeChangedCallback(e,t,i){!this.player||i==null||(e==="src"&&this.player.load(i),e==="projection"&&this.player.setProjection(i))}disconnectedCallback(){var e;(e=this.player)==null||e.dispose(),this.player=void 0}numAttr(e){const t=this.getAttribute(e);return t==null?void 0:Number(t)}get api(){return this.player}}function fc(s="three-video"){typeof customElements<"u"&&!customElements.get(s)&&customElements.define(s,dc)}fc();const de=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},s0=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=r0},r0=Number.MAX_SAFE_INTEGER||9007199254740991;let Ee=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),H=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),x=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var Ye={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ge={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Hn{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class a0{constructor(e,t,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Hn(e),this.fast_=new Hn(t),this.defaultTTFB_=n,this.ttfb_=new Hn(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Hn(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Hn(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Hn(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function o0(s,e,t){return(e=c0(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function at(){return at=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},at.apply(null,arguments)}function pc(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function et(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?pc(Object(t),!0).forEach(function(i){o0(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):pc(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function l0(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function c0(s){var e=l0(s,"string");return typeof e=="symbol"?e:e+""}class li{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=Qi,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const Qi=function(){},h0={trace:Qi,debug:Qi,log:Qi,warn:Qi,info:Qi,error:Qi};function Ma(){return at({},h0)}function u0(s,e){const t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):Qi}function mc(s,e,t){return e[s]?e[s].bind(e):u0(s,t)}const La=Ma();function d0(s,e,t){const i=Ma();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=mc(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return Ma()}n.forEach(r=>{La[r]=mc(r,s)})}else at(La,i);return i}const tt=La;function Ni(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function f0(s){return typeof self<"u"&&s===self.ManagedMediaSource}function gc(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(a=>i.indexOf(a)===-1)}function ti(s,e=!1){if(typeof TextDecoder<"u"){const c=new TextDecoder("utf-8").decode(s);if(e){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const t=s.length;let i,n,r,a="",o=0;for(;o<t;){if(i=s[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=s[o++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[o++],r=s[o++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return a}function Ut(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function vc(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function p0(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ia={exports:{}},_c;function m0(){return _c||(_c=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var p=n.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var v={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(v.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)v.path=f.path,d.params||(v.params=f.params,d.query||(v.query=f.query));else{var m=f.path,g=m.substring(0,m.lastIndexOf("/")+1)+d.path;v.path=o.normalizePath(g)}return v.path===null&&(v.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(v)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()}(Ia)),Ia.exports}var Ca=m0();class ar{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ot={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class wa{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,g0(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let n;i.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(i[1]),this._byteRange=[n,parseInt(i[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ot.AUDIO]:null,[ot.VIDEO]:null,[ot.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ar),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ca.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ot.AUDIO]=null,e[ot.VIDEO]=null,e[ot.AUDIOVIDEO]=null}}function Et(s){return s.sn!=="initSegment"}class or extends wa{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(de(e)&&de(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const i=Object.keys(t);if(i.length===1){const n=this._decryptdata=t[i[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=de(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),n=i.length;if(n>1||n===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!de(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,n),l.endDTS=Math.max(l.endDTS,r)}}class Ec extends wa{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function xc(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||xc(t,e)}}function g0(s,e){const t=xc(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const Sc=Math.pow(2,32)-1,v0=[].push,yc={video:1,audio:2,id3:3,text:4};function At(s){return String.fromCharCode.apply(null,s)}function Tc(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function De(s,e){const t=bc(s,e);return t<0?4294967296+t:t}function Ac(s,e){let t=De(s,e);return t*=Math.pow(2,32),t+=De(s,e+4),t}function bc(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function _0(s){const e=s.byteLength;for(let t=0;t<e;){const i=De(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function We(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n<i;){const r=De(s,n),a=At(s.subarray(n+4,n+8)),o=r>1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,o));else{const l=We(s.subarray(n+8,o),e.slice(1));l.length&&v0.apply(t,l)}n=o}return t}function E0(s){const e=[],t=s[0];let i=8;const n=De(s,i);i+=4;let r=0,a=0;t===0?(r=De(s,i),a=De(s,i+4),i+=8):(r=Ac(s,i),a=Ac(s,i+8),i+=16),i+=2;let o=s.length+a;const l=Tc(s,i);i+=2;for(let c=0;c<l;c++){let h=i;const u=De(s,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return tt.warn("SIDX has hierarchical references (not supported)"),null;const p=De(s,h);h+=4,e.push({referenceSize:d,subsegmentDuration:p,info:{duration:p/n,start:o,end:o+d-1}}),o+=d,h+=4,i=h}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:l,references:e}}function Rc(s){const e=[],t=We(s,["moov","trak"]);for(let n=0;n<t.length;n++){const r=t[n],a=We(r,["tkhd"])[0];if(a){let o=a[0];const l=De(a,o===0?12:20),c=We(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=De(c,o===0?12:20),u=We(r,["mdia","hdlr"])[0];if(u){const d=At(u.subarray(8,12)),f={soun:ot.AUDIO,vide:ot.VIDEO}[d],p=We(r,["mdia","minf","stbl","stsd"])[0],v=x0(p);f?(e[l]={timescale:h,type:f,stsd:v},e[f]=et({timescale:h,id:l},v)):e[l]={timescale:h,type:d,stsd:v}}}}}return We(s,["moov","mvex","trex"]).forEach(n=>{const r=De(n,4),a=e[r];a&&(a.default={duration:De(n,12),flags:De(n,20)})}),e}function x0(s){const e=s.subarray(8),t=e.subarray(86),i=At(e.subarray(4,8));let n=i,r;const a=i==="enca"||i==="encv";if(a){const c=We(e,[i])[0].subarray(i==="enca"?28:78);We(c,["sinf"]).forEach(u=>{const d=We(u,["schm"])[0];if(d){const f=At(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const p=We(u,["frma"])[0];p&&(n=At(p))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const l=We(t,["avcC"])[0];l&&l.length>3&&(n+="."+cr(l[1])+cr(l[2])+cr(l[3]),r=lr(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=We(e,[i])[0],c=We(l.subarray(28),["esds"])[0];if(c&&c.length>7){let h=4;if(c[h++]!==3)break;h=Da(c,h),h+=2;const u=c[h++];if(u&128&&(h+=2),u&64&&(h+=c[h++]),c[h++]!==4)break;h=Da(c,h);const d=c[h++];if(d===64)n+="."+cr(d);else break;if(h+=12,c[h++]!==5)break;h=Da(c,h);const f=c[h++];let p=(f&248)>>3;p===31&&(p+=1+((f&7)<<3)+((c[h]&224)>>5)),n+="."+p}break}case"hvc1":case"hev1":{const l=We(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],h=["","A","B","C"][c>>6],u=c&31,d=De(l,2),f=(c&32)>>5?"H":"L",p=l[12],v=l.subarray(6,12);n+="."+h+u,n+="."+S0(d).toString(16).toUpperCase(),n+="."+f+p;let m="";for(let g=v.length;g--;){const E=v[g];(E||m)&&(m="."+E.toString(16).toUpperCase()+m)}n+=m}r=lr(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=lr(n,t)||n;break}case"vp09":{const l=We(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],h=l[5],u=l[6]>>4&15;n+="."+yi(c)+"."+yi(h)+"."+yi(u)}break}case"av01":{const l=We(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,h=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,p=c===2&&d?f?12:10:d?10:8,v=(l[2]&16)>>4,m=(l[2]&8)>>3,g=(l[2]&4)>>2,E=l[2]&3;n+="."+c+"."+yi(h)+u+"."+yi(p)+"."+v+"."+m+g+E+"."+yi(1)+"."+yi(1)+"."+yi(1)+"."+0,r=lr("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function lr(s,e){const t=We(e,["dvvC"]),i=t.length?t[0]:We(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+yi(n)+"."+yi(r)}}function S0(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Da(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function cr(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function yi(s){return(s<10?"0":"")+s}function y0(s,e){if(!s||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Mc(s,(i,n)=>{const r=i.subarray(8,24);r.some(a=>a!==0)||(tt.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Ut(r)} -> ${Ut(t)}`),i.set(t,8))})}function T0(s){const e=[];return Mc(s,t=>e.push(t.subarray(8,24))),e}function Mc(s,e){We(s,["moov","trak"]).forEach(i=>{const n=We(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let a=We(r,["enca"]);const o=a.length>0;o||(a=We(r,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);We(c,["sinf"]).forEach(u=>{const d=Lc(u);d&&e(d,o)})})})}function Lc(s){const e=We(s,["schm"])[0];if(e){const t=At(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=We(s,["schi","tenc"])[0];if(i)return i}}}function A0(s,e,t){const i={},n=We(s,["moof","traf"]);for(let r=0;r<n.length;r++){const a=n[r],o=We(a,["tfhd"])[0],l=De(o,4),c=e[l];if(!c)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const h=i[l],u=We(a,["tfdt"])[0];if(u){const _=u[0];let T=De(u,4);_===1&&(T===Sc?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Sc+1,T+=De(u,8))),de(T)&&(!de(h.start)||T<h.start)&&(h.start=T)}const d=c.default,f=De(o,0)|(d==null?void 0:d.flags);let p=(d==null?void 0:d.duration)||0;f&8&&(f&2?p=De(o,12):p=De(o,8));const v=We(a,["trun"]);let m=h.start||0,g=0,E=p;for(let _=0;_<v.length;_++){const T=v[_],b=De(T,4),R=h.sampleCount;h.sampleCount+=b;const A=T[3]&1,C=T[3]&4,S=T[2]&1,y=T[2]&2,w=T[2]&4,U=T[2]&8;let X=8,P=b;for(A&&(X+=4),C&&b&&(!(T[X+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=R),X+=4,S?(E=De(T,X),X+=4):E=p,y&&(X+=4),U&&(X+=4),m+=E,g+=E,P--);P--;)S?(E=De(T,X),X+=4):E=p,y&&(X+=4),w&&(T[X+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(P+1),h.keyFrameStart=m),X+=4),U&&(X+=4),m+=E,g+=E;!g&&p&&(g+=p*b)}h.duration+=g}if(!Object.keys(i).some(r=>i[r].duration)){let r=1/0,a=0;const o=We(s,["sidx"]);for(let l=0;l<o.length;l++){const c=E0(o[l]);if(c!=null&&c.references){r=Math.min(r,c.earliestPresentationTime/c.timescale);const h=c.references.reduce((u,d)=>u+d.info.duration||0,0);a=Math.max(a,h+c.earliestPresentationTime/c.timescale)}}a&&de(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start)})}return i}function b0(s){const e={valid:null,remainder:null},t=We(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function ci(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Ic(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return We(i,["moof"]).map(l=>{const c=l.byteOffset-8;We(l,["traf"]).map(u=>{const d=We(u,["tfdt"]).map(f=>{const p=f[0];let v=De(f,4);return p===1&&(v*=Math.pow(2,32),v+=De(f,8)),v/n})[0];return d!==void 0&&(s=d),We(u,["tfhd"]).map(f=>{const p=De(f,4),v=De(f,0)&16777215,m=(v&1)!==0,g=(v&2)!==0,E=(v&8)!==0;let _=0;const T=(v&16)!==0;let b=0;const R=(v&32)!==0;let A=8;p===r&&(m&&(A+=8),g&&(A+=4),E&&(_=De(f,A),A+=4),T&&(b=De(f,A),A+=4),R&&(A+=4),e.type==="video"&&(a=hr(e.codec)),We(u,["trun"]).map(C=>{const S=C[0],y=De(C,0)&16777215,w=(y&1)!==0;let U=0;const X=(y&4)!==0,P=(y&256)!==0;let F=0;const D=(y&512)!==0;let k=0;const N=(y&1024)!==0,B=(y&2048)!==0;let q=0;const V=De(C,4);let W=8;w&&(U=De(C,W),W+=4),X&&(W+=4);let $=U+c;for(let ee=0;ee<V;ee++){if(P?(F=De(C,W),W+=4):F=_,D?(k=De(C,W),W+=4):k=b,N&&(W+=4),B&&(S===0?q=De(C,W):q=bc(C,W),W+=4),e.type===ot.VIDEO){let ie=0;for(;ie<k;){const oe=De(i,$);if($+=4,R0(a,i[$])){const me=i.subarray($,$+oe);Pa(me,a?2:1,s+q/n,t)}$+=oe,ie+=oe+4}}s+=F/n}}))})})}),t}function hr(s){if(!s)return!1;const e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function R0(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Pa(s,e,t,i){const n=Cc(s);let r=0;r+=e;let a=0,o=0,l=0;for(;r<n.length;){a=0;do{if(r>=n.length)break;l=n[r++],a+=l}while(l===255);o=0;do{if(r>=n.length)break;l=n[r++],o+=l}while(l===255);const c=n.length-r;let h=r;if(o<c)r+=o;else if(o>c){tt.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(n[h++]===181){const d=Tc(n,h);if(h+=2,d===49){const f=De(n,h);if(h+=4,f===1195456820){const p=n[h++];if(p===3){const v=n[h++],m=31&v,g=64&v,E=g?2+m*3:0,_=new Uint8Array(E);if(g){_[0]=v;for(let T=1;T<E;T++)_[T]=n[h++]}i.push({type:p,payloadType:a,pts:t,bytes:_})}}}}}else if(a===5&&o>16){const u=[];for(let p=0;p<16;p++){const v=n[h++].toString(16);u.push(v.length==1?"0"+v:v),(p===3||p===5||p===7||p===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=n[h++];i.push({payloadType:a,pts:t,uuid:u.join(""),userData:ti(f),userDataBytes:f})}}}function Cc(s){const e=s.byteLength,t=[];let i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;const n=e-t.length,r=new Uint8Array(n);let a=0;for(i=0;i<n;a++,i++)a===t[0]&&(a++,t.shift()),r[i]=s[a];return r}function M0(s){const e=s[0];let t="",i="",n=0,r=0,a=0,o=0,l=0,c=0;if(e===0){for(;At(s.subarray(c,c+1))!=="\0";)t+=At(s.subarray(c,c+1)),c+=1;for(t+=At(s.subarray(c,c+1)),c+=1;At(s.subarray(c,c+1))!=="\0";)i+=At(s.subarray(c,c+1)),c+=1;i+=At(s.subarray(c,c+1)),c+=1,n=De(s,12),r=De(s,16),o=De(s,20),l=De(s,24),c=28}else if(e===1){c+=4,n=De(s,c),c+=4;const u=De(s,c);c+=4;const d=De(s,c);for(c+=4,a=4294967296*u+d,s0(a)||(a=Number.MAX_SAFE_INTEGER,tt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=De(s,c),c+=4,l=De(s,c),c+=4;At(s.subarray(c,c+1))!=="\0";)t+=At(s.subarray(c,c+1)),c+=1;for(t+=At(s.subarray(c,c+1)),c+=1;At(s.subarray(c,c+1))!=="\0";)i+=At(s.subarray(c,c+1)),c+=1;i+=At(s.subarray(c,c+1)),c+=1}const h=s.subarray(c,s.byteLength);return{schemeIdUri:t,value:i,timeScale:n,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function L0(s,...e){const t=e.length;let i=8,n=t;for(;n--;)i+=e[n].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n<t;n++)r.set(e[n],i),i+=e[n].byteLength;return r}function I0(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,n;i=0,n=new Uint8Array;let r;i>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),L0([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t)}function C0(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32<t;){const n=new DataView(s,i),r=w0(n);e.push(r),i+=r.size}}return e}function w0(s){const e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return{offset:t,size:i};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};const r=s.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=s.buffer,o=Ut(new Uint8Array(a,t+12,16));let l=null,c=null,h=0;if(r===0)h=28;else{const d=s.getUint32(28);if(!d||i<32+d*16)return{offset:t,size:e};l=[];for(let f=0;f<d;f++)l.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=s.getUint32(h);return e-32<u?{offset:t,size:e}:(c=new Uint8Array(a,t+h+4,u),{version:r,systemId:o,kids:l,data:c,offset:t,size:e})}const wc=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),$n={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Fa(s,e){const t=$n[e];return!!t&&!!t[s.slice(0,4)]}function fs(s,e,t=!0){return!s.split(",").some(i=>!Oa(i,e,t))}function Oa(s,e,t=!0){var i;const n=Ni(t);return(i=n==null?void 0:n.isTypeSupported(ps(s,e)))!=null?i:!1}function ps(s,e){return`${e}/mp4;codecs=${s}`}function Dc(s){if(s){const e=s.substring(0,4);return $n.video[e]}return 2}function ur(s){const e=wc();return s.split(",").reduce((t,i)=>{const r=e&&hr(i)?9:$n.video[i];return r?(r*2+t)/(t?3:2):($n.audio[i]+t)/(t?2:1)},0)}const Ua={};function D0(s,e=!0){if(Ua[s])return Ua[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;n<t.length;n++){var i;if(Oa(t[n],"audio",e))return Ua[s]=t[n],t[n];if(t[n]==="mp3"&&(i=Ni(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return s}const P0=/flac|opus|mp4a\.40\.34/i;function dr(s,e=!0){return s.replace(P0,t=>D0(t.toLowerCase(),e))}function F0(s,e){const t=[];if(s){const i=s.split(",");for(let n=0;n<i.length;n++)Fa(i[n],"video")||t.push(i[n])}return e&&t.push(e),t.join(",")}function fr(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(Pc(s,"audio")||Pc(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function Pc(s,e){return Fa(s,e)&&Oa(s,e)}function O0(s){const e=s.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function U0(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function Fc(s){const e=Ni(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Na(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const N0={supported:!0,powerEfficient:!0,smooth:!0},k0={supported:!1,smooth:!1,powerEfficient:!1},Oc={supported:!0,configurations:[],decodingInfoResults:[N0]};function Uc(s,e){return{supported:!1,configurations:e,decodingInfoResults:[k0],error:s}}function B0(s,e,t,i,n,r){const a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=r==null?void 0:r.audioCodec,c=r==null?void 0:r.channels,h=c?parseInt(c):l?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const p=e.groups[f];if(!p)throw new Error(`Audio track group ${f} not found`);Object.keys(p.channels).forEach(v=>{d[v]=(d[v]||0)+p.channels[v]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>hr(d))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!u&&de(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Nc(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(Oc);const r=[],a=G0(s),o=a.length,l=V0(s,e,o>0),c=l.length;for(let h=o||1*c||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),c){u.audio=l[h%c];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(n){const h=navigator.userAgent;if(n.split(",").some(u=>hr(u))&&wc())return Promise.resolve(Uc(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=$0(h);return i[u]||(i[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function G0(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=kc(s),n=s.width||640,r=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:ps(U0(l),"video"),width:n,height:r,bitrate:i,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function V0(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=kc(s);return n&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");n.forEach(f=>{const p={contentType:ps(f,"audio"),bitrate:t?H0(f,r):r};d&&(p.channels=""+d),h.push(p)})}return h},a):a},[]):[]}function H0(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function kc(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function $0(s){let e="";const{audio:t,video:i}=s;if(i){const n=Na(i.contentType);e+=`${n}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const n=Na(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const ka=["NONE","TYPE-0","TYPE-1",null];function z0(s){return ka.indexOf(s)>-1}const pr=["SDR","PQ","HLG"];function W0(s){return!!s&&pr.indexOf(s)>-1}var ms={No:"",Yes:"YES",v2:"v2"};function Bc(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i<e/2;return e&&n?t?ms.v2:ms.Yes:ms.No}class Ba{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class zn{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Gc(this._audioGroups,e)}hasSubtitleGroup(e){return Gc(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Gc(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function K0(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function X0(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||pr.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&K0(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const Y0=s=>{const e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},lt=(s,e)=>JSON.stringify(s,Y0(e));function q0(s,e,t,i,n){const r=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=n==null?void 0:n.videoCodec,c=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,p=1/0,v=1/0,m=0,g=[];const{preferHDR:E,allowedVideoRanges:_}=X0(e,n);for(let C=r.length;C--;){const S=s[r[C]];h||(h=S.channels[2]>0),d=Math.min(d,S.minHeight),f=Math.min(f,S.minFramerate),p=Math.min(p,S.minBitrate),_.filter(w=>S.videoRanges[w]>0).length>0&&(u=!0)}d=de(d)?d:0,f=de(f)?f:0;const T=Math.max(1080,d),b=Math.max(30,f);p=de(p)?p:t,t=Math.max(p,t),u||(e=void 0);const R=r.length>1;return{codecSet:r.reduce((C,S)=>{const y=s[S];if(S===C)return C;if(g=u?_.filter(w=>y.videoRanges[w]>0):[],R){if(y.minBitrate>t)return Ti(S,`min bitrate of ${y.minBitrate} > current estimate of ${t}`),C;if(!y.hasDefaultAudio)return Ti(S,"no renditions with default or auto-select sound found"),C;if(o&&S.indexOf(o.substring(0,4))%5!==0)return Ti(S,`audio codec preference "${o}" not found`),C;if(a&&!c){if(!y.channels[a])return Ti(S,`no renditions with ${a} channel sound found (channels options: ${Object.keys(y.channels)})`),C}else if((!o||c)&&h&&y.channels[2]===0)return Ti(S,"no renditions with stereo sound found"),C;if(y.minHeight>T)return Ti(S,`min resolution of ${y.minHeight} > maximum of ${T}`),C;if(y.minFramerate>b)return Ti(S,`min framerate of ${y.minFramerate} > maximum of ${b}`),C;if(!g.some(w=>y.videoRanges[w]>0))return Ti(S,`no variants with VIDEO-RANGE of ${lt(g)} found`),C;if(l&&S.indexOf(l.substring(0,4))%5!==0)return Ti(S,`video codec preference "${l}" not found`),C;if(y.maxScore<m)return Ti(S,`max score of ${y.maxScore} < selected max of ${m}`),C}return C&&(ur(S)>=ur(C)||y.fragmentError>s[C].fragmentError)?C:(v=y.minIndex,m=y.maxScore,S)},void 0),videoRanges:g,preferHDR:E,minFramerate:f,minBitrate:p,minIndex:v}}function Ti(s,e){tt.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Vc(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const n=t.channels||"2";return i.channels[n]=(i.channels[n]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function j0(s,e,t,i){return s.slice(t,i+1).reduce((n,r,a)=>{if(!r.codecSet)return n;const o=r.audioGroups;let l=n[r.codecSet];l||(n[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const c=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),n},{})}function Hc(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}=s;return{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}}function Ai(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){const n=e[i];if(dn(s,n,t))return i}return-1}function dn(s,e,t){const{groupId:i,name:n,lang:r,assocLang:a,default:o}=s,l=s.forced;return(i===void 0||e.groupId===i)&&(n===void 0||e.name===n)&&(r===void 0||Q0(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||Z0(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function Q0(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function Z0(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(n=>i.indexOf(n)===-1)}function fn(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function J0(s,e,t,i,n){const r=e[i],o=e.reduce((d,f,p)=>{const v=f.uri;return(d[v]||(d[v]=[])).push(p),d},{})[r.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=$c(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,p=t.filter(v=>!f||f.indexOf(v.groupId)!==-1);return Ai(s,p,n)>-1});return u>-1?u:$c(e,i,d=>{const f=d.audioGroups,p=t.filter(v=>!f||f.indexOf(v.groupId)!==-1);return Ai(s,p,n)>-1})}function $c(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}function mr(s,e){var t;return!!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}class zc extends li{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:n,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!n||!l)return;const c=performance.now(),h=r?r.stats:n.stats,u=r?r.duration:n.duration,d=c-h.loading.start,f=a.minAutoLevel,p=n.level,v=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||p<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=v>-1&&v!==p,g=!!t||m;if(!g&&(l.paused||!l.playbackRate||!l.readyState))return;const E=a.mainForwardBufferInfo;if(!g&&E===null)return;const _=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(d<=Math.max(_,1e3*(u/(T*2))))return;const b=E?E.len/T:0,R=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&R>-1,C=this.getBwEstimate(),S=a.levels,y=S[p],w=Math.max(h.loaded,Math.round(u*(n.bitrate||y.averageBitrate)/8));let U=A?d-R:d;U<1&&A&&(U=Math.min(d,h.loaded*8/C));const X=A?h.loaded*1e3/U:0,P=_/1e3,F=X?(w-h.loaded)/X:w*8/C+P;if(F<=b)return;const D=X?X*8:C,k=((i=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let B=Number.POSITIVE_INFINITY,q;for(q=p-1;q>f;q--){const ee=S[q].maxBitrate,ie=!S[q].details||k;if(B=this.getTimeToLoadFrag(P,D,u*ee,ie),B<Math.min(b,u+P))break}if(B>=F||B>u*10)return;A?this.bwEstimator.sample(d-Math.min(_,R),h.loaded):this.bwEstimator.sampleTTFB(d);const V=S[q].maxBitrate;this.getBwEstimate()*N>V&&this.resetEstimator(V);const W=this.findBestLevel(V,f,q,0,b,1,1);W>-1&&(q=W),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${p} is loading too slowly;
|
|
3686
|
+
}`;function $g(s,e,t){let i=new Sl;const n=new nt,r=new nt,a=new Ft,o=new Bg({depthPacking:3201}),l=new Gg,c={},h=t.maxTextureSize,u={0:1,1:0,2:2},d=new on({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new nt},radius:{value:4}},vertexShader:Vg,fragmentShader:Hg}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new ji;p.setAttribute("position",new Ei(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new mi(p,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let g=this.type;this.render=function(R,A,C){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||R.length===0)return;const S=s.getRenderTarget(),y=s.getActiveCubeFace(),w=s.getActiveMipmapLevel(),N=s.state;N.setBlending(0),N.buffers.color.setClear(1,1,1,1),N.buffers.depth.setTest(!0),N.setScissorTest(!1);const Y=g!==3&&this.type===3,D=g===3&&this.type!==3;for(let F=0,O=R.length;F<O;F++){const $=R[F],k=$.shadow;if(k===void 0){console.warn("THREE.WebGLShadowMap:",$,"has no shadow.");continue}if(k.autoUpdate===!1&&k.needsUpdate===!1)continue;n.copy(k.mapSize);const B=k.getFrameExtents();if(n.multiply(B),r.copy(k.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(r.x=Math.floor(h/B.x),n.x=r.x*B.x,k.mapSize.x=r.x),n.y>h&&(r.y=Math.floor(h/B.y),n.y=r.y*B.y,k.mapSize.y=r.y)),k.map===null||Y===!0||D===!0){const P=this.type!==3?{minFilter:1003,magFilter:1003}:{};k.map!==null&&k.map.dispose(),k.map=new nn(n.x,n.y,P),k.map.texture.name=$.name+".shadowMap",k.camera.updateProjectionMatrix()}s.setRenderTarget(k.map),s.clear();const X=k.getViewportCount();for(let P=0;P<X;P++){const V=k.getViewport(P);a.set(r.x*V.x,r.y*V.y,r.x*V.z,r.y*V.w),N.viewport(a),k.updateMatrices($,P),i=k.getFrustum(),T(A,C,k.camera,$,this.type)}k.isPointLightShadow!==!0&&this.type===3&&E(k,C),k.needsUpdate=!1}g=this.type,m.needsUpdate=!1,s.setRenderTarget(S,y,w)};function E(R,A){const C=e.update(v);d.defines.VSM_SAMPLES!==R.blurSamples&&(d.defines.VSM_SAMPLES=R.blurSamples,f.defines.VSM_SAMPLES=R.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),R.mapPass===null&&(R.mapPass=new nn(n.x,n.y)),d.uniforms.shadow_pass.value=R.map.texture,d.uniforms.resolution.value=R.mapSize,d.uniforms.radius.value=R.radius,s.setRenderTarget(R.mapPass),s.clear(),s.renderBufferDirect(A,null,C,d,v,null),f.uniforms.shadow_pass.value=R.mapPass.texture,f.uniforms.resolution.value=R.mapSize,f.uniforms.radius.value=R.radius,s.setRenderTarget(R.map),s.clear(),s.renderBufferDirect(A,null,C,f,v,null)}function _(R,A,C,S){let y=null;const w=C.isPointLight===!0?R.customDistanceMaterial:R.customDepthMaterial;if(w!==void 0)y=w;else if(y=C.isPointLight===!0?l:o,s.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0){const N=y.uuid,Y=A.uuid;let D=c[N];D===void 0&&(D={},c[N]=D);let F=D[Y];F===void 0&&(F=y.clone(),D[Y]=F,A.addEventListener("dispose",b)),y=F}if(y.visible=A.visible,y.wireframe=A.wireframe,S===3?y.side=A.shadowSide!==null?A.shadowSide:A.side:y.side=A.shadowSide!==null?A.shadowSide:u[A.side],y.alphaMap=A.alphaMap,y.alphaTest=A.alphaTest,y.map=A.map,y.clipShadows=A.clipShadows,y.clippingPlanes=A.clippingPlanes,y.clipIntersection=A.clipIntersection,y.displacementMap=A.displacementMap,y.displacementScale=A.displacementScale,y.displacementBias=A.displacementBias,y.wireframeLinewidth=A.wireframeLinewidth,y.linewidth=A.linewidth,C.isPointLight===!0&&y.isMeshDistanceMaterial===!0){const N=s.properties.get(y);N.light=C}return y}function T(R,A,C,S,y){if(R.visible===!1)return;if(R.layers.test(A.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&y===3)&&(!R.frustumCulled||i.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,R.matrixWorld);const Y=e.update(R),D=R.material;if(Array.isArray(D)){const F=Y.groups;for(let O=0,$=F.length;O<$;O++){const k=F[O],B=D[k.materialIndex];if(B&&B.visible){const X=_(R,B,S,y);R.onBeforeShadow(s,R,A,C,Y,X,k),s.renderBufferDirect(C,null,Y,X,R,k),R.onAfterShadow(s,R,A,C,Y,X,k)}}}else if(D.visible){const F=_(R,D,S,y);R.onBeforeShadow(s,R,A,C,Y,F,null),s.renderBufferDirect(C,null,Y,F,R,null),R.onAfterShadow(s,R,A,C,Y,F,null)}}const N=R.children;for(let Y=0,D=N.length;Y<D;Y++)T(N[Y],A,C,S,y)}function b(R){R.target.removeEventListener("dispose",b);for(const C in c){const S=c[C],y=R.target.uuid;y in S&&(S[y].dispose(),delete S[y])}}}function zg(s,e,t){const i=t.isWebGL2;function n(){let U=!1;const fe=new Ft;let pe=null;const Pe=new Ft(0,0,0,0);return{setMask:function(Ce){pe!==Ce&&!U&&(s.colorMask(Ce,Ce,Ce,Ce),pe=Ce)},setLocked:function(Ce){U=Ce},setClear:function(Ce,ct,ht,Dt,$t){$t===!0&&(Ce*=Dt,ct*=Dt,ht*=Dt),fe.set(Ce,ct,ht,Dt),Pe.equals(fe)===!1&&(s.clearColor(Ce,ct,ht,Dt),Pe.copy(fe))},reset:function(){U=!1,pe=null,Pe.set(-1,0,0,0)}}}function r(){let U=!1,fe=null,pe=null,Pe=null;return{setTest:function(Ce){Ce?be(s.DEPTH_TEST):Te(s.DEPTH_TEST)},setMask:function(Ce){fe!==Ce&&!U&&(s.depthMask(Ce),fe=Ce)},setFunc:function(Ce){if(pe!==Ce){switch(Ce){case 0:s.depthFunc(s.NEVER);break;case 1:s.depthFunc(s.ALWAYS);break;case 2:s.depthFunc(s.LESS);break;case 3:s.depthFunc(s.LEQUAL);break;case 4:s.depthFunc(s.EQUAL);break;case 5:s.depthFunc(s.GEQUAL);break;case 6:s.depthFunc(s.GREATER);break;case 7:s.depthFunc(s.NOTEQUAL);break;default:s.depthFunc(s.LEQUAL)}pe=Ce}},setLocked:function(Ce){U=Ce},setClear:function(Ce){Pe!==Ce&&(s.clearDepth(Ce),Pe=Ce)},reset:function(){U=!1,fe=null,pe=null,Pe=null}}}function a(){let U=!1,fe=null,pe=null,Pe=null,Ce=null,ct=null,ht=null,Dt=null,$t=null;return{setTest:function(ut){U||(ut?be(s.STENCIL_TEST):Te(s.STENCIL_TEST))},setMask:function(ut){fe!==ut&&!U&&(s.stencilMask(ut),fe=ut)},setFunc:function(ut,zt,Ii){(pe!==ut||Pe!==zt||Ce!==Ii)&&(s.stencilFunc(ut,zt,Ii),pe=ut,Pe=zt,Ce=Ii)},setOp:function(ut,zt,Ii){(ct!==ut||ht!==zt||Dt!==Ii)&&(s.stencilOp(ut,zt,Ii),ct=ut,ht=zt,Dt=Ii)},setLocked:function(ut){U=ut},setClear:function(ut){$t!==ut&&(s.clearStencil(ut),$t=ut)},reset:function(){U=!1,fe=null,pe=null,Pe=null,Ce=null,ct=null,ht=null,Dt=null,$t=null}}}const o=new n,l=new r,c=new a,h=new WeakMap,u=new WeakMap;let d={},f={},p=new WeakMap,v=[],m=null,g=!1,E=null,_=null,T=null,b=null,R=null,A=null,C=null,S=new rt(0,0,0),y=0,w=!1,N=null,Y=null,D=null,F=null,O=null;const $=s.getParameter(s.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let k=!1,B=0;const X=s.getParameter(s.VERSION);X.indexOf("WebGL")!==-1?(B=parseFloat(/^WebGL (\d)/.exec(X)[1]),k=B>=1):X.indexOf("OpenGL ES")!==-1&&(B=parseFloat(/^OpenGL ES (\d)/.exec(X)[1]),k=B>=2);let P=null,V={};const G=s.getParameter(s.SCISSOR_BOX),J=s.getParameter(s.VIEWPORT),ie=new Ft().fromArray(G),oe=new Ft().fromArray(J);function me(U,fe,pe,Pe){const Ce=new Uint8Array(4),ct=s.createTexture();s.bindTexture(U,ct),s.texParameteri(U,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(U,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let ht=0;ht<pe;ht++)i&&(U===s.TEXTURE_3D||U===s.TEXTURE_2D_ARRAY)?s.texImage3D(fe,0,s.RGBA,1,1,Pe,0,s.RGBA,s.UNSIGNED_BYTE,Ce):s.texImage2D(fe+ht,0,s.RGBA,1,1,0,s.RGBA,s.UNSIGNED_BYTE,Ce);return ct}const Se={};Se[s.TEXTURE_2D]=me(s.TEXTURE_2D,s.TEXTURE_2D,1),Se[s.TEXTURE_CUBE_MAP]=me(s.TEXTURE_CUBE_MAP,s.TEXTURE_CUBE_MAP_POSITIVE_X,6),i&&(Se[s.TEXTURE_2D_ARRAY]=me(s.TEXTURE_2D_ARRAY,s.TEXTURE_2D_ARRAY,1,1),Se[s.TEXTURE_3D]=me(s.TEXTURE_3D,s.TEXTURE_3D,1,1)),o.setClear(0,0,0,1),l.setClear(1),c.setClear(0),be(s.DEPTH_TEST),l.setFunc(3),Me(!1),I(1),be(s.CULL_FACE),le(0);function be(U){d[U]!==!0&&(s.enable(U),d[U]=!0)}function Te(U){d[U]!==!1&&(s.disable(U),d[U]=!1)}function Ge(U,fe){return f[U]!==fe?(s.bindFramebuffer(U,fe),f[U]=fe,i&&(U===s.DRAW_FRAMEBUFFER&&(f[s.FRAMEBUFFER]=fe),U===s.FRAMEBUFFER&&(f[s.DRAW_FRAMEBUFFER]=fe)),!0):!1}function q(U,fe){let pe=v,Pe=!1;if(U)if(pe=p.get(fe),pe===void 0&&(pe=[],p.set(fe,pe)),U.isWebGLMultipleRenderTargets){const Ce=U.texture;if(pe.length!==Ce.length||pe[0]!==s.COLOR_ATTACHMENT0){for(let ct=0,ht=Ce.length;ct<ht;ct++)pe[ct]=s.COLOR_ATTACHMENT0+ct;pe.length=Ce.length,Pe=!0}}else pe[0]!==s.COLOR_ATTACHMENT0&&(pe[0]=s.COLOR_ATTACHMENT0,Pe=!0);else pe[0]!==s.BACK&&(pe[0]=s.BACK,Pe=!0);Pe&&(t.isWebGL2?s.drawBuffers(pe):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(pe))}function Rt(U){return m!==U?(s.useProgram(U),m=U,!0):!1}const Re={100:s.FUNC_ADD,101:s.FUNC_SUBTRACT,102:s.FUNC_REVERSE_SUBTRACT};if(i)Re[103]=s.MIN,Re[104]=s.MAX;else{const U=e.get("EXT_blend_minmax");U!==null&&(Re[103]=U.MIN_EXT,Re[104]=U.MAX_EXT)}const Ue={200:s.ZERO,201:s.ONE,202:s.SRC_COLOR,204:s.SRC_ALPHA,210:s.SRC_ALPHA_SATURATE,208:s.DST_COLOR,206:s.DST_ALPHA,203:s.ONE_MINUS_SRC_COLOR,205:s.ONE_MINUS_SRC_ALPHA,209:s.ONE_MINUS_DST_COLOR,207:s.ONE_MINUS_DST_ALPHA,211:s.CONSTANT_COLOR,212:s.ONE_MINUS_CONSTANT_COLOR,213:s.CONSTANT_ALPHA,214:s.ONE_MINUS_CONSTANT_ALPHA};function le(U,fe,pe,Pe,Ce,ct,ht,Dt,$t,ut){if(U===0){g===!0&&(Te(s.BLEND),g=!1);return}if(g===!1&&(be(s.BLEND),g=!0),U!==5){if(U!==E||ut!==w){if((_!==100||R!==100)&&(s.blendEquation(s.FUNC_ADD),_=100,R=100),ut)switch(U){case 1:s.blendFuncSeparate(s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:s.blendFunc(s.ONE,s.ONE);break;case 3:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:s.blendFuncSeparate(s.ZERO,s.SRC_COLOR,s.ZERO,s.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",U);break}else switch(U){case 1:s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:s.blendFunc(s.SRC_ALPHA,s.ONE);break;case 3:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:s.blendFunc(s.ZERO,s.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",U);break}T=null,b=null,A=null,C=null,S.set(0,0,0),y=0,E=U,w=ut}return}Ce=Ce||fe,ct=ct||pe,ht=ht||Pe,(fe!==_||Ce!==R)&&(s.blendEquationSeparate(Re[fe],Re[Ce]),_=fe,R=Ce),(pe!==T||Pe!==b||ct!==A||ht!==C)&&(s.blendFuncSeparate(Ue[pe],Ue[Pe],Ue[ct],Ue[ht]),T=pe,b=Pe,A=ct,C=ht),(Dt.equals(S)===!1||$t!==y)&&(s.blendColor(Dt.r,Dt.g,Dt.b,$t),S.copy(Dt),y=$t),E=U,w=!1}function $e(U,fe){U.side===2?Te(s.CULL_FACE):be(s.CULL_FACE);let pe=U.side===1;fe&&(pe=!pe),Me(pe),U.blending===1&&U.transparent===!1?le(0):le(U.blending,U.blendEquation,U.blendSrc,U.blendDst,U.blendEquationAlpha,U.blendSrcAlpha,U.blendDstAlpha,U.blendColor,U.blendAlpha,U.premultipliedAlpha),l.setFunc(U.depthFunc),l.setTest(U.depthTest),l.setMask(U.depthWrite),o.setMask(U.colorWrite);const Pe=U.stencilWrite;c.setTest(Pe),Pe&&(c.setMask(U.stencilWriteMask),c.setFunc(U.stencilFunc,U.stencilRef,U.stencilFuncMask),c.setOp(U.stencilFail,U.stencilZFail,U.stencilZPass)),K(U.polygonOffset,U.polygonOffsetFactor,U.polygonOffsetUnits),U.alphaToCoverage===!0?be(s.SAMPLE_ALPHA_TO_COVERAGE):Te(s.SAMPLE_ALPHA_TO_COVERAGE)}function Me(U){N!==U&&(U?s.frontFace(s.CW):s.frontFace(s.CCW),N=U)}function I(U){U!==0?(be(s.CULL_FACE),U!==Y&&(U===1?s.cullFace(s.BACK):U===2?s.cullFace(s.FRONT):s.cullFace(s.FRONT_AND_BACK))):Te(s.CULL_FACE),Y=U}function M(U){U!==D&&(k&&s.lineWidth(U),D=U)}function K(U,fe,pe){U?(be(s.POLYGON_OFFSET_FILL),(F!==fe||O!==pe)&&(s.polygonOffset(fe,pe),F=fe,O=pe)):Te(s.POLYGON_OFFSET_FILL)}function ne(U){U?be(s.SCISSOR_TEST):Te(s.SCISSOR_TEST)}function re(U){U===void 0&&(U=s.TEXTURE0+$-1),P!==U&&(s.activeTexture(U),P=U)}function ae(U,fe,pe){pe===void 0&&(P===null?pe=s.TEXTURE0+$-1:pe=P);let Pe=V[pe];Pe===void 0&&(Pe={type:void 0,texture:void 0},V[pe]=Pe),(Pe.type!==U||Pe.texture!==fe)&&(P!==pe&&(s.activeTexture(pe),P=pe),s.bindTexture(U,fe||Se[U]),Pe.type=U,Pe.texture=fe)}function ye(){const U=V[P];U!==void 0&&U.type!==void 0&&(s.bindTexture(U.type,null),U.type=void 0,U.texture=void 0)}function ue(){try{s.compressedTexImage2D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function _e(){try{s.compressedTexImage3D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function Ie(){try{s.texSubImage2D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function ke(){try{s.texSubImage3D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function se(){try{s.compressedTexSubImage2D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function Ze(){try{s.compressedTexSubImage3D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function Qe(){try{s.texStorage2D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function Ne(){try{s.texStorage3D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function Le(){try{s.texImage2D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function xe(){try{s.texImage3D.apply(s,arguments)}catch(U){console.error("THREE.WebGLState:",U)}}function ze(U){ie.equals(U)===!1&&(s.scissor(U.x,U.y,U.z,U.w),ie.copy(U))}function it(U){oe.equals(U)===!1&&(s.viewport(U.x,U.y,U.z,U.w),oe.copy(U))}function vt(U,fe){let pe=u.get(fe);pe===void 0&&(pe=new WeakMap,u.set(fe,pe));let Pe=pe.get(U);Pe===void 0&&(Pe=s.getUniformBlockIndex(fe,U.name),pe.set(U,Pe))}function qe(U,fe){const Pe=u.get(fe).get(U);h.get(fe)!==Pe&&(s.uniformBlockBinding(fe,Pe,U.__bindingPointIndex),h.set(fe,Pe))}function he(){s.disable(s.BLEND),s.disable(s.CULL_FACE),s.disable(s.DEPTH_TEST),s.disable(s.POLYGON_OFFSET_FILL),s.disable(s.SCISSOR_TEST),s.disable(s.STENCIL_TEST),s.disable(s.SAMPLE_ALPHA_TO_COVERAGE),s.blendEquation(s.FUNC_ADD),s.blendFunc(s.ONE,s.ZERO),s.blendFuncSeparate(s.ONE,s.ZERO,s.ONE,s.ZERO),s.blendColor(0,0,0,0),s.colorMask(!0,!0,!0,!0),s.clearColor(0,0,0,0),s.depthMask(!0),s.depthFunc(s.LESS),s.clearDepth(1),s.stencilMask(4294967295),s.stencilFunc(s.ALWAYS,0,4294967295),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),s.clearStencil(0),s.cullFace(s.BACK),s.frontFace(s.CCW),s.polygonOffset(0,0),s.activeTexture(s.TEXTURE0),s.bindFramebuffer(s.FRAMEBUFFER,null),i===!0&&(s.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),s.bindFramebuffer(s.READ_FRAMEBUFFER,null)),s.useProgram(null),s.lineWidth(1),s.scissor(0,0,s.canvas.width,s.canvas.height),s.viewport(0,0,s.canvas.width,s.canvas.height),d={},P=null,V={},f={},p=new WeakMap,v=[],m=null,g=!1,E=null,_=null,T=null,b=null,R=null,A=null,C=null,S=new rt(0,0,0),y=0,w=!1,N=null,Y=null,D=null,F=null,O=null,ie.set(0,0,s.canvas.width,s.canvas.height),oe.set(0,0,s.canvas.width,s.canvas.height),o.reset(),l.reset(),c.reset()}return{buffers:{color:o,depth:l,stencil:c},enable:be,disable:Te,bindFramebuffer:Ge,drawBuffers:q,useProgram:Rt,setBlending:le,setMaterial:$e,setFlipSided:Me,setCullFace:I,setLineWidth:M,setPolygonOffset:K,setScissorTest:ne,activeTexture:re,bindTexture:ae,unbindTexture:ye,compressedTexImage2D:ue,compressedTexImage3D:_e,texImage2D:Le,texImage3D:xe,updateUBOMapping:vt,uniformBlockBinding:qe,texStorage2D:Qe,texStorage3D:Ne,texSubImage2D:Ie,texSubImage3D:ke,compressedTexSubImage2D:se,compressedTexSubImage3D:Ze,scissor:ze,viewport:it,reset:he}}function Wg(s,e,t,i,n,r,a){const o=n.isWebGL2,l=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new WeakMap;let u;const d=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,M){return f?new OffscreenCanvas(I,M):Cs("canvas")}function v(I,M,K,ne){let re=1;if((I.width>ne||I.height>ne)&&(re=ne/Math.max(I.width,I.height)),re<1||M===!0)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap){const ae=M?ea:Math.floor,ye=ae(re*I.width),ue=ae(re*I.height);u===void 0&&(u=p(ye,ue));const _e=K?p(ye,ue):u;return _e.width=ye,_e.height=ue,_e.getContext("2d").drawImage(I,0,0,ye,ue),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+I.width+"x"+I.height+") to ("+ye+"x"+ue+")."),_e}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+I.width+"x"+I.height+")."),I;return I}function m(I){return Xo(I.width)&&Xo(I.height)}function g(I){return o?!1:I.wrapS!==1001||I.wrapT!==1001||I.minFilter!==1003&&I.minFilter!==1006}function E(I,M){return I.generateMipmaps&&M&&I.minFilter!==1003&&I.minFilter!==1006}function _(I){s.generateMipmap(I)}function T(I,M,K,ne,re=!1){if(o===!1)return M;if(I!==null){if(s[I]!==void 0)return s[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ae=M;if(M===s.RED&&(K===s.FLOAT&&(ae=s.R32F),K===s.HALF_FLOAT&&(ae=s.R16F),K===s.UNSIGNED_BYTE&&(ae=s.R8)),M===s.RED_INTEGER&&(K===s.UNSIGNED_BYTE&&(ae=s.R8UI),K===s.UNSIGNED_SHORT&&(ae=s.R16UI),K===s.UNSIGNED_INT&&(ae=s.R32UI),K===s.BYTE&&(ae=s.R8I),K===s.SHORT&&(ae=s.R16I),K===s.INT&&(ae=s.R32I)),M===s.RG&&(K===s.FLOAT&&(ae=s.RG32F),K===s.HALF_FLOAT&&(ae=s.RG16F),K===s.UNSIGNED_BYTE&&(ae=s.RG8)),M===s.RGBA){const ye=re?Ms:st.getTransfer(ne);K===s.FLOAT&&(ae=s.RGBA32F),K===s.HALF_FLOAT&&(ae=s.RGBA16F),K===s.UNSIGNED_BYTE&&(ae=ye===dt?s.SRGB8_ALPHA8:s.RGBA8),K===s.UNSIGNED_SHORT_4_4_4_4&&(ae=s.RGBA4),K===s.UNSIGNED_SHORT_5_5_5_1&&(ae=s.RGB5_A1)}return(ae===s.R16F||ae===s.R32F||ae===s.RG16F||ae===s.RG32F||ae===s.RGBA16F||ae===s.RGBA32F)&&e.get("EXT_color_buffer_float"),ae}function b(I,M,K){return E(I,K)===!0||I.isFramebufferTexture&&I.minFilter!==1003&&I.minFilter!==1006?Math.log2(Math.max(M.width,M.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?M.mipmaps.length:1}function R(I){return I===1003||I===1004||I===1005?s.NEAREST:s.LINEAR}function A(I){const M=I.target;M.removeEventListener("dispose",A),S(M),M.isVideoTexture&&h.delete(M)}function C(I){const M=I.target;M.removeEventListener("dispose",C),w(M)}function S(I){const M=i.get(I);if(M.__webglInit===void 0)return;const K=I.source,ne=d.get(K);if(ne){const re=ne[M.__cacheKey];re.usedTimes--,re.usedTimes===0&&y(I),Object.keys(ne).length===0&&d.delete(K)}i.remove(I)}function y(I){const M=i.get(I);s.deleteTexture(M.__webglTexture);const K=I.source,ne=d.get(K);delete ne[M.__cacheKey],a.memory.textures--}function w(I){const M=I.texture,K=i.get(I),ne=i.get(M);if(ne.__webglTexture!==void 0&&(s.deleteTexture(ne.__webglTexture),a.memory.textures--),I.depthTexture&&I.depthTexture.dispose(),I.isWebGLCubeRenderTarget)for(let re=0;re<6;re++){if(Array.isArray(K.__webglFramebuffer[re]))for(let ae=0;ae<K.__webglFramebuffer[re].length;ae++)s.deleteFramebuffer(K.__webglFramebuffer[re][ae]);else s.deleteFramebuffer(K.__webglFramebuffer[re]);K.__webglDepthbuffer&&s.deleteRenderbuffer(K.__webglDepthbuffer[re])}else{if(Array.isArray(K.__webglFramebuffer))for(let re=0;re<K.__webglFramebuffer.length;re++)s.deleteFramebuffer(K.__webglFramebuffer[re]);else s.deleteFramebuffer(K.__webglFramebuffer);if(K.__webglDepthbuffer&&s.deleteRenderbuffer(K.__webglDepthbuffer),K.__webglMultisampledFramebuffer&&s.deleteFramebuffer(K.__webglMultisampledFramebuffer),K.__webglColorRenderbuffer)for(let re=0;re<K.__webglColorRenderbuffer.length;re++)K.__webglColorRenderbuffer[re]&&s.deleteRenderbuffer(K.__webglColorRenderbuffer[re]);K.__webglDepthRenderbuffer&&s.deleteRenderbuffer(K.__webglDepthRenderbuffer)}if(I.isWebGLMultipleRenderTargets)for(let re=0,ae=M.length;re<ae;re++){const ye=i.get(M[re]);ye.__webglTexture&&(s.deleteTexture(ye.__webglTexture),a.memory.textures--),i.remove(M[re])}i.remove(M),i.remove(I)}let N=0;function Y(){N=0}function D(){const I=N;return I>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+n.maxTextures),N+=1,I}function F(I){const M=[];return M.push(I.wrapS),M.push(I.wrapT),M.push(I.wrapR||0),M.push(I.magFilter),M.push(I.minFilter),M.push(I.anisotropy),M.push(I.internalFormat),M.push(I.format),M.push(I.type),M.push(I.generateMipmaps),M.push(I.premultiplyAlpha),M.push(I.flipY),M.push(I.unpackAlignment),M.push(I.colorSpace),M.join()}function O(I,M){const K=i.get(I);if(I.isVideoTexture&&$e(I),I.isRenderTargetTexture===!1&&I.version>0&&K.__version!==I.version){const ne=I.image;if(ne===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ne.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{ie(K,I,M);return}}t.bindTexture(s.TEXTURE_2D,K.__webglTexture,s.TEXTURE0+M)}function $(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){ie(K,I,M);return}t.bindTexture(s.TEXTURE_2D_ARRAY,K.__webglTexture,s.TEXTURE0+M)}function k(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){ie(K,I,M);return}t.bindTexture(s.TEXTURE_3D,K.__webglTexture,s.TEXTURE0+M)}function B(I,M){const K=i.get(I);if(I.version>0&&K.__version!==I.version){oe(K,I,M);return}t.bindTexture(s.TEXTURE_CUBE_MAP,K.__webglTexture,s.TEXTURE0+M)}const X={1e3:s.REPEAT,1001:s.CLAMP_TO_EDGE,1002:s.MIRRORED_REPEAT},P={1003:s.NEAREST,1004:s.NEAREST_MIPMAP_NEAREST,1005:s.NEAREST_MIPMAP_LINEAR,1006:s.LINEAR,1007:s.LINEAR_MIPMAP_NEAREST,1008:s.LINEAR_MIPMAP_LINEAR},V={512:s.NEVER,519:s.ALWAYS,513:s.LESS,515:s.LEQUAL,514:s.EQUAL,518:s.GEQUAL,516:s.GREATER,517:s.NOTEQUAL};function G(I,M,K){if(K?(s.texParameteri(I,s.TEXTURE_WRAP_S,X[M.wrapS]),s.texParameteri(I,s.TEXTURE_WRAP_T,X[M.wrapT]),(I===s.TEXTURE_3D||I===s.TEXTURE_2D_ARRAY)&&s.texParameteri(I,s.TEXTURE_WRAP_R,X[M.wrapR]),s.texParameteri(I,s.TEXTURE_MAG_FILTER,P[M.magFilter]),s.texParameteri(I,s.TEXTURE_MIN_FILTER,P[M.minFilter])):(s.texParameteri(I,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(I,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),(I===s.TEXTURE_3D||I===s.TEXTURE_2D_ARRAY)&&s.texParameteri(I,s.TEXTURE_WRAP_R,s.CLAMP_TO_EDGE),(M.wrapS!==1001||M.wrapT!==1001)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),s.texParameteri(I,s.TEXTURE_MAG_FILTER,R(M.magFilter)),s.texParameteri(I,s.TEXTURE_MIN_FILTER,R(M.minFilter)),M.minFilter!==1003&&M.minFilter!==1006&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),M.compareFunction&&(s.texParameteri(I,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(I,s.TEXTURE_COMPARE_FUNC,V[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const ne=e.get("EXT_texture_filter_anisotropic");if(M.magFilter===1003||M.minFilter!==1005&&M.minFilter!==1008||M.type===1015&&e.has("OES_texture_float_linear")===!1||o===!1&&M.type===1016&&e.has("OES_texture_half_float_linear")===!1)return;(M.anisotropy>1||i.get(M).__currentAnisotropy)&&(s.texParameterf(I,ne.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,n.getMaxAnisotropy())),i.get(M).__currentAnisotropy=M.anisotropy)}}function J(I,M){let K=!1;I.__webglInit===void 0&&(I.__webglInit=!0,M.addEventListener("dispose",A));const ne=M.source;let re=d.get(ne);re===void 0&&(re={},d.set(ne,re));const ae=F(M);if(ae!==I.__cacheKey){re[ae]===void 0&&(re[ae]={texture:s.createTexture(),usedTimes:0},a.memory.textures++,K=!0),re[ae].usedTimes++;const ye=re[I.__cacheKey];ye!==void 0&&(re[I.__cacheKey].usedTimes--,ye.usedTimes===0&&y(M)),I.__cacheKey=ae,I.__webglTexture=re[ae].texture}return K}function ie(I,M,K){let ne=s.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(ne=s.TEXTURE_2D_ARRAY),M.isData3DTexture&&(ne=s.TEXTURE_3D);const re=J(I,M),ae=M.source;t.bindTexture(ne,I.__webglTexture,s.TEXTURE0+K);const ye=i.get(ae);if(ae.version!==ye.__version||re===!0){t.activeTexture(s.TEXTURE0+K);const ue=st.getPrimaries(st.workingColorSpace),_e=M.colorSpace===ri?null:st.getPrimaries(M.colorSpace),Ie=M.colorSpace===ri||ue===_e?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,M.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,M.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ie);const ke=g(M)&&m(M.image)===!1;let se=v(M.image,ke,!1,n.maxTextureSize);se=Me(M,se);const Ze=m(se)||o,Qe=r.convert(M.format,M.colorSpace);let Ne=r.convert(M.type),Le=T(M.internalFormat,Qe,Ne,M.colorSpace,M.isVideoTexture);G(ne,M,Ze);let xe;const ze=M.mipmaps,it=o&&M.isVideoTexture!==!0&&Le!==36196,vt=ye.__version===void 0||re===!0,qe=b(M,se,Ze);if(M.isDepthTexture)Le=s.DEPTH_COMPONENT,o?M.type===1015?Le=s.DEPTH_COMPONENT32F:M.type===1014?Le=s.DEPTH_COMPONENT24:M.type===1020?Le=s.DEPTH24_STENCIL8:Le=s.DEPTH_COMPONENT16:M.type===1015&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),M.format===1026&&Le===s.DEPTH_COMPONENT&&M.type!==1012&&M.type!==1014&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),M.type=1014,Ne=r.convert(M.type)),M.format===1027&&Le===s.DEPTH_COMPONENT&&(Le=s.DEPTH_STENCIL,M.type!==1020&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),M.type=1020,Ne=r.convert(M.type))),vt&&(it?t.texStorage2D(s.TEXTURE_2D,1,Le,se.width,se.height):t.texImage2D(s.TEXTURE_2D,0,Le,se.width,se.height,0,Qe,Ne,null));else if(M.isDataTexture)if(ze.length>0&&Ze){it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,U=ze.length;he<U;he++)xe=ze[he],it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,Ne,xe.data):t.texImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,Qe,Ne,xe.data);M.generateMipmaps=!1}else it?(vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height),t.texSubImage2D(s.TEXTURE_2D,0,0,0,se.width,se.height,Qe,Ne,se.data)):t.texImage2D(s.TEXTURE_2D,0,Le,se.width,se.height,0,Qe,Ne,se.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){it&&vt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,qe,Le,ze[0].width,ze[0].height,se.depth);for(let he=0,U=ze.length;he<U;he++)xe=ze[he],M.format!==1023?Qe!==null?it?t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,he,0,0,0,xe.width,xe.height,se.depth,Qe,xe.data,0,0):t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,he,Le,xe.width,xe.height,se.depth,0,xe.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):it?t.texSubImage3D(s.TEXTURE_2D_ARRAY,he,0,0,0,xe.width,xe.height,se.depth,Qe,Ne,xe.data):t.texImage3D(s.TEXTURE_2D_ARRAY,he,Le,xe.width,xe.height,se.depth,0,Qe,Ne,xe.data)}else{it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,U=ze.length;he<U;he++)xe=ze[he],M.format!==1023?Qe!==null?it?t.compressedTexSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,xe.data):t.compressedTexImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,xe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,xe.width,xe.height,Qe,Ne,xe.data):t.texImage2D(s.TEXTURE_2D,he,Le,xe.width,xe.height,0,Qe,Ne,xe.data)}else if(M.isDataArrayTexture)it?(vt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,qe,Le,se.width,se.height,se.depth),t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,se.width,se.height,se.depth,Qe,Ne,se.data)):t.texImage3D(s.TEXTURE_2D_ARRAY,0,Le,se.width,se.height,se.depth,0,Qe,Ne,se.data);else if(M.isData3DTexture)it?(vt&&t.texStorage3D(s.TEXTURE_3D,qe,Le,se.width,se.height,se.depth),t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,se.width,se.height,se.depth,Qe,Ne,se.data)):t.texImage3D(s.TEXTURE_3D,0,Le,se.width,se.height,se.depth,0,Qe,Ne,se.data);else if(M.isFramebufferTexture){if(vt)if(it)t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height);else{let he=se.width,U=se.height;for(let fe=0;fe<qe;fe++)t.texImage2D(s.TEXTURE_2D,fe,Le,he,U,0,Qe,Ne,null),he>>=1,U>>=1}}else if(ze.length>0&&Ze){it&&vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,ze[0].width,ze[0].height);for(let he=0,U=ze.length;he<U;he++)xe=ze[he],it?t.texSubImage2D(s.TEXTURE_2D,he,0,0,Qe,Ne,xe):t.texImage2D(s.TEXTURE_2D,he,Le,Qe,Ne,xe);M.generateMipmaps=!1}else it?(vt&&t.texStorage2D(s.TEXTURE_2D,qe,Le,se.width,se.height),t.texSubImage2D(s.TEXTURE_2D,0,0,0,Qe,Ne,se)):t.texImage2D(s.TEXTURE_2D,0,Le,Qe,Ne,se);E(M,Ze)&&_(ne),ye.__version=ae.version,M.onUpdate&&M.onUpdate(M)}I.__version=M.version}function oe(I,M,K){if(M.image.length!==6)return;const ne=J(I,M),re=M.source;t.bindTexture(s.TEXTURE_CUBE_MAP,I.__webglTexture,s.TEXTURE0+K);const ae=i.get(re);if(re.version!==ae.__version||ne===!0){t.activeTexture(s.TEXTURE0+K);const ye=st.getPrimaries(st.workingColorSpace),ue=M.colorSpace===ri?null:st.getPrimaries(M.colorSpace),_e=M.colorSpace===ri||ye===ue?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,M.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,M.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,_e);const Ie=M.isCompressedTexture||M.image[0].isCompressedTexture,ke=M.image[0]&&M.image[0].isDataTexture,se=[];for(let he=0;he<6;he++)!Ie&&!ke?se[he]=v(M.image[he],!1,!0,n.maxCubemapSize):se[he]=ke?M.image[he].image:M.image[he],se[he]=Me(M,se[he]);const Ze=se[0],Qe=m(Ze)||o,Ne=r.convert(M.format,M.colorSpace),Le=r.convert(M.type),xe=T(M.internalFormat,Ne,Le,M.colorSpace),ze=o&&M.isVideoTexture!==!0,it=ae.__version===void 0||ne===!0;let vt=b(M,Ze,Qe);G(s.TEXTURE_CUBE_MAP,M,Qe);let qe;if(Ie){ze&&it&&t.texStorage2D(s.TEXTURE_CUBE_MAP,vt,xe,Ze.width,Ze.height);for(let he=0;he<6;he++){qe=se[he].mipmaps;for(let U=0;U<qe.length;U++){const fe=qe[U];M.format!==1023?Ne!==null?ze?t.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U,0,0,fe.width,fe.height,Ne,fe.data):t.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U,xe,fe.width,fe.height,0,fe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U,0,0,fe.width,fe.height,Ne,Le,fe.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U,xe,fe.width,fe.height,0,Ne,Le,fe.data)}}}else{qe=M.mipmaps,ze&&it&&(qe.length>0&&vt++,t.texStorage2D(s.TEXTURE_CUBE_MAP,vt,xe,se[0].width,se[0].height));for(let he=0;he<6;he++)if(ke){ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,0,0,se[he].width,se[he].height,Ne,Le,se[he].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,xe,se[he].width,se[he].height,0,Ne,Le,se[he].data);for(let U=0;U<qe.length;U++){const pe=qe[U].image[he].image;ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U+1,0,0,pe.width,pe.height,Ne,Le,pe.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U+1,xe,pe.width,pe.height,0,Ne,Le,pe.data)}}else{ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,0,0,Ne,Le,se[he]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,0,xe,Ne,Le,se[he]);for(let U=0;U<qe.length;U++){const fe=qe[U];ze?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U+1,0,0,Ne,Le,fe.image[he]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+he,U+1,xe,Ne,Le,fe.image[he])}}}E(M,Qe)&&_(s.TEXTURE_CUBE_MAP),ae.__version=re.version,M.onUpdate&&M.onUpdate(M)}I.__version=M.version}function me(I,M,K,ne,re,ae){const ye=r.convert(K.format,K.colorSpace),ue=r.convert(K.type),_e=T(K.internalFormat,ye,ue,K.colorSpace);if(!i.get(M).__hasExternalTextures){const ke=Math.max(1,M.width>>ae),se=Math.max(1,M.height>>ae);re===s.TEXTURE_3D||re===s.TEXTURE_2D_ARRAY?t.texImage3D(re,ae,_e,ke,se,M.depth,0,ye,ue,null):t.texImage2D(re,ae,_e,ke,se,0,ye,ue,null)}t.bindFramebuffer(s.FRAMEBUFFER,I),le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,ne,re,i.get(K).__webglTexture,0,Ue(M)):(re===s.TEXTURE_2D||re>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&re<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,ne,re,i.get(K).__webglTexture,ae),t.bindFramebuffer(s.FRAMEBUFFER,null)}function Se(I,M,K){if(s.bindRenderbuffer(s.RENDERBUFFER,I),M.depthBuffer&&!M.stencilBuffer){let ne=o===!0?s.DEPTH_COMPONENT24:s.DEPTH_COMPONENT16;if(K||le(M)){const re=M.depthTexture;re&&re.isDepthTexture&&(re.type===1015?ne=s.DEPTH_COMPONENT32F:re.type===1014&&(ne=s.DEPTH_COMPONENT24));const ae=Ue(M);le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ae,ne,M.width,M.height):s.renderbufferStorageMultisample(s.RENDERBUFFER,ae,ne,M.width,M.height)}else s.renderbufferStorage(s.RENDERBUFFER,ne,M.width,M.height);s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,I)}else if(M.depthBuffer&&M.stencilBuffer){const ne=Ue(M);K&&le(M)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,ne,s.DEPTH24_STENCIL8,M.width,M.height):le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,ne,s.DEPTH24_STENCIL8,M.width,M.height):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,M.width,M.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,I)}else{const ne=M.isWebGLMultipleRenderTargets===!0?M.texture:[M.texture];for(let re=0;re<ne.length;re++){const ae=ne[re],ye=r.convert(ae.format,ae.colorSpace),ue=r.convert(ae.type),_e=T(ae.internalFormat,ye,ue,ae.colorSpace),Ie=Ue(M);K&&le(M)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,Ie,_e,M.width,M.height):le(M)?l.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,Ie,_e,M.width,M.height):s.renderbufferStorage(s.RENDERBUFFER,_e,M.width,M.height)}}s.bindRenderbuffer(s.RENDERBUFFER,null)}function be(I,M){if(M&&M.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(s.FRAMEBUFFER,I),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!i.get(M.depthTexture).__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),O(M.depthTexture,0);const ne=i.get(M.depthTexture).__webglTexture,re=Ue(M);if(M.depthTexture.format===1026)le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,ne,0,re):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,ne,0);else if(M.depthTexture.format===1027)le(M)?l.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,ne,0,re):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,ne,0);else throw new Error("Unknown depthTexture format")}function Te(I){const M=i.get(I),K=I.isWebGLCubeRenderTarget===!0;if(I.depthTexture&&!M.__autoAllocateDepthBuffer){if(K)throw new Error("target.depthTexture not supported in Cube render targets");be(M.__webglFramebuffer,I)}else if(K){M.__webglDepthbuffer=[];for(let ne=0;ne<6;ne++)t.bindFramebuffer(s.FRAMEBUFFER,M.__webglFramebuffer[ne]),M.__webglDepthbuffer[ne]=s.createRenderbuffer(),Se(M.__webglDepthbuffer[ne],I,!1)}else t.bindFramebuffer(s.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer=s.createRenderbuffer(),Se(M.__webglDepthbuffer,I,!1);t.bindFramebuffer(s.FRAMEBUFFER,null)}function Ge(I,M,K){const ne=i.get(I);M!==void 0&&me(ne.__webglFramebuffer,I,I.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),K!==void 0&&Te(I)}function q(I){const M=I.texture,K=i.get(I),ne=i.get(M);I.addEventListener("dispose",C),I.isWebGLMultipleRenderTargets!==!0&&(ne.__webglTexture===void 0&&(ne.__webglTexture=s.createTexture()),ne.__version=M.version,a.memory.textures++);const re=I.isWebGLCubeRenderTarget===!0,ae=I.isWebGLMultipleRenderTargets===!0,ye=m(I)||o;if(re){K.__webglFramebuffer=[];for(let ue=0;ue<6;ue++)if(o&&M.mipmaps&&M.mipmaps.length>0){K.__webglFramebuffer[ue]=[];for(let _e=0;_e<M.mipmaps.length;_e++)K.__webglFramebuffer[ue][_e]=s.createFramebuffer()}else K.__webglFramebuffer[ue]=s.createFramebuffer()}else{if(o&&M.mipmaps&&M.mipmaps.length>0){K.__webglFramebuffer=[];for(let ue=0;ue<M.mipmaps.length;ue++)K.__webglFramebuffer[ue]=s.createFramebuffer()}else K.__webglFramebuffer=s.createFramebuffer();if(ae)if(n.drawBuffers){const ue=I.texture;for(let _e=0,Ie=ue.length;_e<Ie;_e++){const ke=i.get(ue[_e]);ke.__webglTexture===void 0&&(ke.__webglTexture=s.createTexture(),a.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");if(o&&I.samples>0&&le(I)===!1){const ue=ae?M:[M];K.__webglMultisampledFramebuffer=s.createFramebuffer(),K.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,K.__webglMultisampledFramebuffer);for(let _e=0;_e<ue.length;_e++){const Ie=ue[_e];K.__webglColorRenderbuffer[_e]=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,K.__webglColorRenderbuffer[_e]);const ke=r.convert(Ie.format,Ie.colorSpace),se=r.convert(Ie.type),Ze=T(Ie.internalFormat,ke,se,Ie.colorSpace,I.isXRRenderTarget===!0),Qe=Ue(I);s.renderbufferStorageMultisample(s.RENDERBUFFER,Qe,Ze,I.width,I.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+_e,s.RENDERBUFFER,K.__webglColorRenderbuffer[_e])}s.bindRenderbuffer(s.RENDERBUFFER,null),I.depthBuffer&&(K.__webglDepthRenderbuffer=s.createRenderbuffer(),Se(K.__webglDepthRenderbuffer,I,!0)),t.bindFramebuffer(s.FRAMEBUFFER,null)}}if(re){t.bindTexture(s.TEXTURE_CUBE_MAP,ne.__webglTexture),G(s.TEXTURE_CUBE_MAP,M,ye);for(let ue=0;ue<6;ue++)if(o&&M.mipmaps&&M.mipmaps.length>0)for(let _e=0;_e<M.mipmaps.length;_e++)me(K.__webglFramebuffer[ue][_e],I,M,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+ue,_e);else me(K.__webglFramebuffer[ue],I,M,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0);E(M,ye)&&_(s.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ae){const ue=I.texture;for(let _e=0,Ie=ue.length;_e<Ie;_e++){const ke=ue[_e],se=i.get(ke);t.bindTexture(s.TEXTURE_2D,se.__webglTexture),G(s.TEXTURE_2D,ke,ye),me(K.__webglFramebuffer,I,ke,s.COLOR_ATTACHMENT0+_e,s.TEXTURE_2D,0),E(ke,ye)&&_(s.TEXTURE_2D)}t.unbindTexture()}else{let ue=s.TEXTURE_2D;if((I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(o?ue=I.isWebGL3DRenderTarget?s.TEXTURE_3D:s.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),t.bindTexture(ue,ne.__webglTexture),G(ue,M,ye),o&&M.mipmaps&&M.mipmaps.length>0)for(let _e=0;_e<M.mipmaps.length;_e++)me(K.__webglFramebuffer[_e],I,M,s.COLOR_ATTACHMENT0,ue,_e);else me(K.__webglFramebuffer,I,M,s.COLOR_ATTACHMENT0,ue,0);E(M,ye)&&_(ue),t.unbindTexture()}I.depthBuffer&&Te(I)}function Rt(I){const M=m(I)||o,K=I.isWebGLMultipleRenderTargets===!0?I.texture:[I.texture];for(let ne=0,re=K.length;ne<re;ne++){const ae=K[ne];if(E(ae,M)){const ye=I.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D,ue=i.get(ae).__webglTexture;t.bindTexture(ye,ue),_(ye),t.unbindTexture()}}}function Re(I){if(o&&I.samples>0&&le(I)===!1){const M=I.isWebGLMultipleRenderTargets?I.texture:[I.texture],K=I.width,ne=I.height;let re=s.COLOR_BUFFER_BIT;const ae=[],ye=I.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,ue=i.get(I),_e=I.isWebGLMultipleRenderTargets===!0;if(_e)for(let Ie=0;Ie<M.length;Ie++)t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.RENDERBUFFER,null),t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.TEXTURE_2D,null,0);t.bindFramebuffer(s.READ_FRAMEBUFFER,ue.__webglMultisampledFramebuffer),t.bindFramebuffer(s.DRAW_FRAMEBUFFER,ue.__webglFramebuffer);for(let Ie=0;Ie<M.length;Ie++){ae.push(s.COLOR_ATTACHMENT0+Ie),I.depthBuffer&&ae.push(ye);const ke=ue.__ignoreDepthValues!==void 0?ue.__ignoreDepthValues:!1;if(ke===!1&&(I.depthBuffer&&(re|=s.DEPTH_BUFFER_BIT),I.stencilBuffer&&(re|=s.STENCIL_BUFFER_BIT)),_e&&s.framebufferRenderbuffer(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,ue.__webglColorRenderbuffer[Ie]),ke===!0&&(s.invalidateFramebuffer(s.READ_FRAMEBUFFER,[ye]),s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,[ye])),_e){const se=i.get(M[Ie]).__webglTexture;s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,se,0)}s.blitFramebuffer(0,0,K,ne,0,0,K,ne,re,s.NEAREST),c&&s.invalidateFramebuffer(s.READ_FRAMEBUFFER,ae)}if(t.bindFramebuffer(s.READ_FRAMEBUFFER,null),t.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),_e)for(let Ie=0;Ie<M.length;Ie++){t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.RENDERBUFFER,ue.__webglColorRenderbuffer[Ie]);const ke=i.get(M[Ie]).__webglTexture;t.bindFramebuffer(s.FRAMEBUFFER,ue.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Ie,s.TEXTURE_2D,ke,0)}t.bindFramebuffer(s.DRAW_FRAMEBUFFER,ue.__webglMultisampledFramebuffer)}}function Ue(I){return Math.min(n.maxSamples,I.samples)}function le(I){const M=i.get(I);return o&&I.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function $e(I){const M=a.render.frame;h.get(I)!==M&&(h.set(I,M),I.update())}function Me(I,M){const K=I.colorSpace,ne=I.format,re=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||I.format===1035||K!==Ci&&K!==ri&&(st.getTransfer(K)===dt?o===!1?e.has("EXT_sRGB")===!0&&ne===1023?(I.format=1035,I.minFilter=1006,I.generateMipmaps=!1):M=Zo.sRGBToLinear(M):(ne!==1023||re!==1009)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",K)),M}this.allocateTextureUnit=D,this.resetTextureUnits=Y,this.setTexture2D=O,this.setTexture2DArray=$,this.setTexture3D=k,this.setTextureCube=B,this.rebindTextures=Ge,this.setupRenderTarget=q,this.updateRenderTargetMipmap=Rt,this.updateMultisampleRenderTarget=Re,this.setupDepthRenderbuffer=Te,this.setupFrameBufferTexture=me,this.useMultisampledRTT=le}function Kg(s,e,t){const i=t.isWebGL2;function n(r,a=ri){let o;const l=st.getTransfer(a);if(r===1009)return s.UNSIGNED_BYTE;if(r===1017)return s.UNSIGNED_SHORT_4_4_4_4;if(r===1018)return s.UNSIGNED_SHORT_5_5_5_1;if(r===1010)return s.BYTE;if(r===1011)return s.SHORT;if(r===1012)return s.UNSIGNED_SHORT;if(r===1013)return s.INT;if(r===1014)return s.UNSIGNED_INT;if(r===1015)return s.FLOAT;if(r===1016)return i?s.HALF_FLOAT:(o=e.get("OES_texture_half_float"),o!==null?o.HALF_FLOAT_OES:null);if(r===1021)return s.ALPHA;if(r===1023)return s.RGBA;if(r===1024)return s.LUMINANCE;if(r===1025)return s.LUMINANCE_ALPHA;if(r===1026)return s.DEPTH_COMPONENT;if(r===1027)return s.DEPTH_STENCIL;if(r===1035)return o=e.get("EXT_sRGB"),o!==null?o.SRGB_ALPHA_EXT:null;if(r===1028)return s.RED;if(r===1029)return s.RED_INTEGER;if(r===1030)return s.RG;if(r===1031)return s.RG_INTEGER;if(r===1033)return s.RGBA_INTEGER;if(r===33776||r===33777||r===33778||r===33779)if(l===dt)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(r===33776)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===33777)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===33778)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===33779)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(r===33776)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===33777)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===33778)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===33779)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===35840||r===35841||r===35842||r===35843)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(r===35840)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===35841)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===35842)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===35843)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===36196)return o=e.get("WEBGL_compressed_texture_etc1"),o!==null?o.COMPRESSED_RGB_ETC1_WEBGL:null;if(r===37492||r===37496)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(r===37492)return l===dt?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(r===37496)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===37808||r===37809||r===37810||r===37811||r===37812||r===37813||r===37814||r===37815||r===37816||r===37817||r===37818||r===37819||r===37820||r===37821)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(r===37808)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===37809)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===37810)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===37811)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===37812)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===37813)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===37814)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===37815)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===37816)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===37817)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===37818)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===37819)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===37820)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===37821)return l===dt?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===36492||r===36494||r===36495)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(r===36492)return l===dt?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===36494)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===36495)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===36283||r===36284||r===36285||r===36286)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(r===36492)return o.COMPRESSED_RED_RGTC1_EXT;if(r===36284)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===36285)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===36286)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===1020?i?s.UNSIGNED_INT_24_8:(o=e.get("WEBGL_depth_texture"),o!==null?o.UNSIGNED_INT_24_8_WEBGL:null):s[r]!==void 0?s[r]:null}return{convert:n}}class Xg extends oi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class sr extends Jt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Yg={type:"move"};class Ra{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new sr,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new sr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Q,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Q),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new sr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Q,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Q),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let n=null,r=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,i),g=this._getHandJoint(c,v);m!==null&&(g.matrix.fromArray(m.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=m.radius),g.visible=m!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;c.inputState.pinching&&d>f+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&r!==null&&(n=r),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Yg)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new sr;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class qg extends xn{constructor(e,t){super();const i=this;let n=null,r=1,a=null,o="local-floor",l=1,c=null,h=null,u=null,d=null,f=null,p=null;const v=t.getContextAttributes();let m=null,g=null;const E=[],_=[],T=new nt;let b=null;const R=new oi;R.layers.enable(1),R.viewport=new Ft;const A=new oi;A.layers.enable(2),A.viewport=new Ft;const C=[R,A],S=new Xg;S.layers.enable(1),S.layers.enable(2);let y=null,w=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(G){let J=E[G];return J===void 0&&(J=new Ra,E[G]=J),J.getTargetRaySpace()},this.getControllerGrip=function(G){let J=E[G];return J===void 0&&(J=new Ra,E[G]=J),J.getGripSpace()},this.getHand=function(G){let J=E[G];return J===void 0&&(J=new Ra,E[G]=J),J.getHandSpace()};function N(G){const J=_.indexOf(G.inputSource);if(J===-1)return;const ie=E[J];ie!==void 0&&(ie.update(G.inputSource,G.frame,c||a),ie.dispatchEvent({type:G.type,data:G.inputSource}))}function Y(){n.removeEventListener("select",N),n.removeEventListener("selectstart",N),n.removeEventListener("selectend",N),n.removeEventListener("squeeze",N),n.removeEventListener("squeezestart",N),n.removeEventListener("squeezeend",N),n.removeEventListener("end",Y),n.removeEventListener("inputsourceschange",D);for(let G=0;G<E.length;G++){const J=_[G];J!==null&&(_[G]=null,E[G].disconnect(J))}y=null,w=null,e.setRenderTarget(m),f=null,d=null,u=null,n=null,g=null,V.stop(),i.isPresenting=!1,e.setPixelRatio(b),e.setSize(T.width,T.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(G){r=G,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(G){o=G,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(G){c=G},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(G){if(n=G,n!==null){if(m=e.getRenderTarget(),n.addEventListener("select",N),n.addEventListener("selectstart",N),n.addEventListener("selectend",N),n.addEventListener("squeeze",N),n.addEventListener("squeezestart",N),n.addEventListener("squeezeend",N),n.addEventListener("end",Y),n.addEventListener("inputsourceschange",D),v.xrCompatible!==!0&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(T),n.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const J={antialias:n.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(n,t,J),n.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),g=new nn(f.framebufferWidth,f.framebufferHeight,{format:1023,type:1009,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let J=null,ie=null,oe=null;v.depth&&(oe=v.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,J=v.stencil?1027:1026,ie=v.stencil?1020:1014);const me={colorFormat:t.RGBA8,depthFormat:oe,scaleFactor:r};u=new XRWebGLBinding(n,t),d=u.createProjectionLayer(me),n.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),g=new nn(d.textureWidth,d.textureHeight,{format:1023,type:1009,depthTexture:new Cl(d.textureWidth,d.textureHeight,ie,void 0,void 0,void 0,void 0,void 0,void 0,J),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const Se=e.properties.get(g);Se.__ignoreDepthValues=d.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await n.requestReferenceSpace(o),V.setContext(n),V.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode};function D(G){for(let J=0;J<G.removed.length;J++){const ie=G.removed[J],oe=_.indexOf(ie);oe>=0&&(_[oe]=null,E[oe].disconnect(ie))}for(let J=0;J<G.added.length;J++){const ie=G.added[J];let oe=_.indexOf(ie);if(oe===-1){for(let Se=0;Se<E.length;Se++)if(Se>=_.length){_.push(ie),oe=Se;break}else if(_[Se]===null){_[Se]=ie,oe=Se;break}if(oe===-1)break}const me=E[oe];me&&me.connect(ie)}}const F=new Q,O=new Q;function $(G,J,ie){F.setFromMatrixPosition(J.matrixWorld),O.setFromMatrixPosition(ie.matrixWorld);const oe=F.distanceTo(O),me=J.projectionMatrix.elements,Se=ie.projectionMatrix.elements,be=me[14]/(me[10]-1),Te=me[14]/(me[10]+1),Ge=(me[9]+1)/me[5],q=(me[9]-1)/me[5],Rt=(me[8]-1)/me[0],Re=(Se[8]+1)/Se[0],Ue=be*Rt,le=be*Re,$e=oe/(-Rt+Re),Me=$e*-Rt;J.matrixWorld.decompose(G.position,G.quaternion,G.scale),G.translateX(Me),G.translateZ($e),G.matrixWorld.compose(G.position,G.quaternion,G.scale),G.matrixWorldInverse.copy(G.matrixWorld).invert();const I=be+$e,M=Te+$e,K=Ue-Me,ne=le+(oe-Me),re=Ge*Te/M*I,ae=q*Te/M*I;G.projectionMatrix.makePerspective(K,ne,re,ae,I,M),G.projectionMatrixInverse.copy(G.projectionMatrix).invert()}function k(G,J){J===null?G.matrixWorld.copy(G.matrix):G.matrixWorld.multiplyMatrices(J.matrixWorld,G.matrix),G.matrixWorldInverse.copy(G.matrixWorld).invert()}this.updateCamera=function(G){if(n===null)return;S.near=A.near=R.near=G.near,S.far=A.far=R.far=G.far,(y!==S.near||w!==S.far)&&(n.updateRenderState({depthNear:S.near,depthFar:S.far}),y=S.near,w=S.far);const J=G.parent,ie=S.cameras;k(S,J);for(let oe=0;oe<ie.length;oe++)k(ie[oe],J);ie.length===2?$(S,R,A):S.projectionMatrix.copy(R.projectionMatrix),B(G,S,J)};function B(G,J,ie){ie===null?G.matrix.copy(J.matrixWorld):(G.matrix.copy(ie.matrixWorld),G.matrix.invert(),G.matrix.multiply(J.matrixWorld)),G.matrix.decompose(G.position,G.quaternion,G.scale),G.updateMatrixWorld(!0),G.projectionMatrix.copy(J.projectionMatrix),G.projectionMatrixInverse.copy(J.projectionMatrixInverse),G.isPerspectiveCamera&&(G.fov=Zr*2*Math.atan(1/G.projectionMatrix.elements[5]),G.zoom=1)}this.getCamera=function(){return S},this.getFoveation=function(){if(!(d===null&&f===null))return l},this.setFoveation=function(G){l=G,d!==null&&(d.fixedFoveation=G),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=G)};let X=null;function P(G,J){if(h=J.getViewerPose(c||a),p=J,h!==null){const ie=h.views;f!==null&&(e.setRenderTargetFramebuffer(g,f.framebuffer),e.setRenderTarget(g));let oe=!1;ie.length!==S.cameras.length&&(S.cameras.length=0,oe=!0);for(let me=0;me<ie.length;me++){const Se=ie[me];let be=null;if(f!==null)be=f.getViewport(Se);else{const Ge=u.getViewSubImage(d,Se);be=Ge.viewport,me===0&&(e.setRenderTargetTextures(g,Ge.colorTexture,d.ignoreDepthValues?void 0:Ge.depthStencilTexture),e.setRenderTarget(g))}let Te=C[me];Te===void 0&&(Te=new oi,Te.layers.enable(me),Te.viewport=new Ft,C[me]=Te),Te.matrix.fromArray(Se.transform.matrix),Te.matrix.decompose(Te.position,Te.quaternion,Te.scale),Te.projectionMatrix.fromArray(Se.projectionMatrix),Te.projectionMatrixInverse.copy(Te.projectionMatrix).invert(),Te.viewport.set(be.x,be.y,be.width,be.height),me===0&&(S.matrix.copy(Te.matrix),S.matrix.decompose(S.position,S.quaternion,S.scale)),oe===!0&&S.cameras.push(Te)}}for(let ie=0;ie<E.length;ie++){const oe=_[ie],me=E[ie];oe!==null&&me!==void 0&&me.update(oe,J,c||a)}X&&X(G,J),J.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:J}),p=null}const V=new yl;V.setAnimationLoop(P),this.setAnimationLoop=function(G){X=G},this.dispose=function(){}}}function jg(s,e){function t(m,g){m.matrixAutoUpdate===!0&&m.updateMatrix(),g.value.copy(m.matrix)}function i(m,g){g.color.getRGB(m.fogColor.value,_l(s)),g.isFog?(m.fogNear.value=g.near,m.fogFar.value=g.far):g.isFogExp2&&(m.fogDensity.value=g.density)}function n(m,g,E,_,T){g.isMeshBasicMaterial||g.isMeshLambertMaterial?r(m,g):g.isMeshToonMaterial?(r(m,g),u(m,g)):g.isMeshPhongMaterial?(r(m,g),h(m,g)):g.isMeshStandardMaterial?(r(m,g),d(m,g),g.isMeshPhysicalMaterial&&f(m,g,T)):g.isMeshMatcapMaterial?(r(m,g),p(m,g)):g.isMeshDepthMaterial?r(m,g):g.isMeshDistanceMaterial?(r(m,g),v(m,g)):g.isMeshNormalMaterial?r(m,g):g.isLineBasicMaterial?(a(m,g),g.isLineDashedMaterial&&o(m,g)):g.isPointsMaterial?l(m,g,E,_):g.isSpriteMaterial?c(m,g):g.isShadowMaterial?(m.color.value.copy(g.color),m.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function r(m,g){m.opacity.value=g.opacity,g.color&&m.diffuse.value.copy(g.color),g.emissive&&m.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(m.map.value=g.map,t(g.map,m.mapTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.bumpMap&&(m.bumpMap.value=g.bumpMap,t(g.bumpMap,m.bumpMapTransform),m.bumpScale.value=g.bumpScale,g.side===1&&(m.bumpScale.value*=-1)),g.normalMap&&(m.normalMap.value=g.normalMap,t(g.normalMap,m.normalMapTransform),m.normalScale.value.copy(g.normalScale),g.side===1&&m.normalScale.value.negate()),g.displacementMap&&(m.displacementMap.value=g.displacementMap,t(g.displacementMap,m.displacementMapTransform),m.displacementScale.value=g.displacementScale,m.displacementBias.value=g.displacementBias),g.emissiveMap&&(m.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,m.emissiveMapTransform)),g.specularMap&&(m.specularMap.value=g.specularMap,t(g.specularMap,m.specularMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest);const E=e.get(g).envMap;if(E&&(m.envMap.value=E,m.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=g.reflectivity,m.ior.value=g.ior,m.refractionRatio.value=g.refractionRatio),g.lightMap){m.lightMap.value=g.lightMap;const _=s._useLegacyLights===!0?Math.PI:1;m.lightMapIntensity.value=g.lightMapIntensity*_,t(g.lightMap,m.lightMapTransform)}g.aoMap&&(m.aoMap.value=g.aoMap,m.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,m.aoMapTransform))}function a(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform))}function o(m,g){m.dashSize.value=g.dashSize,m.totalSize.value=g.dashSize+g.gapSize,m.scale.value=g.scale}function l(m,g,E,_){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.size.value=g.size*E,m.scale.value=_*.5,g.map&&(m.map.value=g.map,t(g.map,m.uvTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function c(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.rotation.value=g.rotation,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function h(m,g){m.specular.value.copy(g.specular),m.shininess.value=Math.max(g.shininess,1e-4)}function u(m,g){g.gradientMap&&(m.gradientMap.value=g.gradientMap)}function d(m,g){m.metalness.value=g.metalness,g.metalnessMap&&(m.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,m.metalnessMapTransform)),m.roughness.value=g.roughness,g.roughnessMap&&(m.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,m.roughnessMapTransform)),e.get(g).envMap&&(m.envMapIntensity.value=g.envMapIntensity)}function f(m,g,E){m.ior.value=g.ior,g.sheen>0&&(m.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),m.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(m.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,m.sheenColorMapTransform)),g.sheenRoughnessMap&&(m.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,m.sheenRoughnessMapTransform))),g.clearcoat>0&&(m.clearcoat.value=g.clearcoat,m.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(m.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,m.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(m.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===1&&m.clearcoatNormalScale.value.negate())),g.iridescence>0&&(m.iridescence.value=g.iridescence,m.iridescenceIOR.value=g.iridescenceIOR,m.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(m.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,m.iridescenceMapTransform)),g.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),g.transmission>0&&(m.transmission.value=g.transmission,m.transmissionSamplerMap.value=E.texture,m.transmissionSamplerSize.value.set(E.width,E.height),g.transmissionMap&&(m.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,m.transmissionMapTransform)),m.thickness.value=g.thickness,g.thicknessMap&&(m.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=g.attenuationDistance,m.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(m.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(m.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=g.specularIntensity,m.specularColor.value.copy(g.specularColor),g.specularColorMap&&(m.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,m.specularColorMapTransform)),g.specularIntensityMap&&(m.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,m.specularIntensityMapTransform))}function p(m,g){g.matcap&&(m.matcap.value=g.matcap)}function v(m,g){const E=e.get(g).light;m.referencePosition.value.setFromMatrixPosition(E.matrixWorld),m.nearDistance.value=E.shadow.camera.near,m.farDistance.value=E.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function Qg(s,e,t,i){let n={},r={},a=[];const o=t.isWebGL2?s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(E,_){const T=_.program;i.uniformBlockBinding(E,T)}function c(E,_){let T=n[E.id];T===void 0&&(p(E),T=h(E),n[E.id]=T,E.addEventListener("dispose",m));const b=_.program;i.updateUBOMapping(E,b);const R=e.render.frame;r[E.id]!==R&&(d(E),r[E.id]=R)}function h(E){const _=u();E.__bindingPointIndex=_;const T=s.createBuffer(),b=E.__size,R=E.usage;return s.bindBuffer(s.UNIFORM_BUFFER,T),s.bufferData(s.UNIFORM_BUFFER,b,R),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,_,T),T}function u(){for(let E=0;E<o;E++)if(a.indexOf(E)===-1)return a.push(E),E;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(E){const _=n[E.id],T=E.uniforms,b=E.__cache;s.bindBuffer(s.UNIFORM_BUFFER,_);for(let R=0,A=T.length;R<A;R++){const C=Array.isArray(T[R])?T[R]:[T[R]];for(let S=0,y=C.length;S<y;S++){const w=C[S];if(f(w,R,S,b)===!0){const N=w.__offset,Y=Array.isArray(w.value)?w.value:[w.value];let D=0;for(let F=0;F<Y.length;F++){const O=Y[F],$=v(O);typeof O=="number"||typeof O=="boolean"?(w.__data[0]=O,s.bufferSubData(s.UNIFORM_BUFFER,N+D,w.__data)):O.isMatrix3?(w.__data[0]=O.elements[0],w.__data[1]=O.elements[1],w.__data[2]=O.elements[2],w.__data[3]=0,w.__data[4]=O.elements[3],w.__data[5]=O.elements[4],w.__data[6]=O.elements[5],w.__data[7]=0,w.__data[8]=O.elements[6],w.__data[9]=O.elements[7],w.__data[10]=O.elements[8],w.__data[11]=0):(O.toArray(w.__data,D),D+=$.storage/Float32Array.BYTES_PER_ELEMENT)}s.bufferSubData(s.UNIFORM_BUFFER,N,w.__data)}}}s.bindBuffer(s.UNIFORM_BUFFER,null)}function f(E,_,T,b){const R=E.value,A=_+"_"+T;if(b[A]===void 0)return typeof R=="number"||typeof R=="boolean"?b[A]=R:b[A]=R.clone(),!0;{const C=b[A];if(typeof R=="number"||typeof R=="boolean"){if(C!==R)return b[A]=R,!0}else if(C.equals(R)===!1)return C.copy(R),!0}return!1}function p(E){const _=E.uniforms;let T=0;const b=16;for(let A=0,C=_.length;A<C;A++){const S=Array.isArray(_[A])?_[A]:[_[A]];for(let y=0,w=S.length;y<w;y++){const N=S[y],Y=Array.isArray(N.value)?N.value:[N.value];for(let D=0,F=Y.length;D<F;D++){const O=Y[D],$=v(O),k=T%b;k!==0&&b-k<$.boundary&&(T+=b-k),N.__data=new Float32Array($.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=T,T+=$.storage}}}const R=T%b;return R>0&&(T+=b-R),E.__size=T,E.__cache={},this}function v(E){const _={boundary:0,storage:0};return typeof E=="number"||typeof E=="boolean"?(_.boundary=4,_.storage=4):E.isVector2?(_.boundary=8,_.storage=8):E.isVector3||E.isColor?(_.boundary=16,_.storage=12):E.isVector4?(_.boundary=16,_.storage=16):E.isMatrix3?(_.boundary=48,_.storage=48):E.isMatrix4?(_.boundary=64,_.storage=64):E.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",E),_}function m(E){const _=E.target;_.removeEventListener("dispose",m);const T=a.indexOf(_.__bindingPointIndex);a.splice(T,1),s.deleteBuffer(n[_.id]),delete n[_.id],delete r[_.id]}function g(){for(const E in n)s.deleteBuffer(n[E]);a=[],n={},r={}}return{bind:l,update:c,dispose:g}}class Ql{constructor(e={}){const{canvas:t=Ad(),context:i=null,depth:n=!0,stencil:r=!0,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=e;this.isWebGLRenderer=!0;let d;i!==null?d=i.getContextAttributes().alpha:d=a;const f=new Uint32Array(4),p=new Int32Array(4);let v=null,m=null;const g=[],E=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Mt,this._useLegacyLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const _=this;let T=!1,b=0,R=0,A=null,C=-1,S=null;const y=new Ft,w=new Ft;let N=null;const Y=new rt(0);let D=0,F=t.width,O=t.height,$=1,k=null,B=null;const X=new Ft(0,0,F,O),P=new Ft(0,0,F,O);let V=!1;const G=new Sl;let J=!1,ie=!1,oe=null;const me=new Ot,Se=new nt,be=new Q,Te={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Ge(){return A===null?$:1}let q=i;function Rt(L,W){for(let Z=0;Z<L.length;Z++){const ee=L[Z],j=t.getContext(ee,W);if(j!==null)return j}return null}try{const L={alpha:!0,depth:n,stencil:r,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${qr}`),t.addEventListener("webglcontextlost",he,!1),t.addEventListener("webglcontextrestored",U,!1),t.addEventListener("webglcontextcreationerror",fe,!1),q===null){const W=["webgl2","webgl","experimental-webgl"];if(_.isWebGL1Renderer===!0&&W.shift(),q=Rt(W,L),q===null)throw Rt(W)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&q instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),q.getShaderPrecisionFormat===void 0&&(q.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(L){throw console.error("THREE.WebGLRenderer: "+L.message),L}let Re,Ue,le,$e,Me,I,M,K,ne,re,ae,ye,ue,_e,Ie,ke,se,Ze,Qe,Ne,Le,xe,ze,it;function vt(){Re=new om(q),Ue=new em(q,Re,e),Re.init(Ue),xe=new Kg(q,Re,Ue),le=new zg(q,Re,Ue),$e=new hm(q),Me=new Cg,I=new Wg(q,Re,le,Me,Ue,xe,$e),M=new im(_),K=new am(_),ne=new jd(q,Ue),ze=new Zp(q,Re,ne,Ue),re=new lm(q,ne,$e,ze),ae=new pm(q,re,ne,$e),Qe=new fm(q,Ue,I),ke=new tm(Me),ye=new Ig(_,M,K,Re,Ue,ze,ke),ue=new jg(_,Me),_e=new Dg,Ie=new kg(Re,Ue),Ze=new Qp(_,M,K,le,ae,d,l),se=new $g(_,ae,Ue),it=new Qg(q,$e,Ue,le),Ne=new Jp(q,Re,$e,Ue),Le=new cm(q,Re,$e,Ue),$e.programs=ye.programs,_.capabilities=Ue,_.extensions=Re,_.properties=Me,_.renderLists=_e,_.shadowMap=se,_.state=le,_.info=$e}vt();const qe=new qg(_,q);this.xr=qe,this.getContext=function(){return q},this.getContextAttributes=function(){return q.getContextAttributes()},this.forceContextLoss=function(){const L=Re.get("WEBGL_lose_context");L&&L.loseContext()},this.forceContextRestore=function(){const L=Re.get("WEBGL_lose_context");L&&L.restoreContext()},this.getPixelRatio=function(){return $},this.setPixelRatio=function(L){L!==void 0&&($=L,this.setSize(F,O,!1))},this.getSize=function(L){return L.set(F,O)},this.setSize=function(L,W,Z=!0){if(qe.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=L,O=W,t.width=Math.floor(L*$),t.height=Math.floor(W*$),Z===!0&&(t.style.width=L+"px",t.style.height=W+"px"),this.setViewport(0,0,L,W)},this.getDrawingBufferSize=function(L){return L.set(F*$,O*$).floor()},this.setDrawingBufferSize=function(L,W,Z){F=L,O=W,$=Z,t.width=Math.floor(L*Z),t.height=Math.floor(W*Z),this.setViewport(0,0,L,W)},this.getCurrentViewport=function(L){return L.copy(y)},this.getViewport=function(L){return L.copy(X)},this.setViewport=function(L,W,Z,ee){L.isVector4?X.set(L.x,L.y,L.z,L.w):X.set(L,W,Z,ee),le.viewport(y.copy(X).multiplyScalar($).floor())},this.getScissor=function(L){return L.copy(P)},this.setScissor=function(L,W,Z,ee){L.isVector4?P.set(L.x,L.y,L.z,L.w):P.set(L,W,Z,ee),le.scissor(w.copy(P).multiplyScalar($).floor())},this.getScissorTest=function(){return V},this.setScissorTest=function(L){le.setScissorTest(V=L)},this.setOpaqueSort=function(L){k=L},this.setTransparentSort=function(L){B=L},this.getClearColor=function(L){return L.copy(Ze.getClearColor())},this.setClearColor=function(){Ze.setClearColor.apply(Ze,arguments)},this.getClearAlpha=function(){return Ze.getClearAlpha()},this.setClearAlpha=function(){Ze.setClearAlpha.apply(Ze,arguments)},this.clear=function(L=!0,W=!0,Z=!0){let ee=0;if(L){let j=!1;if(A!==null){const ve=A.texture.format;j=ve===1033||ve===1031||ve===1029}if(j){const ve=A.texture.type,Ae=ve===1009||ve===1014||ve===1012||ve===1020||ve===1017||ve===1018,we=Ze.getClearColor(),Oe=Ze.getClearAlpha(),Ke=we.r,Be=we.g,Ve=we.b;Ae?(f[0]=Ke,f[1]=Be,f[2]=Ve,f[3]=Oe,q.clearBufferuiv(q.COLOR,0,f)):(p[0]=Ke,p[1]=Be,p[2]=Ve,p[3]=Oe,q.clearBufferiv(q.COLOR,0,p))}else ee|=q.COLOR_BUFFER_BIT}W&&(ee|=q.DEPTH_BUFFER_BIT),Z&&(ee|=q.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),q.clear(ee)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",he,!1),t.removeEventListener("webglcontextrestored",U,!1),t.removeEventListener("webglcontextcreationerror",fe,!1),_e.dispose(),Ie.dispose(),Me.dispose(),M.dispose(),K.dispose(),ae.dispose(),ze.dispose(),it.dispose(),ye.dispose(),qe.dispose(),qe.removeEventListener("sessionstart",$t),qe.removeEventListener("sessionend",ut),oe&&(oe.dispose(),oe=null),zt.stop()};function he(L){L.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function U(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const L=$e.autoReset,W=se.enabled,Z=se.autoUpdate,ee=se.needsUpdate,j=se.type;vt(),$e.autoReset=L,se.enabled=W,se.autoUpdate=Z,se.needsUpdate=ee,se.type=j}function fe(L){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",L.statusMessage)}function pe(L){const W=L.target;W.removeEventListener("dispose",pe),Pe(W)}function Pe(L){Ce(L),Me.remove(L)}function Ce(L){const W=Me.get(L).programs;W!==void 0&&(W.forEach(function(Z){ye.releaseProgram(Z)}),L.isShaderMaterial&&ye.releaseShaderCache(L))}this.renderBufferDirect=function(L,W,Z,ee,j,ve){W===null&&(W=Te);const Ae=j.isMesh&&j.matrixWorld.determinant()<0,we=zx(L,W,Z,ee,j);le.setMaterial(ee,Ae);let Oe=Z.index,Ke=1;if(ee.wireframe===!0){if(Oe=re.getWireframeAttribute(Z),Oe===void 0)return;Ke=2}const Be=Z.drawRange,Ve=Z.attributes.position;let xt=Be.start*Ke,si=(Be.start+Be.count)*Ke;ve!==null&&(xt=Math.max(xt,ve.start*Ke),si=Math.min(si,(ve.start+ve.count)*Ke)),Oe!==null?(xt=Math.max(xt,0),si=Math.min(si,Oe.count)):Ve!=null&&(xt=Math.max(xt,0),si=Math.min(si,Ve.count));const Pt=si-xt;if(Pt<0||Pt===1/0)return;ze.setup(j,ee,we,Z,Oe);let zi,mt=Ne;if(Oe!==null&&(zi=ne.get(Oe),mt=Le,mt.setIndex(zi)),j.isMesh)ee.wireframe===!0?(le.setLineWidth(ee.wireframeLinewidth*Ge()),mt.setMode(q.LINES)):mt.setMode(q.TRIANGLES);else if(j.isLine){let je=ee.linewidth;je===void 0&&(je=1),le.setLineWidth(je*Ge()),j.isLineSegments?mt.setMode(q.LINES):j.isLineLoop?mt.setMode(q.LINE_LOOP):mt.setMode(q.LINE_STRIP)}else j.isPoints?mt.setMode(q.POINTS):j.isSprite&&mt.setMode(q.TRIANGLES);if(j.isBatchedMesh)mt.renderMultiDraw(j._multiDrawStarts,j._multiDrawCounts,j._multiDrawCount);else if(j.isInstancedMesh)mt.renderInstances(xt,Pt,j.count);else if(Z.isInstancedBufferGeometry){const je=Z._maxInstanceCount!==void 0?Z._maxInstanceCount:1/0,Ho=Math.min(Z.instanceCount,je);mt.renderInstances(xt,Pt,Ho)}else mt.render(xt,Pt)};function ct(L,W,Z){L.transparent===!0&&L.side===2&&L.forceSinglePass===!1?(L.side=1,L.needsUpdate=!0,Yr(L,W,Z),L.side=0,L.needsUpdate=!0,Yr(L,W,Z),L.side=2):Yr(L,W,Z)}this.compile=function(L,W,Z=null){Z===null&&(Z=L),m=Ie.get(Z),m.init(),E.push(m),Z.traverseVisible(function(j){j.isLight&&j.layers.test(W.layers)&&(m.pushLight(j),j.castShadow&&m.pushShadow(j))}),L!==Z&&L.traverseVisible(function(j){j.isLight&&j.layers.test(W.layers)&&(m.pushLight(j),j.castShadow&&m.pushShadow(j))}),m.setupLights(_._useLegacyLights);const ee=new Set;return L.traverse(function(j){const ve=j.material;if(ve)if(Array.isArray(ve))for(let Ae=0;Ae<ve.length;Ae++){const we=ve[Ae];ct(we,Z,j),ee.add(we)}else ct(ve,Z,j),ee.add(ve)}),E.pop(),m=null,ee},this.compileAsync=function(L,W,Z=null){const ee=this.compile(L,W,Z);return new Promise(j=>{function ve(){if(ee.forEach(function(Ae){Me.get(Ae).currentProgram.isReady()&&ee.delete(Ae)}),ee.size===0){j(L);return}setTimeout(ve,10)}Re.get("KHR_parallel_shader_compile")!==null?ve():setTimeout(ve,10)})};let ht=null;function Dt(L){ht&&ht(L)}function $t(){zt.stop()}function ut(){zt.start()}const zt=new yl;zt.setAnimationLoop(Dt),typeof self<"u"&&zt.setContext(self),this.setAnimationLoop=function(L){ht=L,qe.setAnimationLoop(L),L===null?zt.stop():zt.start()},qe.addEventListener("sessionstart",$t),qe.addEventListener("sessionend",ut),this.render=function(L,W){if(W!==void 0&&W.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),W.parent===null&&W.matrixWorldAutoUpdate===!0&&W.updateMatrixWorld(),qe.enabled===!0&&qe.isPresenting===!0&&(qe.cameraAutoUpdate===!0&&qe.updateCamera(W),W=qe.getCamera()),L.isScene===!0&&L.onBeforeRender(_,L,W,A),m=Ie.get(L,E.length),m.init(),E.push(m),me.multiplyMatrices(W.projectionMatrix,W.matrixWorldInverse),G.setFromProjectionMatrix(me),ie=this.localClippingEnabled,J=ke.init(this.clippingPlanes,ie),v=_e.get(L,g.length),v.init(),g.push(v),Ii(L,W,0,_.sortObjects),v.finish(),_.sortObjects===!0&&v.sort(k,B),this.info.render.frame++,J===!0&&ke.beginShadows();const Z=m.state.shadowsArray;if(se.render(Z,L,W),J===!0&&ke.endShadows(),this.info.autoReset===!0&&this.info.reset(),Ze.render(v,L),m.setupLights(_._useLegacyLights),W.isArrayCamera){const ee=W.cameras;for(let j=0,ve=ee.length;j<ve;j++){const Ae=ee[j];vd(v,L,Ae,Ae.viewport)}}else vd(v,L,W);A!==null&&(I.updateMultisampleRenderTarget(A),I.updateRenderTargetMipmap(A)),L.isScene===!0&&L.onAfterRender(_,L,W),ze.resetDefaultState(),C=-1,S=null,E.pop(),E.length>0?m=E[E.length-1]:m=null,g.pop(),g.length>0?v=g[g.length-1]:v=null};function Ii(L,W,Z,ee){if(L.visible===!1)return;if(L.layers.test(W.layers)){if(L.isGroup)Z=L.renderOrder;else if(L.isLOD)L.autoUpdate===!0&&L.update(W);else if(L.isLight)m.pushLight(L),L.castShadow&&m.pushShadow(L);else if(L.isSprite){if(!L.frustumCulled||G.intersectsSprite(L)){ee&&be.setFromMatrixPosition(L.matrixWorld).applyMatrix4(me);const Ae=ae.update(L),we=L.material;we.visible&&v.push(L,Ae,we,Z,be.z,null)}}else if((L.isMesh||L.isLine||L.isPoints)&&(!L.frustumCulled||G.intersectsObject(L))){const Ae=ae.update(L),we=L.material;if(ee&&(L.boundingSphere!==void 0?(L.boundingSphere===null&&L.computeBoundingSphere(),be.copy(L.boundingSphere.center)):(Ae.boundingSphere===null&&Ae.computeBoundingSphere(),be.copy(Ae.boundingSphere.center)),be.applyMatrix4(L.matrixWorld).applyMatrix4(me)),Array.isArray(we)){const Oe=Ae.groups;for(let Ke=0,Be=Oe.length;Ke<Be;Ke++){const Ve=Oe[Ke],xt=we[Ve.materialIndex];xt&&xt.visible&&v.push(L,Ae,xt,Z,be.z,Ve)}}else we.visible&&v.push(L,Ae,we,Z,be.z,null)}}const ve=L.children;for(let Ae=0,we=ve.length;Ae<we;Ae++)Ii(ve[Ae],W,Z,ee)}function vd(L,W,Z,ee){const j=L.opaque,ve=L.transmissive,Ae=L.transparent;m.setupLightsView(Z),J===!0&&ke.setGlobalState(_.clippingPlanes,Z),ve.length>0&&$x(j,ve,W,Z),ee&&le.viewport(y.copy(ee)),j.length>0&&Xr(j,W,Z),ve.length>0&&Xr(ve,W,Z),Ae.length>0&&Xr(Ae,W,Z),le.buffers.depth.setTest(!0),le.buffers.depth.setMask(!0),le.buffers.color.setMask(!0),le.setPolygonOffset(!1)}function $x(L,W,Z,ee){if((Z.isScene===!0?Z.overrideMaterial:null)!==null)return;const ve=Ue.isWebGL2;oe===null&&(oe=new nn(1,1,{generateMipmaps:!0,type:Re.has("EXT_color_buffer_half_float")?1016:1009,minFilter:1008,samples:ve?4:0})),_.getDrawingBufferSize(Se),ve?oe.setSize(Se.x,Se.y):oe.setSize(ea(Se.x),ea(Se.y));const Ae=_.getRenderTarget();_.setRenderTarget(oe),_.getClearColor(Y),D=_.getClearAlpha(),D<1&&_.setClearColor(16777215,.5),_.clear();const we=_.toneMapping;_.toneMapping=0,Xr(L,Z,ee),I.updateMultisampleRenderTarget(oe),I.updateRenderTargetMipmap(oe);let Oe=!1;for(let Ke=0,Be=W.length;Ke<Be;Ke++){const Ve=W[Ke],xt=Ve.object,si=Ve.geometry,Pt=Ve.material,zi=Ve.group;if(Pt.side===2&&xt.layers.test(ee.layers)){const mt=Pt.side;Pt.side=1,Pt.needsUpdate=!0,_d(xt,Z,ee,si,Pt,zi),Pt.side=mt,Pt.needsUpdate=!0,Oe=!0}}Oe===!0&&(I.updateMultisampleRenderTarget(oe),I.updateRenderTargetMipmap(oe)),_.setRenderTarget(Ae),_.setClearColor(Y,D),_.toneMapping=we}function Xr(L,W,Z){const ee=W.isScene===!0?W.overrideMaterial:null;for(let j=0,ve=L.length;j<ve;j++){const Ae=L[j],we=Ae.object,Oe=Ae.geometry,Ke=ee===null?Ae.material:ee,Be=Ae.group;we.layers.test(Z.layers)&&_d(we,W,Z,Oe,Ke,Be)}}function _d(L,W,Z,ee,j,ve){L.onBeforeRender(_,W,Z,ee,j,ve),L.modelViewMatrix.multiplyMatrices(Z.matrixWorldInverse,L.matrixWorld),L.normalMatrix.getNormalMatrix(L.modelViewMatrix),j.onBeforeRender(_,W,Z,ee,L,ve),j.transparent===!0&&j.side===2&&j.forceSinglePass===!1?(j.side=1,j.needsUpdate=!0,_.renderBufferDirect(Z,W,ee,j,L,ve),j.side=0,j.needsUpdate=!0,_.renderBufferDirect(Z,W,ee,j,L,ve),j.side=2):_.renderBufferDirect(Z,W,ee,j,L,ve),L.onAfterRender(_,W,Z,ee,j,ve)}function Yr(L,W,Z){W.isScene!==!0&&(W=Te);const ee=Me.get(L),j=m.state.lights,ve=m.state.shadowsArray,Ae=j.state.version,we=ye.getParameters(L,j.state,ve,W,Z),Oe=ye.getProgramCacheKey(we);let Ke=ee.programs;ee.environment=L.isMeshStandardMaterial?W.environment:null,ee.fog=W.fog,ee.envMap=(L.isMeshStandardMaterial?K:M).get(L.envMap||ee.environment),Ke===void 0&&(L.addEventListener("dispose",pe),Ke=new Map,ee.programs=Ke);let Be=Ke.get(Oe);if(Be!==void 0){if(ee.currentProgram===Be&&ee.lightsStateVersion===Ae)return xd(L,we),Be}else we.uniforms=ye.getUniforms(L),L.onBuild(Z,we,_),L.onBeforeCompile(we,_),Be=ye.acquireProgram(we,Oe),Ke.set(Oe,Be),ee.uniforms=we.uniforms;const Ve=ee.uniforms;return(!L.isShaderMaterial&&!L.isRawShaderMaterial||L.clipping===!0)&&(Ve.clippingPlanes=ke.uniform),xd(L,we),ee.needsLights=Kx(L),ee.lightsStateVersion=Ae,ee.needsLights&&(Ve.ambientLightColor.value=j.state.ambient,Ve.lightProbe.value=j.state.probe,Ve.directionalLights.value=j.state.directional,Ve.directionalLightShadows.value=j.state.directionalShadow,Ve.spotLights.value=j.state.spot,Ve.spotLightShadows.value=j.state.spotShadow,Ve.rectAreaLights.value=j.state.rectArea,Ve.ltc_1.value=j.state.rectAreaLTC1,Ve.ltc_2.value=j.state.rectAreaLTC2,Ve.pointLights.value=j.state.point,Ve.pointLightShadows.value=j.state.pointShadow,Ve.hemisphereLights.value=j.state.hemi,Ve.directionalShadowMap.value=j.state.directionalShadowMap,Ve.directionalShadowMatrix.value=j.state.directionalShadowMatrix,Ve.spotShadowMap.value=j.state.spotShadowMap,Ve.spotLightMatrix.value=j.state.spotLightMatrix,Ve.spotLightMap.value=j.state.spotLightMap,Ve.pointShadowMap.value=j.state.pointShadowMap,Ve.pointShadowMatrix.value=j.state.pointShadowMatrix),ee.currentProgram=Be,ee.uniformsList=null,Be}function Ed(L){if(L.uniformsList===null){const W=L.currentProgram.getUniforms();L.uniformsList=nr.seqWithValue(W.seq,L.uniforms)}return L.uniformsList}function xd(L,W){const Z=Me.get(L);Z.outputColorSpace=W.outputColorSpace,Z.batching=W.batching,Z.instancing=W.instancing,Z.instancingColor=W.instancingColor,Z.skinning=W.skinning,Z.morphTargets=W.morphTargets,Z.morphNormals=W.morphNormals,Z.morphColors=W.morphColors,Z.morphTargetsCount=W.morphTargetsCount,Z.numClippingPlanes=W.numClippingPlanes,Z.numIntersection=W.numClipIntersection,Z.vertexAlphas=W.vertexAlphas,Z.vertexTangents=W.vertexTangents,Z.toneMapping=W.toneMapping}function zx(L,W,Z,ee,j){W.isScene!==!0&&(W=Te),I.resetTextureUnits();const ve=W.fog,Ae=ee.isMeshStandardMaterial?W.environment:null,we=A===null?_.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ci,Oe=(ee.isMeshStandardMaterial?K:M).get(ee.envMap||Ae),Ke=ee.vertexColors===!0&&!!Z.attributes.color&&Z.attributes.color.itemSize===4,Be=!!Z.attributes.tangent&&(!!ee.normalMap||ee.anisotropy>0),Ve=!!Z.morphAttributes.position,xt=!!Z.morphAttributes.normal,si=!!Z.morphAttributes.color;let Pt=0;ee.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(Pt=_.toneMapping);const zi=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,mt=zi!==void 0?zi.length:0,je=Me.get(ee),Ho=m.state.lights;if(J===!0&&(ie===!0||L!==S)){const hi=L===S&&ee.id===C;ke.setState(ee,L,hi)}let _t=!1;ee.version===je.__version?(je.needsLights&&je.lightsStateVersion!==Ho.state.version||je.outputColorSpace!==we||j.isBatchedMesh&&je.batching===!1||!j.isBatchedMesh&&je.batching===!0||j.isInstancedMesh&&je.instancing===!1||!j.isInstancedMesh&&je.instancing===!0||j.isSkinnedMesh&&je.skinning===!1||!j.isSkinnedMesh&&je.skinning===!0||j.isInstancedMesh&&je.instancingColor===!0&&j.instanceColor===null||j.isInstancedMesh&&je.instancingColor===!1&&j.instanceColor!==null||je.envMap!==Oe||ee.fog===!0&&je.fog!==ve||je.numClippingPlanes!==void 0&&(je.numClippingPlanes!==ke.numPlanes||je.numIntersection!==ke.numIntersection)||je.vertexAlphas!==Ke||je.vertexTangents!==Be||je.morphTargets!==Ve||je.morphNormals!==xt||je.morphColors!==si||je.toneMapping!==Pt||Ue.isWebGL2===!0&&je.morphTargetsCount!==mt)&&(_t=!0):(_t=!0,je.__version=ee.version);let _n=je.currentProgram;_t===!0&&(_n=Yr(ee,W,j));let Sd=!1,bs=!1,$o=!1;const Bt=_n.getUniforms(),En=je.uniforms;if(le.useProgram(_n.program)&&(Sd=!0,bs=!0,$o=!0),ee.id!==C&&(C=ee.id,bs=!0),Sd||S!==L){Bt.setValue(q,"projectionMatrix",L.projectionMatrix),Bt.setValue(q,"viewMatrix",L.matrixWorldInverse);const hi=Bt.map.cameraPosition;hi!==void 0&&hi.setValue(q,be.setFromMatrixPosition(L.matrixWorld)),Ue.logarithmicDepthBuffer&&Bt.setValue(q,"logDepthBufFC",2/(Math.log(L.far+1)/Math.LN2)),(ee.isMeshPhongMaterial||ee.isMeshToonMaterial||ee.isMeshLambertMaterial||ee.isMeshBasicMaterial||ee.isMeshStandardMaterial||ee.isShaderMaterial)&&Bt.setValue(q,"isOrthographic",L.isOrthographicCamera===!0),S!==L&&(S=L,bs=!0,$o=!0)}if(j.isSkinnedMesh){Bt.setOptional(q,j,"bindMatrix"),Bt.setOptional(q,j,"bindMatrixInverse");const hi=j.skeleton;hi&&(Ue.floatVertexTextures?(hi.boneTexture===null&&hi.computeBoneTexture(),Bt.setValue(q,"boneTexture",hi.boneTexture,I)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}j.isBatchedMesh&&(Bt.setOptional(q,j,"batchingTexture"),Bt.setValue(q,"batchingTexture",j._matricesTexture,I));const zo=Z.morphAttributes;if((zo.position!==void 0||zo.normal!==void 0||zo.color!==void 0&&Ue.isWebGL2===!0)&&Qe.update(j,Z,_n),(bs||je.receiveShadow!==j.receiveShadow)&&(je.receiveShadow=j.receiveShadow,Bt.setValue(q,"receiveShadow",j.receiveShadow)),ee.isMeshGouraudMaterial&&ee.envMap!==null&&(En.envMap.value=Oe,En.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),bs&&(Bt.setValue(q,"toneMappingExposure",_.toneMappingExposure),je.needsLights&&Wx(En,$o),ve&&ee.fog===!0&&ue.refreshFogUniforms(En,ve),ue.refreshMaterialUniforms(En,ee,$,O,oe),nr.upload(q,Ed(je),En,I)),ee.isShaderMaterial&&ee.uniformsNeedUpdate===!0&&(nr.upload(q,Ed(je),En,I),ee.uniformsNeedUpdate=!1),ee.isSpriteMaterial&&Bt.setValue(q,"center",j.center),Bt.setValue(q,"modelViewMatrix",j.modelViewMatrix),Bt.setValue(q,"normalMatrix",j.normalMatrix),Bt.setValue(q,"modelMatrix",j.matrixWorld),ee.isShaderMaterial||ee.isRawShaderMaterial){const hi=ee.uniformsGroups;for(let Wo=0,Xx=hi.length;Wo<Xx;Wo++)if(Ue.isWebGL2){const yd=hi[Wo];it.update(yd,_n),it.bind(yd,_n)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return _n}function Wx(L,W){L.ambientLightColor.needsUpdate=W,L.lightProbe.needsUpdate=W,L.directionalLights.needsUpdate=W,L.directionalLightShadows.needsUpdate=W,L.pointLights.needsUpdate=W,L.pointLightShadows.needsUpdate=W,L.spotLights.needsUpdate=W,L.spotLightShadows.needsUpdate=W,L.rectAreaLights.needsUpdate=W,L.hemisphereLights.needsUpdate=W}function Kx(L){return L.isMeshLambertMaterial||L.isMeshToonMaterial||L.isMeshPhongMaterial||L.isMeshStandardMaterial||L.isShadowMaterial||L.isShaderMaterial&&L.lights===!0}this.getActiveCubeFace=function(){return b},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(L,W,Z){Me.get(L.texture).__webglTexture=W,Me.get(L.depthTexture).__webglTexture=Z;const ee=Me.get(L);ee.__hasExternalTextures=!0,ee.__hasExternalTextures&&(ee.__autoAllocateDepthBuffer=Z===void 0,ee.__autoAllocateDepthBuffer||Re.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),ee.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(L,W){const Z=Me.get(L);Z.__webglFramebuffer=W,Z.__useDefaultFramebuffer=W===void 0},this.setRenderTarget=function(L,W=0,Z=0){A=L,b=W,R=Z;let ee=!0,j=null,ve=!1,Ae=!1;if(L){const Oe=Me.get(L);Oe.__useDefaultFramebuffer!==void 0?(le.bindFramebuffer(q.FRAMEBUFFER,null),ee=!1):Oe.__webglFramebuffer===void 0?I.setupRenderTarget(L):Oe.__hasExternalTextures&&I.rebindTextures(L,Me.get(L.texture).__webglTexture,Me.get(L.depthTexture).__webglTexture);const Ke=L.texture;(Ke.isData3DTexture||Ke.isDataArrayTexture||Ke.isCompressedArrayTexture)&&(Ae=!0);const Be=Me.get(L).__webglFramebuffer;L.isWebGLCubeRenderTarget?(Array.isArray(Be[W])?j=Be[W][Z]:j=Be[W],ve=!0):Ue.isWebGL2&&L.samples>0&&I.useMultisampledRTT(L)===!1?j=Me.get(L).__webglMultisampledFramebuffer:Array.isArray(Be)?j=Be[Z]:j=Be,y.copy(L.viewport),w.copy(L.scissor),N=L.scissorTest}else y.copy(X).multiplyScalar($).floor(),w.copy(P).multiplyScalar($).floor(),N=V;if(le.bindFramebuffer(q.FRAMEBUFFER,j)&&Ue.drawBuffers&&ee&&le.drawBuffers(L,j),le.viewport(y),le.scissor(w),le.setScissorTest(N),ve){const Oe=Me.get(L.texture);q.framebufferTexture2D(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_CUBE_MAP_POSITIVE_X+W,Oe.__webglTexture,Z)}else if(Ae){const Oe=Me.get(L.texture),Ke=W||0;q.framebufferTextureLayer(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,Oe.__webglTexture,Z||0,Ke)}C=-1},this.readRenderTargetPixels=function(L,W,Z,ee,j,ve,Ae){if(!(L&&L.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let we=Me.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ae!==void 0&&(we=we[Ae]),we){le.bindFramebuffer(q.FRAMEBUFFER,we);try{const Oe=L.texture,Ke=Oe.format,Be=Oe.type;if(Ke!==1023&&xe.convert(Ke)!==q.getParameter(q.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const Ve=Be===1016&&(Re.has("EXT_color_buffer_half_float")||Ue.isWebGL2&&Re.has("EXT_color_buffer_float"));if(Be!==1009&&xe.convert(Be)!==q.getParameter(q.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Be===1015&&(Ue.isWebGL2||Re.has("OES_texture_float")||Re.has("WEBGL_color_buffer_float")))&&!Ve){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}W>=0&&W<=L.width-ee&&Z>=0&&Z<=L.height-j&&q.readPixels(W,Z,ee,j,xe.convert(Ke),xe.convert(Be),ve)}finally{const Oe=A!==null?Me.get(A).__webglFramebuffer:null;le.bindFramebuffer(q.FRAMEBUFFER,Oe)}}},this.copyFramebufferToTexture=function(L,W,Z=0){const ee=Math.pow(2,-Z),j=Math.floor(W.image.width*ee),ve=Math.floor(W.image.height*ee);I.setTexture2D(W,0),q.copyTexSubImage2D(q.TEXTURE_2D,Z,0,0,L.x,L.y,j,ve),le.unbindTexture()},this.copyTextureToTexture=function(L,W,Z,ee=0){const j=W.image.width,ve=W.image.height,Ae=xe.convert(Z.format),we=xe.convert(Z.type);I.setTexture2D(Z,0),q.pixelStorei(q.UNPACK_FLIP_Y_WEBGL,Z.flipY),q.pixelStorei(q.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Z.premultiplyAlpha),q.pixelStorei(q.UNPACK_ALIGNMENT,Z.unpackAlignment),W.isDataTexture?q.texSubImage2D(q.TEXTURE_2D,ee,L.x,L.y,j,ve,Ae,we,W.image.data):W.isCompressedTexture?q.compressedTexSubImage2D(q.TEXTURE_2D,ee,L.x,L.y,W.mipmaps[0].width,W.mipmaps[0].height,Ae,W.mipmaps[0].data):q.texSubImage2D(q.TEXTURE_2D,ee,L.x,L.y,Ae,we,W.image),ee===0&&Z.generateMipmaps&&q.generateMipmap(q.TEXTURE_2D),le.unbindTexture()},this.copyTextureToTexture3D=function(L,W,Z,ee,j=0){if(_.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ve=L.max.x-L.min.x+1,Ae=L.max.y-L.min.y+1,we=L.max.z-L.min.z+1,Oe=xe.convert(ee.format),Ke=xe.convert(ee.type);let Be;if(ee.isData3DTexture)I.setTexture3D(ee,0),Be=q.TEXTURE_3D;else if(ee.isDataArrayTexture||ee.isCompressedArrayTexture)I.setTexture2DArray(ee,0),Be=q.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}q.pixelStorei(q.UNPACK_FLIP_Y_WEBGL,ee.flipY),q.pixelStorei(q.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ee.premultiplyAlpha),q.pixelStorei(q.UNPACK_ALIGNMENT,ee.unpackAlignment);const Ve=q.getParameter(q.UNPACK_ROW_LENGTH),xt=q.getParameter(q.UNPACK_IMAGE_HEIGHT),si=q.getParameter(q.UNPACK_SKIP_PIXELS),Pt=q.getParameter(q.UNPACK_SKIP_ROWS),zi=q.getParameter(q.UNPACK_SKIP_IMAGES),mt=Z.isCompressedTexture?Z.mipmaps[j]:Z.image;q.pixelStorei(q.UNPACK_ROW_LENGTH,mt.width),q.pixelStorei(q.UNPACK_IMAGE_HEIGHT,mt.height),q.pixelStorei(q.UNPACK_SKIP_PIXELS,L.min.x),q.pixelStorei(q.UNPACK_SKIP_ROWS,L.min.y),q.pixelStorei(q.UNPACK_SKIP_IMAGES,L.min.z),Z.isDataTexture||Z.isData3DTexture?q.texSubImage3D(Be,j,W.x,W.y,W.z,ve,Ae,we,Oe,Ke,mt.data):Z.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),q.compressedTexSubImage3D(Be,j,W.x,W.y,W.z,ve,Ae,we,Oe,mt.data)):q.texSubImage3D(Be,j,W.x,W.y,W.z,ve,Ae,we,Oe,Ke,mt),q.pixelStorei(q.UNPACK_ROW_LENGTH,Ve),q.pixelStorei(q.UNPACK_IMAGE_HEIGHT,xt),q.pixelStorei(q.UNPACK_SKIP_PIXELS,si),q.pixelStorei(q.UNPACK_SKIP_ROWS,Pt),q.pixelStorei(q.UNPACK_SKIP_IMAGES,zi),j===0&&ee.generateMipmaps&&q.generateMipmap(Be),le.unbindTexture()},this.initTexture=function(L){L.isCubeTexture?I.setTextureCube(L,0):L.isData3DTexture?I.setTexture3D(L,0):L.isDataArrayTexture||L.isCompressedArrayTexture?I.setTexture2DArray(L,0):I.setTexture2D(L,0),le.unbindTexture()},this.resetState=function(){b=0,R=0,A=null,le.reset(),ze.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return 2e3}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===jr?"display-p3":"srgb",t.unpackColorSpace=st.workingColorSpace===Rs?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===Mt?3001:3e3}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===3001?Mt:Ci}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class Zg extends Ql{}Zg.prototype.isWebGL1Renderer=!0;class Jg extends Jt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t}}class e0 extends Xt{constructor(e,t,i,n,r,a,o,l,c){super(e,t,i,n,r,a,o,l,c),this.isVideoTexture=!0,this.minFilter=a!==void 0?a:1006,this.magFilter=r!==void 0?r:1006,this.generateMipmaps=!1;const h=this;function u(){h.needsUpdate=!0,e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(u)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class rr extends ji{constructor(e=1,t=32,i=16,n=0,r=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const l=Math.min(a+o,Math.PI);let c=0;const h=[],u=new Q,d=new Q,f=[],p=[],v=[],m=[];for(let g=0;g<=i;g++){const E=[],_=g/i;let T=0;g===0&&a===0?T=.5/t:g===i&&l===Math.PI&&(T=-.5/t);for(let b=0;b<=t;b++){const R=b/t;u.x=-e*Math.cos(n+R*r)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(n+R*r)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),v.push(d.x,d.y,d.z),m.push(R+T,1-_),E.push(c++)}h.push(E)}for(let g=0;g<i;g++)for(let E=0;E<t;E++){const _=h[g][E+1],T=h[g][E],b=h[g+1][E],R=h[g+1][E+1];(g!==0||a>0)&&f.push(_,T,R),(g!==i-1||l<Math.PI)&&f.push(T,b,R)}this.setIndex(f),this.setAttribute("position",new xi(p,3)),this.setAttribute("normal",new xi(v,3)),this.setAttribute("uv",new xi(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new rr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:qr}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=qr);class Vn{static createButton(e){const t=document.createElement("button");function i(){let l=null;async function c(d){d.addEventListener("end",h),await e.xr.setSession(d),t.textContent="EXIT VR",l=d}function h(){l.removeEventListener("end",h),t.textContent="ENTER VR",l=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="ENTER VR";const u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","layers"]};t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){l===null?navigator.xr.requestSession("immersive-vr",u).then(c):(l.end(),navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",u).then(c))},navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",u).then(c)}function n(){t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function r(){n(),t.textContent="VR NOT SUPPORTED"}function a(l){n(),console.warn("Exception when trying to call xr.isSessionSupported",l),t.textContent="VR NOT ALLOWED"}function o(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return t.id="VRButton",t.style.display="none",o(t),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),l&&Vn.xrSessionIsGranted&&t.click()}).catch(a),t;{const l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",o(l),l}}static registerSessionGrantedListener(){if(typeof navigator<"u"&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{Vn.xrSessionIsGranted=!0})}}}Vn.xrSessionIsGranted=!1,Vn.registerSessionGrantedListener();const Ui={"180-sbs":{geom:"sphere180",split:"sbs",stereo:!0},"180-mono":{geom:"sphere180",split:"mono",stereo:!1},"360-mono":{geom:"sphere360",split:"mono",stereo:!1},"360-sbs":{geom:"sphere360",split:"sbs",stereo:!0},"360-tb":{geom:"sphere360",split:"tb",stereo:!0},"flat-2d":{geom:"plane",split:"mono",stereo:!1,flat:!0,aspect:"full"},"flat-sbs-full":{geom:"plane",split:"sbs",stereo:!0,flat:!0,aspect:"per-eye"},"flat-sbs-half":{geom:"plane",split:"sbs",stereo:!0,flat:!0,aspect:"full"}},Zl=[{value:"180-sbs",label:"180° SBS (VR180)"},{value:"180-mono",label:"180° Mono"},{value:"360-mono",label:"360° Mono"},{value:"360-sbs",label:"360° SBS"},{value:"360-tb",label:"360° Top-Bottom"},{value:"flat-2d",label:"Flat 2D (regular movie)"},{value:"flat-sbs-full",label:"Flat 3D — Full SBS"},{value:"flat-sbs-half",label:"Flat 3D — Half SBS"}];function t0(s){var e;return!!((e=Ui[s])!=null&&e.flat)}function Jl(s){const e=String(s).toLowerCase(),t=/(^|[^a-z])(tb|ou|top.?bottom|over.?under)([^a-z]|$)/.test(e),i=/(sbs|side.?by.?side)/.test(e);return e.includes("360")?t?"360-tb":i?"360-sbs":"360-mono":e.includes("180")||e.includes("vr180")?e.includes("mono")?"180-mono":"180-sbs":i?e.includes("half")?"flat-sbs-half":"flat-sbs-full":null}class ec{constructor(e){this.scene=new Jg,this.meshes=[],this.frameCbs=[],this.animate=()=>{for(const l of this.frameCbs)l();this.renderer.render(this.scene,this.camera)},this.resize=()=>{const l=this.w(),c=this.h();this.camera.aspect=l/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(l,c,!1)};const{canvas:t,video:i,projection:n="180-sbs",swapEyes:r=!1,fov:a=70,supersampling:o=1.5}=e;this.canvas=t,this.video=i,this.currentMode=Ui[n]?n:"180-sbs",this.currentSwap=r,this.renderer=new Ql({canvas:t,antialias:!0}),this.renderer.setPixelRatio(this.pixelRatioFor(o)),this.renderer.setSize(this.w(),this.h(),!1),this.renderer.xr.enabled=!0,this.camera=new oi(a,this.w()/this.h(),.1,1e3),this.camera.position.set(0,0,0),this.camera.layers.enable(1),this.maxAnisotropy=this.renderer.capabilities.getMaxAnisotropy(),this.texture=new e0(i),this.texture.colorSpace=Mt,this.texture.minFilter=1006,this.texture.magFilter=1006,this.texture.anisotropy=this.maxAnisotropy,this.applyProjection(this.currentMode,this.currentSwap),i.addEventListener("loadedmetadata",()=>{Ui[this.currentMode].flat&&this.applyProjection(this.currentMode,this.currentSwap)}),this.renderer.setAnimationLoop(this.animate),this.vrButton=Vn.createButton(this.renderer),this.ro=new ResizeObserver(()=>this.resize()),this.ro.observe(t)}w(){return this.canvas.clientWidth||1}h(){return this.canvas.clientHeight||1}pixelRatioFor(e){return Math.min(window.devicePixelRatio*e,4)}planeAspect(e){const t=this.video.videoWidth,i=this.video.videoHeight;return!t||!i?1.7777777777777777:Ui[e].aspect==="per-eye"?t/2/i:t/i}buildGeometry(e){const t=Ui[e].geom;if(t==="sphere180"){const a=new rr(500,60,40,-Math.PI,Math.PI,0,Math.PI);return a.scale(-1,1,1),a}if(t==="sphere360"){const a=new rr(500,60,40);return a.scale(-1,1,1),a}const i=2.4,n=i*this.planeAspect(e),r=new Js(n,i);return r.translate(0,0,-2),r}splitUV(e,t,i){if(t==="mono")return;const n=e.attributes.uv.array;for(let r=0;r<n.length;r+=2)t==="sbs"?n[r]=n[r]*.5+(i==="right"?.5:0):t==="tb"&&(n[r+1]=n[r+1]*.5+(i==="left"?.5:0));e.attributes.uv.needsUpdate=!0}clearMeshes(){for(const e of this.meshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.meshes.length=0}applyProjection(e,t){Ui[e]||(e="180-sbs"),this.clearMeshes();const i=Ui[e];if(i.stereo){const n=this.buildGeometry(e);this.splitUV(n,i.split,"left");const r=this.buildGeometry(e);this.splitUV(r,i.split,"right");const a=new mi(n,new hs({map:this.texture})),o=new mi(r,new hs({map:this.texture}));a.layers.set(t?2:1),o.layers.set(t?1:2),this.scene.add(a,o),this.meshes.push(a,o)}else{const n=new mi(this.buildGeometry(e),new hs({map:this.texture}));n.layers.set(0),this.scene.add(n),this.meshes.push(n)}this.currentMode=e,this.currentSwap=t}setProjection(e){this.applyProjection(e,this.currentSwap)}setSwapEyes(e){this.applyProjection(this.currentMode,e)}setFov(e){this.camera.fov=e,this.camera.updateProjectionMatrix()}setSupersampling(e){this.renderer.setPixelRatio(this.pixelRatioFor(e)),this.renderer.setSize(this.w(),this.h(),!1)}getProjection(){return this.currentMode}isFlat(){return!!Ui[this.currentMode].flat}onFrame(e){this.frameCbs.push(e)}pauseRendering(){this.renderer.setAnimationLoop(null)}resumeRendering(){this.renderer.setAnimationLoop(this.animate)}dispose(){this.ro.disconnect(),this.renderer.setAnimationLoop(null),this.texture.dispose(),this.clearMeshes(),this.renderer.dispose()}}const tc=Math.PI/180;function ic(s,e){return{lon:Math.max(-90,Math.min(90,s)),lat:Math.max(-85,Math.min(85,e))}}class nc{constructor(e,t,i={}){this.camera=e,this.dom=t,this.lon=0,this.lat=0,this.dragging=!1,this.px=0,this.py=0,this.enabled=!0,this.onDown=n=>{this.enabled&&(this.dragging=!0,this.px=n.clientX,this.py=n.clientY,this.capture("setPointerCapture",n.pointerId))},this.onMove=n=>{if(!this.dragging)return;const r=n.clientX-this.px,a=n.clientY-this.py;this.px=n.clientX,this.py=n.clientY,{lon:this.lon,lat:this.lat}=ic(this.lon-r*.15,this.lat+a*.15)},this.onUp=n=>{this.dragging=!1,this.capture("releasePointerCapture",n.pointerId)},this.isPresenting=i.isPresenting??(()=>!1),this.dom.addEventListener("pointerdown",this.onDown),this.dom.addEventListener("pointermove",this.onMove),this.dom.addEventListener("pointerup",this.onUp),this.dom.addEventListener("pointercancel",this.onUp)}capture(e,t){var i,n;try{(n=(i=this.dom)[e])==null||n.call(i,t)}catch{}}update(){if(this.isPresenting()||!this.enabled)return;const e=(90-this.lat)*tc,t=this.lon*tc;this.camera.lookAt(Math.sin(e)*Math.sin(t),Math.cos(e),-Math.sin(e)*Math.cos(t))}reset(){this.lon=0,this.lat=0}setEnabled(e){this.enabled=e,e||(this.lon=0,this.lat=0,this.camera.lookAt(0,0,-1))}getAngles(){return{lon:this.lon,lat:this.lat}}dispose(){this.dom.removeEventListener("pointerdown",this.onDown),this.dom.removeEventListener("pointermove",this.onMove),this.dom.removeEventListener("pointerup",this.onUp),this.dom.removeEventListener("pointercancel",this.onUp)}}class sc{constructor(){this.hls=null}async attach(e,t,i={}){this.dispose();const n=i.crossOrigin===void 0?"anonymous":i.crossOrigin;n===null?e.removeAttribute("crossorigin"):e.crossOrigin=n,e.playsInline=!0;const{url:r,format:a}=t,o=a==="hls"||a==="dash",l=e.canPlayType("application/vnd.apple.mpegurl")!=="";return new Promise((c,h)=>{const u=()=>{e.removeEventListener("loadedmetadata",d),e.removeEventListener("error",f)},d=()=>{u(),c()},f=()=>{u();const p=e.error?e.error.code:"unknown";h(new Error(`Video failed to load (media error ${p}). Is the source reachable and CORS-clean?`))};e.addEventListener("loadedmetadata",d),e.addEventListener("error",f),o&&!l?Promise.resolve().then(()=>Hx).then(({default:p})=>{if(!p.isSupported()){u(),h(new Error("HLS/DASH stream needs hls.js, which is unsupported in this browser."));return}this.hls=new p({enableWorker:!0}),this.hls.on(p.Events.ERROR,(v,m)=>{m.fatal&&(u(),this.dispose(),h(new Error(`HLS fatal error: ${m.type} / ${m.details}`)))}),this.hls.loadSource(r),this.hls.attachMedia(e)}).catch(()=>{u(),h(new Error('This looks like an HLS/DASH stream but hls.js could not be loaded. Install "hls.js".'))}):(e.src=r,e.load())})}dispose(){this.hls&&(this.hls.destroy(),this.hls=null)}}function rc(s){let e=s;try{e=new URL(s).pathname}catch{}const t=e.toLowerCase();return t.endsWith(".m3u8")?"hls":t.endsWith(".mpd")?"dash":"progressive"}const i0={progressive:"/proxy/stream",hls:"/proxy/hls/manifest.m3u8",dash:"/proxy/mpd/manifest.m3u8"};function ac(s,e){const t=rc(s);if(!e||!e.url)return{url:s,format:t};const i=e.url.replace(/\/+$/,""),n=new URLSearchParams;n.set("d",s),e.apiPassword&&n.set("api_password",e.apiPassword);for(const[r,a]of Object.entries(e.headers??{}))a!=null&&a!==""&&n.set(`h_${r}`,a);return{url:`${i}${i0[t]}?${n.toString()}`,format:t}}function oc(s){if(!Number.isFinite(s)||s<0)return"0:00";const e=Math.floor(s%60),t=Math.floor(s/60%60),i=Math.floor(s/3600),n=String(e).padStart(2,"0");return i>0?`${i}:${String(t).padStart(2,"0")}:${n}`:`${t}:${n}`}function Je(s,e={},t=[]){const i=document.createElement(s),{class:n,...r}=e;n&&(i.className=n),Object.assign(i,r);for(const a of t)i.append(a);return i}class n0{constructor(e,t){this.nodes=[],this.disposers=[];const i=t.video,n=Je("button",{class:"tvp-btn tvp-play",title:"Play/Pause",textContent:"▶"}),r=Je("input",{class:"tvp-seek",type:"range",min:"0",max:"1000",value:"0"}),a=Je("span",{class:"tvp-time",textContent:"0:00 / 0:00"}),o=Je("button",{class:"tvp-btn tvp-mute",title:"Volume",textContent:"🔊"}),l=Je("input",{class:"tvp-volume",type:"range",min:"0",max:"1",step:"0.01",value:"1"}),c=Je("div",{class:"tvp-volpopup",hidden:!0},[l]),h=Je("span",{class:"tvp-volwrap"},[o,c]),u=Je("span",{class:"tvp-vrslot"}),d=Je("button",{class:"tvp-btn tvp-projbtn",title:"Projection",textContent:"🌐"}),f=Je("div",{class:"tvp-projmenu",hidden:!0});for(const P of Zl){const V=Je("button",{textContent:P.label});V.dataset.mode=P.value,f.append(V)}const p=Je("span",{class:"tvp-projwrap"},[d,f]),v=Je("button",{class:"tvp-btn tvp-settingsbtn",title:"Settings",textContent:"⚙"}),m=Je("button",{class:"tvp-btn tvp-fullscreen",title:"Fullscreen",textContent:"⛶"}),g=Je("footer",{class:"tvp-controls"},[n,r,a,h,u,p,v,m]),E=Je("input",{type:"checkbox",checked:t.initial.swapEyes}),_=Je("input",{type:"range",min:"30",max:"100",step:"1",value:String(t.initial.fov)}),T=Je("span",{textContent:String(t.initial.fov)}),b=Je("input",{type:"range",min:"1",max:"2",step:"0.25",value:String(t.initial.supersampling)}),R=Je("span",{textContent:String(t.initial.supersampling)}),A=Je("input",{type:"checkbox",checked:t.proxy.enabled}),C=Je("input",{type:"text",value:t.proxy.url,placeholder:"http://localhost:8888",spellcheck:!1}),S=Je("input",{type:"password",value:t.proxy.apiPassword,placeholder:"API password"}),y=Je("section",{class:"tvp-settings"},[Je("label",{class:"row"},[E,"Swap eyes (if depth looks wrong)"]),Je("label",{},[lc("Field of view (zoom): ",T,"°"),_]),Je("label",{},[lc("Supersampling: ",R,"× (sharpness)"),b]),Je("hr",{class:"tvp-sep"}),Je("label",{class:"row"},[A,"Use CORS proxy"]),Je("label",{},["Proxy URL",C]),Je("label",{},["API password",S])]),w=Je("div",{class:"tvp-toast"});this.nodes.push(g,y,w);for(const P of this.nodes)e.append(P);const N=(P,V,G,J)=>{P.addEventListener(V,G,J),this.disposers.push(()=>P.removeEventListener(V,G,J))},Y=P=>r.style.setProperty("--seek",`${P}%`),D=()=>{c.hidden=!0,f.hidden=!0,y.classList.remove("open")};N(n,"click",()=>{i.paused?i.play():i.pause()}),N(i,"play",()=>{n.textContent="⏸"}),N(i,"pause",()=>{n.textContent="▶"}),N(i,"timeupdate",()=>{if(i.duration){const P=i.currentTime/i.duration*100;r.value=String(P*10),Y(P),a.textContent=`${oc(i.currentTime)} / ${oc(i.duration)}`}}),N(r,"input",()=>{Y(Number(r.value)/10),i.duration&&(i.currentTime=Number(r.value)/1e3*i.duration)}),N(o,"click",P=>{P.stopPropagation();const V=c.hidden;D(),c.hidden=!V}),N(l,"input",()=>{i.volume=Number(l.value),i.muted=i.volume===0,o.textContent=i.muted?"🔇":"🔊"});const F=()=>{const P=t.getProjection();let V="Projection";f.querySelectorAll("button").forEach(G=>{const J=G.dataset.mode===P;G.classList.toggle("active",J),J&&(V=`Projection: ${G.textContent}`)}),d.title=V};N(d,"click",P=>{P.stopPropagation();const V=f.hidden;D(),f.hidden=!V}),N(f,"click",P=>{const V=P.target.closest("button[data-mode]");V&&(t.setProjection(V.dataset.mode),F(),f.hidden=!0)}),F(),N(v,"click",P=>{P.stopPropagation();const V=!y.classList.contains("open");D(),y.classList.toggle("open",V)}),N(E,"change",()=>t.setSwapEyes(E.checked)),N(_,"input",()=>{const P=Number(_.value);T.textContent=String(P),t.setFov(P)}),N(b,"input",()=>{const P=Number(b.value);R.textContent=String(P),t.setSupersampling(P)});const O=()=>t.setProxy({url:C.value.trim(),apiPassword:S.value,enabled:A.checked});N(A,"change",O),N(C,"change",O),N(S,"change",O),N(t.surface,"wheel",P=>{P.preventDefault();const V=Math.max(30,Math.min(100,Number(_.value)+Math.sign(P.deltaY)*3));_.value=String(V),T.textContent=String(V),t.setFov(V)},{passive:!1}),N(m,"click",()=>{var V,G;const P=t.fullscreenTarget;document.fullscreenElement?(G=document.exitFullscreen)==null||G.call(document):(V=P.requestFullscreen)==null||V.call(P)}),N(document,"click",P=>{const V=P.composedPath(),G=J=>V.includes(J);[c,o,f,d,y,v].some(G)||D()});let $=0;const k=()=>!c.hidden||!f.hidden||y.classList.contains("open"),B=()=>{k()||g.classList.add("tvp-hidden")},X=()=>{g.classList.remove("tvp-hidden"),clearTimeout($),$=window.setTimeout(B,5e3)};N(t.fullscreenTarget,"pointermove",X),N(t.fullscreenTarget,"pointerdown",X),N(t.fullscreenTarget,"pointerleave",()=>{clearTimeout($),B()}),this.disposers.push(()=>clearTimeout($)),X(),t.vrSupported().then(P=>{P&&(Object.assign(t.vrButton.style,{position:"static",left:"auto",bottom:"auto",transform:"none",margin:"0"}),u.append(t.vrButton))})}dispose(){for(const e of this.disposers)e();for(const e of this.nodes)e.remove()}}function lc(s,e,t){const i=document.createDocumentFragment();return i.append(s,e,t),i}const cc=":host,:host *,.tvp,.tvp *{box-sizing:border-box}.tvp-canvas{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab}.tvp-canvas:active{cursor:grabbing}.tvp-video{display:none}.tvp-controls{position:absolute;left:0;right:0;bottom:0;display:flex;align-items:center;gap:10px;padding:12px;background:linear-gradient(transparent,#000c);z-index:5;font:14px system-ui,Segoe UI,Roboto,sans-serif;color:#e8eaed;transition:opacity .3s}.tvp-controls.tvp-hidden{opacity:0;pointer-events:none}.tvp-btn{padding:4px;border:0;background:none;color:#e8eaed;cursor:pointer;font-size:22px;line-height:1}.tvp-btn:hover{opacity:.7}.tvp-seek{flex:1;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:14px;background:transparent;cursor:pointer;margin:0}.tvp-seek::-webkit-slider-runnable-track{height:4px;border-radius:2px;background:linear-gradient(to right,#4f8cff var(--seek,0%),#3a4150 var(--seek,0%))}.tvp-seek::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-top:-4px;width:12px;height:12px;border-radius:50%;background:#fff;cursor:pointer}.tvp-seek::-moz-range-track{height:4px;border-radius:2px;background:#3a4150}.tvp-seek::-moz-range-progress{height:4px;border-radius:2px;background:#4f8cff}.tvp-seek::-moz-range-thumb{width:12px;height:12px;border:0;border-radius:50%;background:#fff;cursor:pointer}.tvp-time{font-variant-numeric:tabular-nums;min-width:96px;text-align:center;color:#cfd6e2}.tvp-volwrap,.tvp-projwrap{position:relative;display:inline-flex}.tvp-volpopup{position:absolute;bottom:calc(100% + 10px);left:50%;transform:translate(-50%);width:40px;height:132px;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:10px;z-index:8;box-shadow:0 8px 24px #0009}.tvp-volpopup[hidden]{display:none}.tvp-volume{position:absolute;top:50%;left:50%;width:104px;height:14px;margin:0;transform:translate(-50%,-50%) rotate(-90deg);-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;cursor:pointer}.tvp-volume::-webkit-slider-runnable-track{height:4px;border-radius:2px;background:#3a4150}.tvp-volume::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-top:-4px;width:12px;height:12px;border-radius:50%;background:#fff;cursor:pointer}.tvp-volume::-moz-range-track{height:4px;border-radius:2px;background:#3a4150}.tvp-volume::-moz-range-thumb{width:12px;height:12px;border:0;border-radius:50%;background:#fff;cursor:pointer}.tvp-projmenu{position:absolute;bottom:calc(100% + 8px);right:0;min-width:210px;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:10px;padding:6px;display:flex;flex-direction:column;gap:2px;z-index:8;box-shadow:0 8px 24px #0009}.tvp-projmenu[hidden]{display:none}.tvp-projmenu button{text-align:left;background:transparent;border:0;color:#e8eaed;padding:8px 10px;border-radius:7px;cursor:pointer;font:inherit;white-space:nowrap}.tvp-projmenu button:hover{background:#252b39}.tvp-projmenu button.active{background:#4f8cff;color:#fff}.tvp-vrslot button{position:static!important}.tvp-settings{position:absolute;bottom:62px;right:10px;width:300px;max-width:calc(100% - 20px);max-height:70%;overflow-y:auto;background:#121418eb;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:1px solid #2a2f3a;border-radius:12px;padding:14px;display:none;flex-direction:column;gap:12px;z-index:6;font:14px system-ui,Segoe UI,Roboto,sans-serif;color:#e8eaed}.tvp-settings.open{display:flex}.tvp-settings label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:#aab2c0}.tvp-settings label.row{flex-direction:row;align-items:center;gap:8px;color:#e8eaed;font-size:13px}.tvp-settings input[type=range]{width:100%;accent-color:#4f8cff}.tvp-settings input[type=text],.tvp-settings input[type=password]{width:100%;padding:7px 9px;border-radius:7px;border:1px solid #333;background:#151821;color:#e8eaed;font:inherit}.tvp-sep{width:100%;border:0;border-top:1px solid #2a2f3a;margin:2px 0}.tvp-toast{position:absolute;left:50%;bottom:74px;transform:translate(-50%);max-width:80%;padding:10px 16px;border-radius:10px;background:#1b1f2aed;border:1px solid #2a2f3a;color:#e8eaed;opacity:0;pointer-events:none;transition:opacity .2s;z-index:7;font:13px system-ui}.tvp-toast.show{opacity:1}",hc="three-vr-player:settings";class uc{constructor(e,t={}){var r,a;this.source=new sc,this.listeners=new Map,this.readyEmitted=!1,this.native=!1,this.loading=!1,this.useProxy=!1,this.opts=t,this.proxyConfig=t.proxy,this.useProxy=!!t.proxy;const i=t.persistSettings?this.loadSettings():null;this.view={projection:t.projection??(i==null?void 0:i.projection)??"180-sbs",swapEyes:t.swapEyes??(i==null?void 0:i.swapEyes)??!1,fov:t.fov??(i==null?void 0:i.fov)??70,supersampling:t.supersampling??(i==null?void 0:i.supersampling)??1.5},this.wrap=document.createElement("div"),this.wrap.className="tvp",this.wrap.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;",e.appendChild(this.wrap);let n;if(t.shadowDom!==!1){const o=this.wrap.attachShadow({mode:"open"}),l=document.createElement("style");l.textContent=cc,o.appendChild(l),n=o}else{if(!document.getElementById("tvp-styles")){const o=document.createElement("style");o.id="tvp-styles",o.textContent=cc,document.head.appendChild(o)}n=this.wrap}this.canvas=document.createElement("canvas"),this.canvas.className="tvp-canvas",this.video=document.createElement("video"),this.video.className="tvp-video",this.video.playsInline=!0,t.crossOrigin!==null&&(this.video.crossOrigin=t.crossOrigin??"anonymous"),n.append(this.canvas,this.video),this.scene=new ec({canvas:this.canvas,video:this.video,projection:this.view.projection,swapEyes:this.view.swapEyes,fov:this.view.fov,supersampling:this.view.supersampling}),this.look=new nc(this.scene.camera,this.canvas,{isPresenting:()=>this.scene.renderer.xr.isPresenting}),this.scene.onFrame(()=>this.look.update()),this.look.setEnabled(!this.scene.isFlat()),t.controls!==!1&&(this.ui=new n0(n,{video:this.video,surface:this.canvas,fullscreenTarget:this.wrap,vrButton:this.scene.vrButton,vrSupported:()=>this.vrSupported(),getProjection:()=>this.scene.getProjection(),setProjection:o=>this.setProjection(o),setSwapEyes:o=>this.setSwapEyes(o),setFov:o=>this.setFov(o),setSupersampling:o=>this.setSupersampling(o),initial:{swapEyes:this.view.swapEyes,fov:this.view.fov,supersampling:this.view.supersampling},proxy:{url:((r=this.proxyConfig)==null?void 0:r.url)??"",apiPassword:((a=this.proxyConfig)==null?void 0:a.apiPassword)??"",enabled:this.useProxy},setProxy:o=>this.setProxy(o)})),this.video.addEventListener("play",()=>this.emit("play")),this.video.addEventListener("pause",()=>this.emit("pause")),this.video.addEventListener("ended",()=>this.emit("ended")),this.video.addEventListener("timeupdate",()=>this.emit("timeupdate",this.video.currentTime)),this.video.addEventListener("error",()=>{this.loading||this.emit("error",this.video.error)}),this.video.addEventListener("loadedmetadata",()=>{this.readyEmitted||(this.readyEmitted=!0,this.emit("ready"))}),this.scene.renderer.xr.addEventListener("sessionstart",()=>this.emit("enterxr")),this.scene.renderer.xr.addEventListener("sessionend",()=>this.emit("exitxr")),t.src&&this.load(t.src,{projection:t.projection})}vrSupported(){return this.opts.vrButton===!1||!navigator.xr?Promise.resolve(!1):navigator.xr.isSessionSupported("immersive-vr").catch(()=>!1)}async load(e,t={}){this.currentSrc=e;const i=t.projection??(this.opts.autoDetect!==!1?Jl(e):null);i&&this.setProjection(i);const{url:n,format:r}=ac(e,this.useProxy?this.proxyConfig:void 0),a=this.opts.crossOrigin===void 0?"anonymous":this.opts.crossOrigin;this.loading=!0;try{await this.source.attach(this.video,{url:n,format:r},{crossOrigin:a}),this.setNativeFallback(!1),await this.video.play().catch(()=>{})}catch(o){if(this.opts.nativeFallback!==!1&&r==="progressive"&&a!==null)try{this.setNativeFallback(!0),await this.source.attach(this.video,{url:n,format:r},{crossOrigin:null}),await this.video.play().catch(()=>{}),this.emit("fallback");return}catch(l){throw this.setNativeFallback(!1),this.emit("error",l),l}throw this.setNativeFallback(!1),this.emit("error",o),o}finally{this.loading=!1}}setNativeFallback(e){e!==this.native&&(this.native=e,e?(this.scene.pauseRendering(),this.canvas.style.display="none",Object.assign(this.video.style,{display:"block",position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",background:"#000",zIndex:"1"})):(this.canvas.style.display="",this.video.style.cssText="",this.scene.resumeRendering()))}async play(){await this.video.play()}pause(){this.video.pause()}setProjection(e){this.scene.setProjection(e),this.look.setEnabled(!this.scene.isFlat()),this.look.reset(),this.view.projection=e,this.persist(),this.emit("projectionchange",e)}setSwapEyes(e){this.scene.setSwapEyes(e),this.view.swapEyes=e,this.persist()}setFov(e){this.scene.setFov(e),this.view.fov=e,this.persist()}setSupersampling(e){this.scene.setSupersampling(e),this.view.supersampling=e,this.persist()}setProxy(e){this.proxyConfig=e.url?{url:e.url,apiPassword:e.apiPassword||void 0}:void 0,this.useProxy=e.enabled,this.currentSrc&&this.load(this.currentSrc)}async enterVR(){var t;const e=this.scene.vrButton;(t=e==null?void 0:e.click)==null||t.call(e)}get three(){return{renderer:this.scene.renderer,scene:this.scene.scene,camera:this.scene.camera}}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),this}off(e,t){var i;return(i=this.listeners.get(e))==null||i.delete(t),this}emit(e,t){var i;(i=this.listeners.get(e))==null||i.forEach(n=>n(t))}persist(){if(this.opts.persistSettings)try{localStorage.setItem(hc,JSON.stringify(this.view))}catch{}}loadSettings(){try{const e=localStorage.getItem(hc);return e?JSON.parse(e):null}catch{return null}}dispose(){var e;(e=this.ui)==null||e.dispose(),this.look.dispose(),this.source.dispose(),this.scene.dispose(),this.video.remove(),this.canvas.remove(),this.wrap.remove(),this.listeners.clear()}}class dc extends HTMLElement{static get observedAttributes(){return["src","projection"]}connectedCallback(){this.player||(this.style.display||(this.style.display="block"),this.player=new uc(this,{src:this.getAttribute("src")??void 0,projection:this.getAttribute("projection")??void 0,controls:this.hasAttribute("controls"),swapEyes:this.hasAttribute("swap-eyes"),autoDetect:this.getAttribute("auto-detect")!=="false",fov:this.numAttr("fov"),supersampling:this.numAttr("supersampling"),proxy:this.getAttribute("proxy-url")?{url:this.getAttribute("proxy-url"),apiPassword:this.getAttribute("proxy-password")??void 0}:void 0}))}attributeChangedCallback(e,t,i){!this.player||i==null||(e==="src"&&this.player.load(i),e==="projection"&&this.player.setProjection(i))}disconnectedCallback(){var e;(e=this.player)==null||e.dispose(),this.player=void 0}numAttr(e){const t=this.getAttribute(e);return t==null?void 0:Number(t)}get api(){return this.player}}function fc(s="three-video"){typeof customElements<"u"&&!customElements.get(s)&&customElements.define(s,dc)}fc();const de=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},s0=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=r0},r0=Number.MAX_SAFE_INTEGER||9007199254740991;let Ee=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),z=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),x=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var Ye={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ge={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Hn{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class a0{constructor(e,t,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Hn(e),this.fast_=new Hn(t),this.defaultTTFB_=n,this.ttfb_=new Hn(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Hn(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Hn(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Hn(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function o0(s,e,t){return(e=c0(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function at(){return at=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},at.apply(null,arguments)}function pc(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function et(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?pc(Object(t),!0).forEach(function(i){o0(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):pc(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function l0(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function c0(s){var e=l0(s,"string");return typeof e=="symbol"?e:e+""}class li{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=Qi,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const Qi=function(){},h0={trace:Qi,debug:Qi,log:Qi,warn:Qi,info:Qi,error:Qi};function Ma(){return at({},h0)}function u0(s,e){const t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):Qi}function mc(s,e,t){return e[s]?e[s].bind(e):u0(s,t)}const La=Ma();function d0(s,e,t){const i=Ma();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=mc(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return Ma()}n.forEach(r=>{La[r]=mc(r,s)})}else at(La,i);return i}const tt=La;function Ni(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function f0(s){return typeof self<"u"&&s===self.ManagedMediaSource}function gc(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(a=>i.indexOf(a)===-1)}function ti(s,e=!1){if(typeof TextDecoder<"u"){const c=new TextDecoder("utf-8").decode(s);if(e){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const t=s.length;let i,n,r,a="",o=0;for(;o<t;){if(i=s[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=s[o++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[o++],r=s[o++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return a}function Ut(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function vc(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function p0(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ia={exports:{}},_c;function m0(){return _c||(_c=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var p=n.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var v={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(v.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)v.path=f.path,d.params||(v.params=f.params,d.query||(v.query=f.query));else{var m=f.path,g=m.substring(0,m.lastIndexOf("/")+1)+d.path;v.path=o.normalizePath(g)}return v.path===null&&(v.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(v)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()}(Ia)),Ia.exports}var Ca=m0();class ar{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ot={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class wa{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,g0(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let n;i.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(i[1]),this._byteRange=[n,parseInt(i[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ot.AUDIO]:null,[ot.VIDEO]:null,[ot.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ar),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ca.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ot.AUDIO]=null,e[ot.VIDEO]=null,e[ot.AUDIOVIDEO]=null}}function Et(s){return s.sn!=="initSegment"}class or extends wa{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(de(e)&&de(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const i=Object.keys(t);if(i.length===1){const n=this._decryptdata=t[i[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=de(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),n=i.length;if(n>1||n===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!de(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,n),l.endDTS=Math.max(l.endDTS,r)}}class Ec extends wa{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function xc(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||xc(t,e)}}function g0(s,e){const t=xc(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const Sc=Math.pow(2,32)-1,v0=[].push,yc={video:1,audio:2,id3:3,text:4};function At(s){return String.fromCharCode.apply(null,s)}function Tc(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function De(s,e){const t=bc(s,e);return t<0?4294967296+t:t}function Ac(s,e){let t=De(s,e);return t*=Math.pow(2,32),t+=De(s,e+4),t}function bc(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function _0(s){const e=s.byteLength;for(let t=0;t<e;){const i=De(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function We(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n<i;){const r=De(s,n),a=At(s.subarray(n+4,n+8)),o=r>1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,o));else{const l=We(s.subarray(n+8,o),e.slice(1));l.length&&v0.apply(t,l)}n=o}return t}function E0(s){const e=[],t=s[0];let i=8;const n=De(s,i);i+=4;let r=0,a=0;t===0?(r=De(s,i),a=De(s,i+4),i+=8):(r=Ac(s,i),a=Ac(s,i+8),i+=16),i+=2;let o=s.length+a;const l=Tc(s,i);i+=2;for(let c=0;c<l;c++){let h=i;const u=De(s,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return tt.warn("SIDX has hierarchical references (not supported)"),null;const p=De(s,h);h+=4,e.push({referenceSize:d,subsegmentDuration:p,info:{duration:p/n,start:o,end:o+d-1}}),o+=d,h+=4,i=h}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:l,references:e}}function Rc(s){const e=[],t=We(s,["moov","trak"]);for(let n=0;n<t.length;n++){const r=t[n],a=We(r,["tkhd"])[0];if(a){let o=a[0];const l=De(a,o===0?12:20),c=We(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=De(c,o===0?12:20),u=We(r,["mdia","hdlr"])[0];if(u){const d=At(u.subarray(8,12)),f={soun:ot.AUDIO,vide:ot.VIDEO}[d],p=We(r,["mdia","minf","stbl","stsd"])[0],v=x0(p);f?(e[l]={timescale:h,type:f,stsd:v},e[f]=et({timescale:h,id:l},v)):e[l]={timescale:h,type:d,stsd:v}}}}}return We(s,["moov","mvex","trex"]).forEach(n=>{const r=De(n,4),a=e[r];a&&(a.default={duration:De(n,12),flags:De(n,20)})}),e}function x0(s){const e=s.subarray(8),t=e.subarray(86),i=At(e.subarray(4,8));let n=i,r;const a=i==="enca"||i==="encv";if(a){const c=We(e,[i])[0].subarray(i==="enca"?28:78);We(c,["sinf"]).forEach(u=>{const d=We(u,["schm"])[0];if(d){const f=At(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const p=We(u,["frma"])[0];p&&(n=At(p))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const l=We(t,["avcC"])[0];l&&l.length>3&&(n+="."+cr(l[1])+cr(l[2])+cr(l[3]),r=lr(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=We(e,[i])[0],c=We(l.subarray(28),["esds"])[0];if(c&&c.length>7){let h=4;if(c[h++]!==3)break;h=Da(c,h),h+=2;const u=c[h++];if(u&128&&(h+=2),u&64&&(h+=c[h++]),c[h++]!==4)break;h=Da(c,h);const d=c[h++];if(d===64)n+="."+cr(d);else break;if(h+=12,c[h++]!==5)break;h=Da(c,h);const f=c[h++];let p=(f&248)>>3;p===31&&(p+=1+((f&7)<<3)+((c[h]&224)>>5)),n+="."+p}break}case"hvc1":case"hev1":{const l=We(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],h=["","A","B","C"][c>>6],u=c&31,d=De(l,2),f=(c&32)>>5?"H":"L",p=l[12],v=l.subarray(6,12);n+="."+h+u,n+="."+S0(d).toString(16).toUpperCase(),n+="."+f+p;let m="";for(let g=v.length;g--;){const E=v[g];(E||m)&&(m="."+E.toString(16).toUpperCase()+m)}n+=m}r=lr(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=lr(n,t)||n;break}case"vp09":{const l=We(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],h=l[5],u=l[6]>>4&15;n+="."+yi(c)+"."+yi(h)+"."+yi(u)}break}case"av01":{const l=We(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,h=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,p=c===2&&d?f?12:10:d?10:8,v=(l[2]&16)>>4,m=(l[2]&8)>>3,g=(l[2]&4)>>2,E=l[2]&3;n+="."+c+"."+yi(h)+u+"."+yi(p)+"."+v+"."+m+g+E+"."+yi(1)+"."+yi(1)+"."+yi(1)+"."+0,r=lr("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function lr(s,e){const t=We(e,["dvvC"]),i=t.length?t[0]:We(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+yi(n)+"."+yi(r)}}function S0(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Da(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function cr(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function yi(s){return(s<10?"0":"")+s}function y0(s,e){if(!s||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Mc(s,(i,n)=>{const r=i.subarray(8,24);r.some(a=>a!==0)||(tt.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Ut(r)} -> ${Ut(t)}`),i.set(t,8))})}function T0(s){const e=[];return Mc(s,t=>e.push(t.subarray(8,24))),e}function Mc(s,e){We(s,["moov","trak"]).forEach(i=>{const n=We(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let a=We(r,["enca"]);const o=a.length>0;o||(a=We(r,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);We(c,["sinf"]).forEach(u=>{const d=Lc(u);d&&e(d,o)})})})}function Lc(s){const e=We(s,["schm"])[0];if(e){const t=At(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=We(s,["schi","tenc"])[0];if(i)return i}}}function A0(s,e,t){const i={},n=We(s,["moof","traf"]);for(let r=0;r<n.length;r++){const a=n[r],o=We(a,["tfhd"])[0],l=De(o,4),c=e[l];if(!c)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const h=i[l],u=We(a,["tfdt"])[0];if(u){const _=u[0];let T=De(u,4);_===1&&(T===Sc?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Sc+1,T+=De(u,8))),de(T)&&(!de(h.start)||T<h.start)&&(h.start=T)}const d=c.default,f=De(o,0)|(d==null?void 0:d.flags);let p=(d==null?void 0:d.duration)||0;f&8&&(f&2?p=De(o,12):p=De(o,8));const v=We(a,["trun"]);let m=h.start||0,g=0,E=p;for(let _=0;_<v.length;_++){const T=v[_],b=De(T,4),R=h.sampleCount;h.sampleCount+=b;const A=T[3]&1,C=T[3]&4,S=T[2]&1,y=T[2]&2,w=T[2]&4,N=T[2]&8;let Y=8,D=b;for(A&&(Y+=4),C&&b&&(!(T[Y+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=R),Y+=4,S?(E=De(T,Y),Y+=4):E=p,y&&(Y+=4),N&&(Y+=4),m+=E,g+=E,D--);D--;)S?(E=De(T,Y),Y+=4):E=p,y&&(Y+=4),w&&(T[Y+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(D+1),h.keyFrameStart=m),Y+=4),N&&(Y+=4),m+=E,g+=E;!g&&p&&(g+=p*b)}h.duration+=g}if(!Object.keys(i).some(r=>i[r].duration)){let r=1/0,a=0;const o=We(s,["sidx"]);for(let l=0;l<o.length;l++){const c=E0(o[l]);if(c!=null&&c.references){r=Math.min(r,c.earliestPresentationTime/c.timescale);const h=c.references.reduce((u,d)=>u+d.info.duration||0,0);a=Math.max(a,h+c.earliestPresentationTime/c.timescale)}}a&&de(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start)})}return i}function b0(s){const e={valid:null,remainder:null},t=We(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function ci(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Ic(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return We(i,["moof"]).map(l=>{const c=l.byteOffset-8;We(l,["traf"]).map(u=>{const d=We(u,["tfdt"]).map(f=>{const p=f[0];let v=De(f,4);return p===1&&(v*=Math.pow(2,32),v+=De(f,8)),v/n})[0];return d!==void 0&&(s=d),We(u,["tfhd"]).map(f=>{const p=De(f,4),v=De(f,0)&16777215,m=(v&1)!==0,g=(v&2)!==0,E=(v&8)!==0;let _=0;const T=(v&16)!==0;let b=0;const R=(v&32)!==0;let A=8;p===r&&(m&&(A+=8),g&&(A+=4),E&&(_=De(f,A),A+=4),T&&(b=De(f,A),A+=4),R&&(A+=4),e.type==="video"&&(a=hr(e.codec)),We(u,["trun"]).map(C=>{const S=C[0],y=De(C,0)&16777215,w=(y&1)!==0;let N=0;const Y=(y&4)!==0,D=(y&256)!==0;let F=0;const O=(y&512)!==0;let $=0;const k=(y&1024)!==0,B=(y&2048)!==0;let X=0;const P=De(C,4);let V=8;w&&(N=De(C,V),V+=4),Y&&(V+=4);let G=N+c;for(let J=0;J<P;J++){if(D?(F=De(C,V),V+=4):F=_,O?($=De(C,V),V+=4):$=b,k&&(V+=4),B&&(S===0?X=De(C,V):X=bc(C,V),V+=4),e.type===ot.VIDEO){let ie=0;for(;ie<$;){const oe=De(i,G);if(G+=4,R0(a,i[G])){const me=i.subarray(G,G+oe);Pa(me,a?2:1,s+X/n,t)}G+=oe,ie+=oe+4}}s+=F/n}}))})})}),t}function hr(s){if(!s)return!1;const e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function R0(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Pa(s,e,t,i){const n=Cc(s);let r=0;r+=e;let a=0,o=0,l=0;for(;r<n.length;){a=0;do{if(r>=n.length)break;l=n[r++],a+=l}while(l===255);o=0;do{if(r>=n.length)break;l=n[r++],o+=l}while(l===255);const c=n.length-r;let h=r;if(o<c)r+=o;else if(o>c){tt.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(n[h++]===181){const d=Tc(n,h);if(h+=2,d===49){const f=De(n,h);if(h+=4,f===1195456820){const p=n[h++];if(p===3){const v=n[h++],m=31&v,g=64&v,E=g?2+m*3:0,_=new Uint8Array(E);if(g){_[0]=v;for(let T=1;T<E;T++)_[T]=n[h++]}i.push({type:p,payloadType:a,pts:t,bytes:_})}}}}}else if(a===5&&o>16){const u=[];for(let p=0;p<16;p++){const v=n[h++].toString(16);u.push(v.length==1?"0"+v:v),(p===3||p===5||p===7||p===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=n[h++];i.push({payloadType:a,pts:t,uuid:u.join(""),userData:ti(f),userDataBytes:f})}}}function Cc(s){const e=s.byteLength,t=[];let i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;const n=e-t.length,r=new Uint8Array(n);let a=0;for(i=0;i<n;a++,i++)a===t[0]&&(a++,t.shift()),r[i]=s[a];return r}function M0(s){const e=s[0];let t="",i="",n=0,r=0,a=0,o=0,l=0,c=0;if(e===0){for(;At(s.subarray(c,c+1))!=="\0";)t+=At(s.subarray(c,c+1)),c+=1;for(t+=At(s.subarray(c,c+1)),c+=1;At(s.subarray(c,c+1))!=="\0";)i+=At(s.subarray(c,c+1)),c+=1;i+=At(s.subarray(c,c+1)),c+=1,n=De(s,12),r=De(s,16),o=De(s,20),l=De(s,24),c=28}else if(e===1){c+=4,n=De(s,c),c+=4;const u=De(s,c);c+=4;const d=De(s,c);for(c+=4,a=4294967296*u+d,s0(a)||(a=Number.MAX_SAFE_INTEGER,tt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=De(s,c),c+=4,l=De(s,c),c+=4;At(s.subarray(c,c+1))!=="\0";)t+=At(s.subarray(c,c+1)),c+=1;for(t+=At(s.subarray(c,c+1)),c+=1;At(s.subarray(c,c+1))!=="\0";)i+=At(s.subarray(c,c+1)),c+=1;i+=At(s.subarray(c,c+1)),c+=1}const h=s.subarray(c,s.byteLength);return{schemeIdUri:t,value:i,timeScale:n,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function L0(s,...e){const t=e.length;let i=8,n=t;for(;n--;)i+=e[n].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n<t;n++)r.set(e[n],i),i+=e[n].byteLength;return r}function I0(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,n;i=0,n=new Uint8Array;let r;i>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),L0([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t)}function C0(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32<t;){const n=new DataView(s,i),r=w0(n);e.push(r),i+=r.size}}return e}function w0(s){const e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return{offset:t,size:i};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};const r=s.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=s.buffer,o=Ut(new Uint8Array(a,t+12,16));let l=null,c=null,h=0;if(r===0)h=28;else{const d=s.getUint32(28);if(!d||i<32+d*16)return{offset:t,size:e};l=[];for(let f=0;f<d;f++)l.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=s.getUint32(h);return e-32<u?{offset:t,size:e}:(c=new Uint8Array(a,t+h+4,u),{version:r,systemId:o,kids:l,data:c,offset:t,size:e})}const wc=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),$n={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Fa(s,e){const t=$n[e];return!!t&&!!t[s.slice(0,4)]}function fs(s,e,t=!0){return!s.split(",").some(i=>!Oa(i,e,t))}function Oa(s,e,t=!0){var i;const n=Ni(t);return(i=n==null?void 0:n.isTypeSupported(ps(s,e)))!=null?i:!1}function ps(s,e){return`${e}/mp4;codecs=${s}`}function Dc(s){if(s){const e=s.substring(0,4);return $n.video[e]}return 2}function ur(s){const e=wc();return s.split(",").reduce((t,i)=>{const r=e&&hr(i)?9:$n.video[i];return r?(r*2+t)/(t?3:2):($n.audio[i]+t)/(t?2:1)},0)}const Ua={};function D0(s,e=!0){if(Ua[s])return Ua[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;n<t.length;n++){var i;if(Oa(t[n],"audio",e))return Ua[s]=t[n],t[n];if(t[n]==="mp3"&&(i=Ni(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return s}const P0=/flac|opus|mp4a\.40\.34/i;function dr(s,e=!0){return s.replace(P0,t=>D0(t.toLowerCase(),e))}function F0(s,e){const t=[];if(s){const i=s.split(",");for(let n=0;n<i.length;n++)Fa(i[n],"video")||t.push(i[n])}return e&&t.push(e),t.join(",")}function fr(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(Pc(s,"audio")||Pc(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function Pc(s,e){return Fa(s,e)&&Oa(s,e)}function O0(s){const e=s.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function U0(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function Fc(s){const e=Ni(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Na(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const N0={supported:!0,powerEfficient:!0,smooth:!0},k0={supported:!1,smooth:!1,powerEfficient:!1},Oc={supported:!0,configurations:[],decodingInfoResults:[N0]};function Uc(s,e){return{supported:!1,configurations:e,decodingInfoResults:[k0],error:s}}function B0(s,e,t,i,n,r){const a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=r==null?void 0:r.audioCodec,c=r==null?void 0:r.channels,h=c?parseInt(c):l?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const p=e.groups[f];if(!p)throw new Error(`Audio track group ${f} not found`);Object.keys(p.channels).forEach(v=>{d[v]=(d[v]||0)+p.channels[v]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>hr(d))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!u&&de(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Nc(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(Oc);const r=[],a=G0(s),o=a.length,l=V0(s,e,o>0),c=l.length;for(let h=o||1*c||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),c){u.audio=l[h%c];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(n){const h=navigator.userAgent;if(n.split(",").some(u=>hr(u))&&wc())return Promise.resolve(Uc(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=$0(h);return i[u]||(i[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function G0(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=kc(s),n=s.width||640,r=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:ps(U0(l),"video"),width:n,height:r,bitrate:i,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function V0(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=kc(s);return n&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");n.forEach(f=>{const p={contentType:ps(f,"audio"),bitrate:t?H0(f,r):r};d&&(p.channels=""+d),h.push(p)})}return h},a):a},[]):[]}function H0(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function kc(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function $0(s){let e="";const{audio:t,video:i}=s;if(i){const n=Na(i.contentType);e+=`${n}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const n=Na(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const ka=["NONE","TYPE-0","TYPE-1",null];function z0(s){return ka.indexOf(s)>-1}const pr=["SDR","PQ","HLG"];function W0(s){return!!s&&pr.indexOf(s)>-1}var ms={No:"",Yes:"YES",v2:"v2"};function Bc(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i<e/2;return e&&n?t?ms.v2:ms.Yes:ms.No}class Ba{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class zn{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Gc(this._audioGroups,e)}hasSubtitleGroup(e){return Gc(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Gc(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function K0(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function X0(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||pr.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&K0(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const Y0=s=>{const e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},lt=(s,e)=>JSON.stringify(s,Y0(e));function q0(s,e,t,i,n){const r=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=n==null?void 0:n.videoCodec,c=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,p=1/0,v=1/0,m=0,g=[];const{preferHDR:E,allowedVideoRanges:_}=X0(e,n);for(let C=r.length;C--;){const S=s[r[C]];h||(h=S.channels[2]>0),d=Math.min(d,S.minHeight),f=Math.min(f,S.minFramerate),p=Math.min(p,S.minBitrate),_.filter(w=>S.videoRanges[w]>0).length>0&&(u=!0)}d=de(d)?d:0,f=de(f)?f:0;const T=Math.max(1080,d),b=Math.max(30,f);p=de(p)?p:t,t=Math.max(p,t),u||(e=void 0);const R=r.length>1;return{codecSet:r.reduce((C,S)=>{const y=s[S];if(S===C)return C;if(g=u?_.filter(w=>y.videoRanges[w]>0):[],R){if(y.minBitrate>t)return Ti(S,`min bitrate of ${y.minBitrate} > current estimate of ${t}`),C;if(!y.hasDefaultAudio)return Ti(S,"no renditions with default or auto-select sound found"),C;if(o&&S.indexOf(o.substring(0,4))%5!==0)return Ti(S,`audio codec preference "${o}" not found`),C;if(a&&!c){if(!y.channels[a])return Ti(S,`no renditions with ${a} channel sound found (channels options: ${Object.keys(y.channels)})`),C}else if((!o||c)&&h&&y.channels[2]===0)return Ti(S,"no renditions with stereo sound found"),C;if(y.minHeight>T)return Ti(S,`min resolution of ${y.minHeight} > maximum of ${T}`),C;if(y.minFramerate>b)return Ti(S,`min framerate of ${y.minFramerate} > maximum of ${b}`),C;if(!g.some(w=>y.videoRanges[w]>0))return Ti(S,`no variants with VIDEO-RANGE of ${lt(g)} found`),C;if(l&&S.indexOf(l.substring(0,4))%5!==0)return Ti(S,`video codec preference "${l}" not found`),C;if(y.maxScore<m)return Ti(S,`max score of ${y.maxScore} < selected max of ${m}`),C}return C&&(ur(S)>=ur(C)||y.fragmentError>s[C].fragmentError)?C:(v=y.minIndex,m=y.maxScore,S)},void 0),videoRanges:g,preferHDR:E,minFramerate:f,minBitrate:p,minIndex:v}}function Ti(s,e){tt.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Vc(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const n=t.channels||"2";return i.channels[n]=(i.channels[n]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function j0(s,e,t,i){return s.slice(t,i+1).reduce((n,r,a)=>{if(!r.codecSet)return n;const o=r.audioGroups;let l=n[r.codecSet];l||(n[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const c=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),n},{})}function Hc(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}=s;return{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}}function Ai(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){const n=e[i];if(dn(s,n,t))return i}return-1}function dn(s,e,t){const{groupId:i,name:n,lang:r,assocLang:a,default:o}=s,l=s.forced;return(i===void 0||e.groupId===i)&&(n===void 0||e.name===n)&&(r===void 0||Q0(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||Z0(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function Q0(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function Z0(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(n=>i.indexOf(n)===-1)}function fn(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function J0(s,e,t,i,n){const r=e[i],o=e.reduce((d,f,p)=>{const v=f.uri;return(d[v]||(d[v]=[])).push(p),d},{})[r.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=$c(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,p=t.filter(v=>!f||f.indexOf(v.groupId)!==-1);return Ai(s,p,n)>-1});return u>-1?u:$c(e,i,d=>{const f=d.audioGroups,p=t.filter(v=>!f||f.indexOf(v.groupId)!==-1);return Ai(s,p,n)>-1})}function $c(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}function mr(s,e){var t;return!!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}class zc extends li{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:n,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!n||!l)return;const c=performance.now(),h=r?r.stats:n.stats,u=r?r.duration:n.duration,d=c-h.loading.start,f=a.minAutoLevel,p=n.level,v=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||p<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=v>-1&&v!==p,g=!!t||m;if(!g&&(l.paused||!l.playbackRate||!l.readyState))return;const E=a.mainForwardBufferInfo;if(!g&&E===null)return;const _=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(d<=Math.max(_,1e3*(u/(T*2))))return;const b=E?E.len/T:0,R=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&R>-1,C=this.getBwEstimate(),S=a.levels,y=S[p],w=Math.max(h.loaded,Math.round(u*(n.bitrate||y.averageBitrate)/8));let N=A?d-R:d;N<1&&A&&(N=Math.min(d,h.loaded*8/C));const Y=A?h.loaded*1e3/N:0,D=_/1e3,F=Y?(w-h.loaded)/Y:w*8/C+D;if(F<=b)return;const O=Y?Y*8:C,$=((i=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,k=this.hls.config.abrBandWidthUpFactor;let B=Number.POSITIVE_INFINITY,X;for(X=p-1;X>f;X--){const J=S[X].maxBitrate,ie=!S[X].details||$;if(B=this.getTimeToLoadFrag(D,O,u*J,ie),B<Math.min(b,u+D))break}if(B>=F||B>u*10)return;A?this.bwEstimator.sample(d-Math.min(_,R),h.loaded):this.bwEstimator.sampleTTFB(d);const P=S[X].maxBitrate;this.getBwEstimate()*k>P&&this.resetEstimator(P);const V=this.findBestLevel(P,f,X,0,b,1,1);V>-1&&(X=V),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${p} is loading too slowly;
|
|
3687
3687
|
Fragment duration: ${n.duration.toFixed(3)}
|
|
3688
3688
|
Time to underbuffer: ${b.toFixed(3)} s
|
|
3689
3689
|
Estimated load time for current fragment: ${F.toFixed(3)} s
|
|
@@ -3691,27 +3691,27 @@ void main() {
|
|
|
3691
3691
|
TTFB estimate: ${R|0} ms
|
|
3692
3692
|
Current BW estimate: ${de(C)?C|0:"Unknown"} bps
|
|
3693
3693
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
3694
|
-
Switching to level ${
|
|
3694
|
+
Switching to level ${X} @ ${P|0} bps`),a.nextLoadLevel=a.nextAutoLevel=X,this.clearTimer();const G=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===X&&X>0){const J=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${X>0?"and switching down":""}
|
|
3695
3695
|
Fragment duration: ${n.duration.toFixed(3)} s
|
|
3696
|
-
Time to underbuffer: ${ee.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,q>f){let ie=this.findBestLevel(this.hls.levels[f].bitrate,f,q,0,ee,1,1);ie===-1&&(ie=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ie,this.resetEstimator(this.hls.levels[ie].bitrate)}}};m||F>B*2?$():this.timer=self.setInterval($,B*1e3),a.trigger(x.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:r,stats:h})},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 a0(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(x.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case H.BUFFER_ADD_CODEC_ERROR:case H.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case H.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const a=performance.now(),o=r?r.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,a=n?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;de(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===ge.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 r=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(x.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ge.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const m=this.findBestLevel(l,a,n,c,0,h,u);if(m>=0)return this.rebufferNotice=-1,m}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const m=this.bitrateTestDelay;m&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(l,a,n,c,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const p=i.levels[a],v=i.loadLevelObj;return v&&(p==null?void 0:p.bitrate)<v.bitrate?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,r,a,o){var l;const c=n+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:p,allAudioTracks:v,loadLevel:m,config:g}=this.hls;if(p.length===1)return 0;const E=p[u],_=!!((l=this.hls.latestLevelDetails)!=null&&l.live),T=m===-1||h===-1;let b,R="SDR",A=(E==null?void 0:E.frameRate)||0;const{audioPreference:C,videoPreference:S}=g,y=this.audioTracksByGroup||(this.audioTracksByGroup=Vc(v));let w=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const D=this.codecTiers||(this.codecTiers=j0(p,y,t,i)),k=q0(D,R,e,C,S),{codecSet:N,videoRanges:B,minFramerate:q,minBitrate:V,minIndex:W,preferHDR:$}=k;w=W,b=N,R=$?B[B.length-1]:B[0],A=q,e=Math.max(e,V),this.log(`picked start tier ${lt(k)}`)}else b=E==null?void 0:E.codecSet,R=E==null?void 0:E.videoRange;const U=f?f.duration:d?d.duration:0,X=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let D=i;D>=t;D--){var F;const k=p[D],N=D>u;if(!k)continue;if(g.useMediaCapabilities&&!k.supportedResult&&!k.supportedPromise){const ie=navigator.mediaCapabilities;typeof(ie==null?void 0:ie.decodingInfo)=="function"&&B0(k,y,R,A,e,C)?(k.supportedPromise=Nc(k,y,ie,this.supportedCache),k.supportedPromise.then(oe=>{if(!this.hls)return;k.supportedResult=oe;const me=this.hls.levels,Se=me.indexOf(k);oe.error?this.warn(`MediaCapabilities decodingInfo error: "${oe.error}" for level ${Se} ${lt(oe)}`):oe.supported?oe.decodingInfoResults.some(be=>be.smooth===!1||be.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Se} not smooth or powerEfficient: ${lt(oe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Se} ${lt(oe)}`),Se>-1&&me.length>1&&(this.log(`Removing unsupported level ${Se}`),this.hls.removeLevel(Se),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(oe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${oe}`)})):k.supportedResult=Oc}if((b&&k.codecSet!==b||R&&k.videoRange!==R||N&&A>k.frameRate||!N&&A>0&&A<k.frameRate||(F=k.supportedResult)!=null&&(F=F.decodingInfoResults)!=null&&F.some(ie=>ie.smooth===!1))&&(!T||D!==w)){P.push(D);continue}const B=k.details,q=(f?B==null?void 0:B.partTarget:B==null?void 0:B.averagetargetduration)||U;let V;N?V=o*e:V=a*e;const W=U&&n>=U*2&&r===0?k.averageBitrate:k.maxBitrate,$=this.getTimeToLoadFrag(X,V,W*q,B===void 0);if(V>=W&&(D===h||k.loadError===0&&k.fragmentError===0)&&($<=X||!de($)||_&&!this.bitrateTestDelay||$<c)){const ie=this.forcedAutoLevel;return D!==m&&(ie===-1||ie!==m)&&(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${p[P[0]].codecs}" ${p[P[0]].videoRange}; not compatible with "${b}" ${R}`),this.info(`switch candidate:${u}->${D} adjustedbw(${Math.round(V)})-bitrate=${Math.round(V-W)} ttfb:${X.toFixed(1)} avgDuration:${q.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${$.toFixed(1)} firstSelection:${T} codecSet:${k.codecSet} videoRange:${k.videoRange} hls.loadLevel:${m}`)),T&&(this.firstSelection=D),D}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Wc={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function ev(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!de(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let r=0;r<s.length;++r){const a=s[r];if(iv(e,t,a))return a}return null}function pn(s,e,t=0,i=0,n=.005){let r=null;if(s){r=e[1+s.sn-e[0].sn]||null;const o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&s.level!==r.level&&r.end<=s.end&&(r=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&Kc(t,i,r)===0||tv(r,s,Math.min(n,i))))return r;const a=Wc.search(e,Kc.bind(null,t,i));return a&&(a!==s||!r)?a:r}function tv(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function Kc(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function iv(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function Xc(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments;const{fragmentHint:n}=s;n&&(i=i.concat(n));let r;return Wc.search(i,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function gr(s){switch(s.details){case H.FRAG_LOAD_TIMEOUT:case H.KEY_LOAD_TIMEOUT:case H.LEVEL_LOAD_TIMEOUT:case H.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yc(s){return s.details.startsWith("key")}function qc(s){return Yc(s)&&!!s.frag&&!s.frag.decryptdata}function jc(s,e){const t=gr(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ga(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Qc(s){return et(et({},s),{errorRetry:null,timeoutRetry:null})}function vr(s,e,t,i){if(!s)return!1;const n=i==null?void 0:i.code,r=e<s.maxNumRetry&&(nv(n)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,r):r}function nv(s){return Va(s)||!!s&&(s<400||s>499)}function Va(s){return s===0&&navigator.onLine===!1}var It={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Yt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Zc extends li{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(x.ERROR,this.onError,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.ERROR,this.onError,this),e.off(x.ERROR,this.onErrorOut,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===ge.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(a=>n.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case H.FRAG_LOAD_ERROR:case H.FRAG_LOAD_TIMEOUT:case H.KEY_LOAD_ERROR:case H.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case H.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Wn();return}case H.FRAG_GAP:case H.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=It.SendAlternateToPenaltyBox;return}case H.LEVEL_EMPTY_ERROR:case H.LEVEL_PARSING_ERROR:{var a;const l=t.parent===ge.MAIN?t.level:n.loadLevel;t.details===H.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case H.LEVEL_LOAD_ERROR:case H.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case H.AUDIO_TRACK_LOAD_ERROR:case H.AUDIO_TRACK_LOAD_TIMEOUT:case H.SUBTITLE_LOAD_ERROR:case H.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const l=n.loadLevelObj;if(l&&(r.type===Ye.AUDIO_TRACK&&l.hasAudioGroup(r.groupId)||r.type===Ye.SUBTITLE_TRACK&&l.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=It.SendAlternateToPenaltyBox,t.errorAction.flags=Yt.MoveAllAlternatesMatchingHost;return}}return;case H.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingHDCP};return;case H.KEY_SYSTEM_SESSION_UPDATE_FAILED:case H.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case H.KEY_SYSTEM_NO_SESSION:t.errorAction={action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingKey};return;case H.BUFFER_ADD_CODEC_ERROR:case H.REMUX_ALLOC_ERROR:case H.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:n.loadLevel)}return;case H.INTERNAL_EXCEPTION:case H.BUFFER_APPENDING_ERROR:case H.BUFFER_FULL_ERROR:case H.LEVEL_SWITCH_ERROR:case H.BUFFER_STALLED_ERROR:case H.BUFFER_SEEK_OVER_HOLE:case H.BUFFER_NUDGE_ON_STALL:t.errorAction=Wn();return}t.type===Ee.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Wn())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=jc(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(vr(n,r,gr(e),e.response))return{action:It.RetryRequest,flags:Yt.None,retryConfig:n,retryCount:r};const o=this.getLevelSwitchAction(e,t);return n&&(o.retryConfig=n,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=jc(Yc(e)?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(n&&(e.details!==H.FRAG_GAP&&n.fragmentError++,!qc(e)&&vr(o,l,gr(e),e.response)))return{action:It.RetryRequest,flags:Yt.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,a;const c=e.details;n.loadError++,c===H.BUFFER_APPEND_ERROR&&n.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:p}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const v=(r=e.frag)==null?void 0:r.type,g=(v===ge.AUDIO&&c===H.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===H.BUFFER_ADD_CODEC_ERROR||c===H.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:R})=>n.audioCodec!==R),_=e.sourceBufferName==="video"&&(c===H.BUFFER_ADD_CODEC_ERROR||c===H.BUFFER_APPEND_ERROR)&&u.some(({codecSet:R,audioCodec:A})=>n.codecSet!==R&&n.audioCodec===A),{type:T,groupId:b}=(a=e.context)!=null?a:{};for(let R=u.length;R--;){const A=(R+d)%u.length;if(A!==d&&A>=f&&A<=p&&u[A].loadError===0){var o,l;const C=u[A];if(c===H.FRAG_GAP&&v===ge.MAIN&&e.frag){const S=u[A].details;if(S){const y=pn(e.frag,S.fragments,e.frag.start);if(y!=null&&y.gap)continue}}else{if(T===Ye.AUDIO_TRACK&&C.hasAudioGroup(b)||T===Ye.SUBTITLE_TRACK&&C.hasSubtitleGroup(b))continue;if(v===ge.AUDIO&&(o=n.audioGroups)!=null&&o.some(S=>C.hasAudioGroup(S))||v===ge.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(S=>C.hasSubtitleGroup(S))||g&&n.audioCodec===C.audioCodec||_&&n.codecSet===C.codecSet||!g&&n.codecSet!==C.codecSet)continue}h=A;break}}if(h>-1&&i.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:It.SendAlternateToPenaltyBox,flags:Yt.None,nextAutoLevel:h}}return{action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case It.DoNothing:break;case It.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==H.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n}=i,r=i.nextAutoLevel;switch(n){case Yt.None:this.switchLevel(e,r);break;case Yt.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),c=t.levels[l],h=c==null?void 0:c.attrs["HDCP-LEVEL"];if(i.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=ka[ka.indexOf(h)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Yt.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const c=this.hls.levels,h=c.length;for(let d=h;d--;)if(this.variantHasKey(c[d],l)){var a,o;this.log(`Banned key found in level ${d} (${c[d].bitrate}bps) or audio group "${(a=c[d].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Ut(l.keyId||[])}`),c[d].fragmentError++,c[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)i.resolved=!0;else if(u&&u.type!==ge.MAIN){const d=u.decryptdata;d&&!l.matches(d)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===H.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Na(e.mimeType),n=this.hls.levels;for(let r=n.length;r--;)n[r][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}}function Wn(s){const e={action:It.DoNothing,flags:Yt.None};return s&&(e.resolved=!0),e}var bt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class sv{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&&(e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const r=i[n];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,r=Object.keys(n);for(let a=r.length;a--;){const o=n[r[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,r){this.timeRanges&&(this.timeRanges[e]=t);const a=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||r)){l.body.type===i&&this.removeFragment(l.body);return}const c=l.range[e];if(c){if(c.time.length===0){this.removeFragment(l.body);return}c.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(l.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Kn(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(o=>{const l=i.elementaryStreams[o];if(!l)return;const c=t[o],h=a||l.partial===!0;r.range[o]=this.getBufferedTimes(i,e.part,h,c)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),_r(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Jc(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Kn(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<n.length;h++){const u=n.start(h)-this.bufferPadding,d=n.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,n.start(h)),endPTS:Math.min(o,n.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,n.start(h)),p=Math.min(o,n.end(h));p>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:p}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,i,n,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&_r(h)&&(n=h.body.start-o,r=h.body.end+o,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=h.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||_r(t))}getState(e){const t=Kn(e),i=this.fragments[t];return i?i.buffered?_r(i)?bt.PARTIAL:bt.OK:bt.APPENDING:bt.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a<i.length;a++){if(n=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,e>=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=Kn(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:a}=t;if(i.sn==="initSegment")return;const o=i.type;if(n){let c=this.activePartLists[o];c||(this.activePartLists[o]=c=[]),c.push(n)}this.timeRanges=r;const l=r[a];this.detectEvictedFragments(a,l,o,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Kn(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Kn(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=Jc(i,r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function _r(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Kn(s){return`${s.type}_${s.level}_${s.sn}`}function Jc(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Zi={cbc:0,ctr:1};class rv{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Zi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Zi.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 av(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class ov{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let p=0,v=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let g=v^v<<1^v<<2^v<<3^v<<4;g=g>>>8^g&255^99,e[p]=g,t[g]=p;const E=f[p],_=f[E],T=f[_];let b=f[g]*257^g*16843008;n[p]=b<<24|b>>>8,r[p]=b<<16|b>>>16,a[p]=b<<8|b>>>24,o[p]=b,b=T*16843009^_*65537^E*257^p*16843008,c[g]=b<<24|b>>>8,h[g]=b<<16|b>>>16,u[g]=b<<8|b>>>24,d[g]=b,p?(p=E^f[f[f[T^E]]],v^=f[f[v]]):p=v=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],v=f[1],m=f[2],g=f[3];let E,_;for(o=0;o<a;o++){if(o<r){E=c[o]=t[o];continue}_=E,o%r===0?(_=_<<8|_>>>24,_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255],_^=d[o/r|0]<<24):r>6&&o%r===4&&(_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255]),c[o]=E=(c[o-r]^_)>>>0}for(l=0;l<a;l++)o=a-l,l&3?_=c[o]:_=c[o-4],l<4||o<=4?h[l]=_:h[l]=p[u[_>>>24]]^v[u[_>>>16&255]]^m[u[_>>>8&255]]^g[u[_&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],p=d[1],v=d[2],m=d[3];const g=new Int32Array(e),E=new Int32Array(g.length);let _,T,b,R,A,C,S,y,w,U,X,P,F,D;const k=this.networkToHostOrderSwap;for(;t<g.length;){for(w=k(g[t]),U=k(g[t+1]),X=k(g[t+2]),P=k(g[t+3]),A=w^r[0],C=P^r[1],S=X^r[2],y=U^r[3],F=4,D=1;D<n;D++)_=l[A>>>24]^c[C>>16&255]^h[S>>8&255]^u[y&255]^r[F],T=l[C>>>24]^c[S>>16&255]^h[y>>8&255]^u[A&255]^r[F+1],b=l[S>>>24]^c[y>>16&255]^h[A>>8&255]^u[C&255]^r[F+2],R=l[y>>>24]^c[A>>16&255]^h[C>>8&255]^u[S&255]^r[F+3],A=_,C=T,S=b,y=R,F=F+4;_=a[A>>>24]<<24^a[C>>16&255]<<16^a[S>>8&255]<<8^a[y&255]^r[F],T=a[C>>>24]<<24^a[S>>16&255]<<16^a[y>>8&255]<<8^a[A&255]^r[F+1],b=a[S>>>24]<<24^a[y>>16&255]<<16^a[A>>8&255]<<8^a[C&255]^r[F+2],R=a[y>>>24]<<24^a[A>>16&255]<<16^a[C>>8&255]<<8^a[S&255]^r[F+3],E[t]=k(_^f),E[t+1]=k(R^p),E[t+2]=k(b^v),E[t+3]=k(T^m),f=w,p=U,v=X,m=P,t=t+4}return E.buffer}}class lv{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=cv(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function cv(s){switch(s){case Zi.cbc:return"AES-CBC";case Zi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}const hv=16;class Ha{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?av(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((r,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,n);const l=this.flush();l?r(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:a,remainderData:o}=this;if(n!==Zi.cbc||t.byteLength!==16)return tt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ci(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;r&&(i=r);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new ov),c.expandKey(t);const h=a;return this.currentResult=c.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new lv(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new rv(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(tt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%hv;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(tt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const eh=Math.pow(2,17);class uv{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new ki({type:Ee.NETWORK_ERROR,details:H.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){l(ih(e));return}else e.gap=!1;const c=this.loader=r?new r(n):new a(n),h=th(e);e.loader=c;const u=Qc(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:eh};e.stats=c.stats;const f={onSuccess:(p,v,m,g)=>{this.resetLoader(e,c);let E=p.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:g})},onError:(p,v,m,g)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:et({url:i,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:m,stats:g}))},onAbort:(p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:p}))},onTimeout:(p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:p}))}};t&&(f.onProgress=(p,v,m,g)=>t({frag:e,part:null,payload:m,networkDetails:g})),c.load(h,d,f)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ih(e,t));return}const c=this.loader=r?new r(n):new a(n),h=th(e,t);e.loader=c;const u=Qc(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:eh};t.stats=c.stats,c.load(h,d,{onSuccess:(f,p,v,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const g={frag:e,part:t,payload:f.data,networkDetails:m};i(g),o(g)},onError:(f,p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:et({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:v,stats:m}))},onAbort:(f,p,v)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:v,stats:f}))},onTimeout:(f,p,v)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:H.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:v,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/r),l),u=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+u}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=n.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function th(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(de(n)&&de(r)){var a;let o=n,l=r;if(s.sn==="initSegment"&&dv((a=s.decryptdata)==null?void 0:a.method)){const c=r-n;c%16&&(l=r+(16-c%16)),n!==0&&(i.resetIV=!0,o=n-16)}i.rangeStart=o,i.rangeEnd=l}return i}function ih(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Ee.MEDIA_ERROR,details:H.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new ki(i)}function dv(s){return s==="AES-128"||s==="AES-256"}class ki extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class nh extends li{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 Er{constructor(e,t,i,n=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=xr(),this.buffering={audio:xr(),video:xr(),audiovideo:xr()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=a}}function xr(){return{start:0,executeStart:0,executeEnd:0,end:0}}const sh={length:0,start:()=>0,end:()=>0};class Fe{static isBuffered(e,t){if(e){const i=Fe.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Fe.getBuffered(e);return Fe.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Fe.bufferedRanges(e);if(n.length)return Fe.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let n=-1,r=[];if(i)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(n=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<i?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,c=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(n===-1&&t>=u&&t<=d&&(n=h),t+i>=u&&t<d)l=u,c=d,a=c-t;else if(t+i<u){o=u;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||sh}catch(t){return tt.log("failed to get media.buffered",t),sh}}}const rh=/\{\$([a-zA-Z0-9-_]+)\}/g;function ah(s){return rh.test(s)}function $a(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(rh,i=>{const n=i.substring(2,i.length-1),r=t==null?void 0:t[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function oh(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function fv(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const pv=/^(\d+)x(\d+)$/,lh=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ft{constructor(e,t){typeof e=="string"&&(e=ft.parseAttrList(e,t)),at(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,r)=>(n[r.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=pv.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},r='"';for(lh.lastIndex=0;(i=lh.exec(e))!==null;){const a=i[1].trim();let o=i[2];const l=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=$a(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":tt.warn(`${e}: attribute ${a} is missing quotes`)}n[a]=o}return n}}const mv="com.apple.hls.interstitial";function gv(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function vv(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class za{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){tt.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=at(new ft({}),r,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 r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(r.getTime())&&(this._endDate=r)}}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?(tt.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===mv}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 _v=10;class ch{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||_v}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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Sr(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function hh(s,e){return!s&&!e?!0:!s||!e?!1:Sr(s,e)}function Xn(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Wa(s){switch(s){case"AES-128":case"AES-256":return Zi.cbc;case"AES-256-CTR":return Zi.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Ka(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Xa(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function Ev(s){const e=Xa(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function uh(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function dh(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",a=n[1];r?(i.splice(-1,1),t=Ka(a)):t=Ev(a)}}return t}const yr=typeof self<"u"?self:void 0;var pt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ct={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Tr(s){switch(s){case Ct.FAIRPLAY:return pt.FAIRPLAY;case Ct.PLAYREADY:return pt.PLAYREADY;case Ct.WIDEVINE:return pt.WIDEVINE;case Ct.CLEARKEY:return pt.CLEARKEY}}function Ya(s){switch(s){case pt.FAIRPLAY:return Ct.FAIRPLAY;case pt.PLAYREADY:return Ct.PLAYREADY;case pt.WIDEVINE:return Ct.WIDEVINE;case pt.CLEARKEY:return Ct.CLEARKEY}}function gs(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[pt.FAIRPLAY,pt.WIDEVINE,pt.PLAYREADY,pt.CLEARKEY].filter(n=>!!e[n]):[];return!i[pt.WIDEVINE]&&t&&i.push(pt.WIDEVINE),i}const qa=function(s){return yr!=null&&(s=yr.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function xv(s,e,t,i){let n;switch(s){case pt.FAIRPLAY:n=["cenc","sinf"];break;case pt.WIDEVINE:case pt.PLAYREADY:n=["cenc"];break;case pt.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Sv(n,e,t,i)}function Sv(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function yv(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function fh(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=Ka(o).subarray(0,16);return uh(l),l}}return null}let Yn={};class Bi{static clearKeyUriToKeyIdMap(){Yn={}}static setKeyIdForUri(e,t){Yn[e]=t}static addKeyIdForUri(e){const t=Object.keys(Yn).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Yn[e]=i,i}constructor(e,t,i,n=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Xn(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(vc(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Sr(e.keyFormatVersions,this.keyFormatVersions)&&hh(e.iv,this.iv)&&hh(e.keyId,this.keyId)}isSupported(){if(this.method){if(Xn(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ct.FAIRPLAY:case Ct.WIDEVINE:case Ct.PLAYREADY:case Ct.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Xn(this.method)){let r=this.iv;return r||(typeof e!="number"&&(tt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Av(e)),new Bi(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Yn[this.uri];if(r&&!Sr(this.keyId,r)&&Bi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=dh(this.uri);if(i)switch(this.keyFormat){case Ct.WIDEVINE:if(this.pssh=i,!this.keyId){const r=C0(i.buffer);if(r.length){var n;const a=r[0];this.keyId=(n=a.kids)!=null&&n.length?a.kids[0]:null}}this.keyId||(this.keyId=ph(t));break;case Ct.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=I0(r,null,i),this.keyId=fh(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Tv(t),r||(r=ph(t),r||(r=Yn[this.uri])),r&&(this.keyId=r,Bi.setKeyIdForUri(this.uri,r))}return this}}function Tv(s){const e=s==null?void 0:s[Ct.WIDEVINE];return e?e.keyId:null}function ph(s){const e=s==null?void 0:s[Ct.PLAYREADY];if(e){const t=dh(e.uri);if(t)return fh(t)}return null}function Av(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const mh=/#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,gh=/#EXT-X-MEDIA:(.*)/g,bv=/^#EXT(?:INF|-X-TARGETDURATION):/m,ja=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Rv=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 gi{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return Ca.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return bv.test(e)}static parseMasterPlaylist(e,t){const i=ah(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];if(mh.lastIndex=0,!e.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let a;for(;(a=mh.exec(e))!=null;)if(a[1]){var o;const c=new ft(a[1],n),h=$a(n,a[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:gi.resolve(h,t)},d=c.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),xh(c.CODECS,u);const f=c["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},xh(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),n.levels.push(u)}else if(a[3]){const c=a[3],h=a[4];switch(c){case"SESSION-DATA":{const u=new ft(h,n),d=u["DATA-ID"];d&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[d]=u);break}case"SESSION-KEY":{const u=_h(h,t,n);u.encrypted&&u.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(u)):tt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new ft(h,n);oh(n,u,t)}break}case"CONTENT-STEERING":{const u=new ft(h,n);n.contentSteering={uri:gi.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Eh(h);break}}}const l=r.length>0&&r.length<n.levels.length;return n.levels=l?r:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const r={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(gh.lastIndex=0;(n=gh.exec(e))!==null;){const c=new ft(n[1],i),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=c.LANGUAGE,p=c["ASSOC-LANGUAGE"],v=c.CHANNELS,m=c.CHARACTERISTICS,g=c["INSTREAM-ID"],E={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?gi.resolve(c.URI,t):""};if(p&&(E.assocLang=p),v&&(E.channels=v),m&&(E.characteristics=m),g&&(E.instreamId=g),u!=null&&u.length){const _=gi.findGroup(u,E.groupId)||u[0];Sh(E,_,"audioCodec"),Sh(E,_,"textCodec")}d.push(E)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){var o;const l={url:t},c=new ch(t),h=c.fragments,u=[];let d=null,f=0,p=0,v=0,m=0,g=0,E=null,_=new or(n,l),T,b,R,A=-1,C=!1,S=null,y;if(ja.lastIndex=0,c.m3u8=e,c.hasVariableRefs=ah(e),((o=ja.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(T=ja.exec(e))!==null;){C&&(C=!1,_=new or(n,l),_.playlistOffset=v,_.setStart(v),_.sn=f,_.cc=m,g&&(_.bitrate=g),_.level=i,d&&(_.initSegment=d,d.rawProgramDateTime&&(_.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),S&&(_.setByteRange(S),S=null)));const P=T[1];if(P){_.duration=parseFloat(P);const F=(" "+T[2]).slice(1);_.title=F||null,_.tagList.push(F?["INF",P,F]:["INF",P])}else if(T[3]){if(de(_.duration)){_.playlistOffset=v,_.setStart(v),R&&Th(_,R,c),_.sn=f,_.level=i,_.cc=m,h.push(_);const F=(" "+T[3]).slice(1);_.relurl=$a(c,F),Qa(_,E,u),E=_,v+=_.duration,f++,p=0,C=!0}}else{if(T=T[0].match(Rv),!T){tt.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<T.length&&T[b]===void 0;b++);const F=(" "+T[b]).slice(1),D=(" "+T[b+1]).slice(1),k=T[b+2]?(" "+T[b+2]).slice(1):null;switch(F){case"BYTERANGE":E?_.setByteRange(D,E):_.setByteRange(D);break;case"PROGRAM-DATE-TIME":_.rawProgramDateTime=D,_.tagList.push(["PROGRAM-DATE-TIME",D]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":c.type&&Gi(c,F,T),c.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?Gi(c,F,T):h.length>0&&Ah(c,F,T),f=c.startSN=parseInt(D);break;case"SKIP":{c.skippedSegments&&Gi(c,F,T);const N=new ft(D,c),B=N.decimalInteger("SKIPPED-SEGMENTS");if(de(B)){c.skippedSegments+=B;for(let V=B;V--;)h.push(null);f+=B}const q=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");q&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(q.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&Gi(c,F,T),c.targetduration=Math.max(parseInt(D),1);break;case"VERSION":c.version!==null&&Gi(c,F,T),c.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||Gi(c,F,T),c.live=!1;break;case"#":(D||k)&&_.tagList.push(k?[D,k]:[D]);break;case"DISCONTINUITY":m++,_.tagList.push(["DIS"]);break;case"GAP":_.gap=!0,_.tagList.push([F]);break;case"BITRATE":_.tagList.push([F,D]),g=parseInt(D)*1e3,de(g)?_.bitrate=g:g=0;break;case"DATERANGE":{const N=new ft(D,c),B=new za(N,c.dateRanges[N.ID],c.dateRangeTagCount);c.dateRangeTagCount++,B.isValid||c.skippedSegments?c.dateRanges[B.id]=B:tt.warn(`Ignoring invalid DATERANGE tag: "${D}"`),_.tagList.push(["EXT-X-DATERANGE",D]);break}case"DEFINE":{{const N=new ft(D,c);"IMPORT"in N?fv(c,N,a):oh(c,N,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?Gi(c,F,T):h.length>0&&Ah(c,F,T),c.startCC=m=parseInt(D);break;case"KEY":{const N=_h(D,t,c);if(N.isSupported()){if(N.method==="NONE"){R=void 0;break}R||(R={});const B=R[N.keyFormat];B!=null&&B.matches(N)||(B&&(R=at({},R)),R[N.keyFormat]=N)}else tt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${D}"`);break}case"START":c.startTimeOffset=Eh(D);break;case"MAP":{const N=new ft(D,c);if(_.duration){const B=new or(n,l);yh(B,N,i,R),d=B,_.initSegment=d,d.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=d.rawProgramDateTime)}else{const B=_.byteRangeEndOffset;if(B){const q=_.byteRangeStartOffset;S=`${B-q}@${q}`}else S=null;yh(_,N,i,R),d=_,C=!0}d.cc=m;break}case"SERVER-CONTROL":{y&&Gi(c,F,T),y=new ft(D),c.canBlockReload=y.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=y.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&y.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=y.optionalFloat("PART-HOLD-BACK",0),c.holdBack=y.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&Gi(c,F,T);const N=new ft(D);c.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=c.partList;N||(N=c.partList=[]);const B=p>0?N[N.length-1]:void 0,q=p++,V=new ft(D,c),W=new Ec(V,_,l,q,B);N.push(W),_.duration+=W.duration;break}case"PRELOAD-HINT":{const N=new ft(D,c);c.preloadHint=N;break}case"RENDITION-REPORT":{const N=new ft(D,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(N);break}default:tt.warn(`line parsed but not handled: ${T}`);break}}}E&&!E.relurl?(h.pop(),v-=E.duration,c.partList&&(c.fragmentHint=E)):c.partList&&(Qa(_,E,u),_.cc=m,c.fragmentHint=_,R&&Th(_,R,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const w=h.length,U=h[0],X=h[w-1];if(v+=c.skippedSegments*c.targetduration,v>0&&w&&X){c.averagetargetduration=v/w;const P=X.sn;c.endSN=P!=="initSegment"?P:0,c.live||(X.endList=!0),A>0&&(Lv(h,A),U&&u.unshift(U))}return c.fragmentHint&&(v+=c.fragmentHint.duration),c.totalduration=v,u.length&&c.dateRangeTagCount&&U&&vh(u,c),c.endCC=m,c}}function vh(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];s.push(o),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],c=l.startDate.getTime();l.tagAnchor=i.ref;for(let h=t;h--;){var a;if(((a=s[h])==null?void 0:a.sn)<e.startSN)break;const u=Mv(e,c,s,h,n);if(u!==-1){l.tagAnchor=e.fragments[u].ref;break}}}}function Mv(s,e,t,i,n){const r=t[i];if(r){const o=r.programDateTime;if(e>=o||i===0){var a;const l=(((a=t[i+1])==null?void 0:a.start)||n)-r.start;if(e<=o+l*1e3){const c=t[i].sn-s.startSN;if(c<0)return-1;const h=s.fragments;if(h.length>t.length){const d=(t[i+1]||h[h.length-1]).sn-s.startSN;for(let f=d;f>c;f--){const p=h[f].programDateTime;if(e>=p&&e<p+h[f].duration*1e3)return f}}return c}}}return-1}function _h(s,e,t){var i,n;const r=new ft(s,t),a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(n=r.KEYFORMAT)!=null?n:"identity";o&&r.IV&&!l&&tt.error(`Invalid IV: ${r.IV}`);const u=o?gi.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Bi(a,u,h,d,l,r.KEYID)}function Eh(s){const t=new ft(s).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function xh(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(r=>Fa(r,i));n.length&&(e[`${i}Codec`]=n.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function Sh(s,e,t){const i=e[t];i&&(s[t]=i)}function Lv(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Qa(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function yh(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function Th(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}function Gi(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Ah(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Za(s,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function bh(s,e,t,i,n,r,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let l=t,c=i;const h=e.startPTS,u=e.endPTS;if(de(h)){const g=Math.abs(h-t);s&&g>s.totalduration?a.warn(`media timestamps and playlist times differ by ${g}s for level ${e.level} ${s.url}`):de(e.deltaPTS)?e.deltaPTS=Math.max(g,e.deltaPTS):e.deltaPTS=g,l=Math.max(t,h),t=Math.min(t,h),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,c=Math.min(i,u),i=Math.max(i,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=c,e.endDTS=r;const f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let p;const v=f-s.startSN,m=s.fragments;for(m[v]=e,p=v;p>0;p--)Za(m[p],m[p-1]);for(p=v;p<m.length-1;p++)Za(m[p],m[p+1]);return s.fragmentHint&&Za(m[m.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,d}function Iv(s,e,t){if(s===e)return;let i=null;const n=s.fragments;for(let h=n.length-1;h>=0;h--){const u=n[h].initSegment;if(u){i=u;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;Dv(s,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const p=h.cc-u.cc;for(let v=d;v<f.length;v++)f[v].cc+=p;e.endCC=f[f.length-1].cc}de(h.startPTS)&&de(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,i=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(h.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Cv(s.dateRanges,e,t));const h=s.fragments.filter(u=>u.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Qa(o[u],o[u-1],h);vh(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const h=Ih(s,e.startSN-1);e.startCC=(l=h==null?void 0:h.cc)!=null?l:a[0].cc}wv(s.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?bh(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Mh(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const h=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=h),e.driftEndTime=c,e.driftEnd=h}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function Cv(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=at({},s);n&&n.forEach(l=>{delete r[l]});const o=Object.keys(r).length;return o?(Object.keys(i).forEach(l=>{const c=r[l],h=new za(i[l].attr,c);h.isValid?(r[l]=h,c||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${lt(i[l].attr)}"`)}),r):i}function wv(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],o=e[n+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Dv(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=n;c<=r;c++){const h=l[a+c];let u=o[c];if(i&&!u&&h&&(u=e.fragments[c]=h),h&&u){t(h,u,c,o);const d=h.relurl,f=u.relurl;if(d&&Pv(d,f)){e.playlistParsingError=Rh(`media sequence mismatch ${u.sn}:`,s,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=Rh(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,s,e,h,u);return}}}}function Rh(s,e,t,i,n){return new Error(`${s} ${n.url}
|
|
3696
|
+
Time to underbuffer: ${J.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,X>f){let ie=this.findBestLevel(this.hls.levels[f].bitrate,f,X,0,J,1,1);ie===-1&&(ie=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ie,this.resetEstimator(this.hls.levels[ie].bitrate)}}};m||F>B*2?G():this.timer=self.setInterval(G,B*1e3),a.trigger(x.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:r,stats:h})},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 a0(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(x.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case z.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const a=performance.now(),o=r?r.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,a=n?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;de(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===ge.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 r=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(x.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ge.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const m=this.findBestLevel(l,a,n,c,0,h,u);if(m>=0)return this.rebufferNotice=-1,m}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const m=this.bitrateTestDelay;m&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(l,a,n,c,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const p=i.levels[a],v=i.loadLevelObj;return v&&(p==null?void 0:p.bitrate)<v.bitrate?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,r,a,o){var l;const c=n+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:p,allAudioTracks:v,loadLevel:m,config:g}=this.hls;if(p.length===1)return 0;const E=p[u],_=!!((l=this.hls.latestLevelDetails)!=null&&l.live),T=m===-1||h===-1;let b,R="SDR",A=(E==null?void 0:E.frameRate)||0;const{audioPreference:C,videoPreference:S}=g,y=this.audioTracksByGroup||(this.audioTracksByGroup=Vc(v));let w=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const O=this.codecTiers||(this.codecTiers=j0(p,y,t,i)),$=q0(O,R,e,C,S),{codecSet:k,videoRanges:B,minFramerate:X,minBitrate:P,minIndex:V,preferHDR:G}=$;w=V,b=k,R=G?B[B.length-1]:B[0],A=X,e=Math.max(e,P),this.log(`picked start tier ${lt($)}`)}else b=E==null?void 0:E.codecSet,R=E==null?void 0:E.videoRange;const N=f?f.duration:d?d.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let O=i;O>=t;O--){var F;const $=p[O],k=O>u;if(!$)continue;if(g.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){const ie=navigator.mediaCapabilities;typeof(ie==null?void 0:ie.decodingInfo)=="function"&&B0($,y,R,A,e,C)?($.supportedPromise=Nc($,y,ie,this.supportedCache),$.supportedPromise.then(oe=>{if(!this.hls)return;$.supportedResult=oe;const me=this.hls.levels,Se=me.indexOf($);oe.error?this.warn(`MediaCapabilities decodingInfo error: "${oe.error}" for level ${Se} ${lt(oe)}`):oe.supported?oe.decodingInfoResults.some(be=>be.smooth===!1||be.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Se} not smooth or powerEfficient: ${lt(oe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Se} ${lt(oe)}`),Se>-1&&me.length>1&&(this.log(`Removing unsupported level ${Se}`),this.hls.removeLevel(Se),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(oe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${oe}`)})):$.supportedResult=Oc}if((b&&$.codecSet!==b||R&&$.videoRange!==R||k&&A>$.frameRate||!k&&A>0&&A<$.frameRate||(F=$.supportedResult)!=null&&(F=F.decodingInfoResults)!=null&&F.some(ie=>ie.smooth===!1))&&(!T||O!==w)){D.push(O);continue}const B=$.details,X=(f?B==null?void 0:B.partTarget:B==null?void 0:B.averagetargetduration)||N;let P;k?P=o*e:P=a*e;const V=N&&n>=N*2&&r===0?$.averageBitrate:$.maxBitrate,G=this.getTimeToLoadFrag(Y,P,V*X,B===void 0);if(P>=V&&(O===h||$.loadError===0&&$.fragmentError===0)&&(G<=Y||!de(G)||_&&!this.bitrateTestDelay||G<c)){const ie=this.forcedAutoLevel;return O!==m&&(ie===-1||ie!==m)&&(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${p[D[0]].codecs}" ${p[D[0]].videoRange}; not compatible with "${b}" ${R}`),this.info(`switch candidate:${u}->${O} adjustedbw(${Math.round(P)})-bitrate=${Math.round(P-V)} ttfb:${Y.toFixed(1)} avgDuration:${X.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${G.toFixed(1)} firstSelection:${T} codecSet:${$.codecSet} videoRange:${$.videoRange} hls.loadLevel:${m}`)),T&&(this.firstSelection=O),O}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Wc={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function ev(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!de(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let r=0;r<s.length;++r){const a=s[r];if(iv(e,t,a))return a}return null}function pn(s,e,t=0,i=0,n=.005){let r=null;if(s){r=e[1+s.sn-e[0].sn]||null;const o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&s.level!==r.level&&r.end<=s.end&&(r=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&Kc(t,i,r)===0||tv(r,s,Math.min(n,i))))return r;const a=Wc.search(e,Kc.bind(null,t,i));return a&&(a!==s||!r)?a:r}function tv(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function Kc(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function iv(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function Xc(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments;const{fragmentHint:n}=s;n&&(i=i.concat(n));let r;return Wc.search(i,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function gr(s){switch(s.details){case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_TIMEOUT:case z.LEVEL_LOAD_TIMEOUT:case z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yc(s){return s.details.startsWith("key")}function qc(s){return Yc(s)&&!!s.frag&&!s.frag.decryptdata}function jc(s,e){const t=gr(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ga(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Qc(s){return et(et({},s),{errorRetry:null,timeoutRetry:null})}function vr(s,e,t,i){if(!s)return!1;const n=i==null?void 0:i.code,r=e<s.maxNumRetry&&(nv(n)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,r):r}function nv(s){return Va(s)||!!s&&(s<400||s>499)}function Va(s){return s===0&&navigator.onLine===!1}var It={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Yt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Zc extends li{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(x.ERROR,this.onError,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.ERROR,this.onError,this),e.off(x.ERROR,this.onErrorOut,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===ge.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(a=>n.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case z.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Wn();return}case z.FRAG_GAP:case z.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=It.SendAlternateToPenaltyBox;return}case z.LEVEL_EMPTY_ERROR:case z.LEVEL_PARSING_ERROR:{var a;const l=t.parent===ge.MAIN?t.level:n.loadLevel;t.details===z.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.SUBTITLE_LOAD_ERROR:case z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const l=n.loadLevelObj;if(l&&(r.type===Ye.AUDIO_TRACK&&l.hasAudioGroup(r.groupId)||r.type===Ye.SUBTITLE_TRACK&&l.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=It.SendAlternateToPenaltyBox,t.errorAction.flags=Yt.MoveAllAlternatesMatchingHost;return}}return;case z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingHDCP};return;case z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case z.KEY_SYSTEM_NO_SESSION:t.errorAction={action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingKey};return;case z.BUFFER_ADD_CODEC_ERROR:case z.REMUX_ALLOC_ERROR:case z.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:n.loadLevel)}return;case z.INTERNAL_EXCEPTION:case z.BUFFER_APPENDING_ERROR:case z.BUFFER_FULL_ERROR:case z.LEVEL_SWITCH_ERROR:case z.BUFFER_STALLED_ERROR:case z.BUFFER_SEEK_OVER_HOLE:case z.BUFFER_NUDGE_ON_STALL:t.errorAction=Wn();return}t.type===Ee.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Wn())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=jc(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(vr(n,r,gr(e),e.response))return{action:It.RetryRequest,flags:Yt.None,retryConfig:n,retryCount:r};const o=this.getLevelSwitchAction(e,t);return n&&(o.retryConfig=n,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=jc(Yc(e)?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(n&&(e.details!==z.FRAG_GAP&&n.fragmentError++,!qc(e)&&vr(o,l,gr(e),e.response)))return{action:It.RetryRequest,flags:Yt.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,a;const c=e.details;n.loadError++,c===z.BUFFER_APPEND_ERROR&&n.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:p}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const v=(r=e.frag)==null?void 0:r.type,g=(v===ge.AUDIO&&c===z.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===z.BUFFER_ADD_CODEC_ERROR||c===z.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:R})=>n.audioCodec!==R),_=e.sourceBufferName==="video"&&(c===z.BUFFER_ADD_CODEC_ERROR||c===z.BUFFER_APPEND_ERROR)&&u.some(({codecSet:R,audioCodec:A})=>n.codecSet!==R&&n.audioCodec===A),{type:T,groupId:b}=(a=e.context)!=null?a:{};for(let R=u.length;R--;){const A=(R+d)%u.length;if(A!==d&&A>=f&&A<=p&&u[A].loadError===0){var o,l;const C=u[A];if(c===z.FRAG_GAP&&v===ge.MAIN&&e.frag){const S=u[A].details;if(S){const y=pn(e.frag,S.fragments,e.frag.start);if(y!=null&&y.gap)continue}}else{if(T===Ye.AUDIO_TRACK&&C.hasAudioGroup(b)||T===Ye.SUBTITLE_TRACK&&C.hasSubtitleGroup(b))continue;if(v===ge.AUDIO&&(o=n.audioGroups)!=null&&o.some(S=>C.hasAudioGroup(S))||v===ge.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(S=>C.hasSubtitleGroup(S))||g&&n.audioCodec===C.audioCodec||_&&n.codecSet===C.codecSet||!g&&n.codecSet!==C.codecSet)continue}h=A;break}}if(h>-1&&i.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:It.SendAlternateToPenaltyBox,flags:Yt.None,nextAutoLevel:h}}return{action:It.SendAlternateToPenaltyBox,flags:Yt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case It.DoNothing:break;case It.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==z.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n}=i,r=i.nextAutoLevel;switch(n){case Yt.None:this.switchLevel(e,r);break;case Yt.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),c=t.levels[l],h=c==null?void 0:c.attrs["HDCP-LEVEL"];if(i.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=ka[ka.indexOf(h)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Yt.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const c=this.hls.levels,h=c.length;for(let d=h;d--;)if(this.variantHasKey(c[d],l)){var a,o;this.log(`Banned key found in level ${d} (${c[d].bitrate}bps) or audio group "${(a=c[d].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Ut(l.keyId||[])}`),c[d].fragmentError++,c[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)i.resolved=!0;else if(u&&u.type!==ge.MAIN){const d=u.decryptdata;d&&!l.matches(d)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Na(e.mimeType),n=this.hls.levels;for(let r=n.length;r--;)n[r][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}}function Wn(s){const e={action:It.DoNothing,flags:Yt.None};return s&&(e.resolved=!0),e}var bt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class sv{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&&(e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const r=i[n];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:n}=this,r=Object.keys(n);for(let a=r.length;a--;){const o=n[r[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,n,r){this.timeRanges&&(this.timeRanges[e]=t);const a=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||r)){l.body.type===i&&this.removeFragment(l.body);return}const c=l.range[e];if(c){if(c.time.length===0){this.removeFragment(l.body);return}c.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(l.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Kn(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(o=>{const l=i.elementaryStreams[o];if(!l)return;const c=t[o],h=a||l.partial===!0;r.range[o]=this.getBufferedTimes(i,e.part,h,c)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),_r(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Jc(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Kn(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<n.length;h++){const u=n.start(h)-this.bufferPadding,d=n.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,n.start(h)),endPTS:Math.min(o,n.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,n.start(h)),p=Math.min(o,n.end(h));p>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:p}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,i,n,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&_r(h)&&(n=h.body.start-o,r=h.body.end+o,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=h.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||_r(t))}getState(e){const t=Kn(e),i=this.fragments[t];return i?i.buffered?_r(i)?bt.PARTIAL:bt.OK:bt.APPENDING:bt.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a<i.length;a++){if(n=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,e>=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=Kn(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:a}=t;if(i.sn==="initSegment")return;const o=i.type;if(n){let c=this.activePartLists[o];c||(this.activePartLists[o]=c=[]),c.push(n)}this.timeRanges=r;const l=r[a];this.detectEvictedFragments(a,l,o,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Kn(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||n&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Kn(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=Jc(i,r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function _r(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Kn(s){return`${s.type}_${s.level}_${s.sn}`}function Jc(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Zi={cbc:0,ctr:1};class rv{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Zi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Zi.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 av(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class ov{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let p=0,v=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let g=v^v<<1^v<<2^v<<3^v<<4;g=g>>>8^g&255^99,e[p]=g,t[g]=p;const E=f[p],_=f[E],T=f[_];let b=f[g]*257^g*16843008;n[p]=b<<24|b>>>8,r[p]=b<<16|b>>>16,a[p]=b<<8|b>>>24,o[p]=b,b=T*16843009^_*65537^E*257^p*16843008,c[g]=b<<24|b>>>8,h[g]=b<<16|b>>>16,u[g]=b<<8|b>>>24,d[g]=b,p?(p=E^f[f[f[T^E]]],v^=f[f[v]]):p=v=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n<t.length&&i;)i=t[n]===this.key[n],n++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],v=f[1],m=f[2],g=f[3];let E,_;for(o=0;o<a;o++){if(o<r){E=c[o]=t[o];continue}_=E,o%r===0?(_=_<<8|_>>>24,_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255],_^=d[o/r|0]<<24):r>6&&o%r===4&&(_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255]),c[o]=E=(c[o-r]^_)>>>0}for(l=0;l<a;l++)o=a-l,l&3?_=c[o]:_=c[o-4],l<4||o<=4?h[l]=_:h[l]=p[u[_>>>24]]^v[u[_>>>16&255]]^m[u[_>>>8&255]]^g[u[_&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const n=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],p=d[1],v=d[2],m=d[3];const g=new Int32Array(e),E=new Int32Array(g.length);let _,T,b,R,A,C,S,y,w,N,Y,D,F,O;const $=this.networkToHostOrderSwap;for(;t<g.length;){for(w=$(g[t]),N=$(g[t+1]),Y=$(g[t+2]),D=$(g[t+3]),A=w^r[0],C=D^r[1],S=Y^r[2],y=N^r[3],F=4,O=1;O<n;O++)_=l[A>>>24]^c[C>>16&255]^h[S>>8&255]^u[y&255]^r[F],T=l[C>>>24]^c[S>>16&255]^h[y>>8&255]^u[A&255]^r[F+1],b=l[S>>>24]^c[y>>16&255]^h[A>>8&255]^u[C&255]^r[F+2],R=l[y>>>24]^c[A>>16&255]^h[C>>8&255]^u[S&255]^r[F+3],A=_,C=T,S=b,y=R,F=F+4;_=a[A>>>24]<<24^a[C>>16&255]<<16^a[S>>8&255]<<8^a[y&255]^r[F],T=a[C>>>24]<<24^a[S>>16&255]<<16^a[y>>8&255]<<8^a[A&255]^r[F+1],b=a[S>>>24]<<24^a[y>>16&255]<<16^a[A>>8&255]<<8^a[C&255]^r[F+2],R=a[y>>>24]<<24^a[A>>16&255]<<16^a[C>>8&255]<<8^a[S&255]^r[F+3],E[t]=$(_^f),E[t+1]=$(R^p),E[t+2]=$(b^v),E[t+3]=$(T^m),f=w,p=N,v=Y,m=D,t=t+4}return E.buffer}}class lv{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=cv(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function cv(s){switch(s){case Zi.cbc:return"AES-CBC";case Zi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}const hv=16;class Ha{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?av(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,n){return this.useSoftware?new Promise((r,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,n);const l=this.flush();l?r(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:a,remainderData:o}=this;if(n!==Zi.cbc||t.byteLength!==16)return tt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ci(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;r&&(i=r);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new ov),c.expandKey(t);const h=a;return this.currentResult=c.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new lv(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new rv(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(tt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%hv;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(tt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const eh=Math.pow(2,17);class uv{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new ki({type:Ee.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){l(ih(e));return}else e.gap=!1;const c=this.loader=r?new r(n):new a(n),h=th(e);e.loader=c;const u=Qc(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:eh};e.stats=c.stats;const f={onSuccess:(p,v,m,g)=>{this.resetLoader(e,c);let E=p.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:g})},onError:(p,v,m,g)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:et({url:i,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:m,stats:g}))},onAbort:(p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:p}))},onTimeout:(p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:p}))}};t&&(f.onProgress=(p,v,m,g)=>t({frag:e,part:null,payload:m,networkDetails:g})),c.load(h,d,f)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ih(e,t));return}const c=this.loader=r?new r(n):new a(n),h=th(e,t);e.loader=c;const u=Qc(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:eh};t.stats=c.stats,c.load(h,d,{onSuccess:(f,p,v,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const g={frag:e,part:t,payload:f.data,networkDetails:m};i(g),o(g)},onError:(f,p,v,m)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:et({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:v,stats:m}))},onAbort:(f,p,v)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:v,stats:f}))},onTimeout:(f,p,v)=>{this.resetLoader(e,c),l(new ki({type:Ee.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:v,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/r),l),u=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+u}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=n.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function th(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(de(n)&&de(r)){var a;let o=n,l=r;if(s.sn==="initSegment"&&dv((a=s.decryptdata)==null?void 0:a.method)){const c=r-n;c%16&&(l=r+(16-c%16)),n!==0&&(i.resetIV=!0,o=n-16)}i.rangeStart=o,i.rangeEnd=l}return i}function ih(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Ee.MEDIA_ERROR,details:z.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new ki(i)}function dv(s){return s==="AES-128"||s==="AES-256"}class ki extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class nh extends li{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 Er{constructor(e,t,i,n=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=xr(),this.buffering={audio:xr(),video:xr(),audiovideo:xr()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=a}}function xr(){return{start:0,executeStart:0,executeEnd:0,end:0}}const sh={length:0,start:()=>0,end:()=>0};class Fe{static isBuffered(e,t){if(e){const i=Fe.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Fe.getBuffered(e);return Fe.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const n=Fe.bufferedRanges(e);if(n.length)return Fe.bufferedInfo(n,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let n=-1,r=[];if(i)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(n=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<i?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,c=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(n===-1&&t>=u&&t<=d&&(n=h),t+i>=u&&t<d)l=u,c=d,a=c-t;else if(t+i<u){o=u;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||sh}catch(t){return tt.log("failed to get media.buffered",t),sh}}}const rh=/\{\$([a-zA-Z0-9-_]+)\}/g;function ah(s){return rh.test(s)}function $a(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(rh,i=>{const n=i.substring(2,i.length-1),r=t==null?void 0:t[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function oh(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function fv(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const pv=/^(\d+)x(\d+)$/,lh=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ft{constructor(e,t){typeof e=="string"&&(e=ft.parseAttrList(e,t)),at(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)i[n]=parseInt(t.slice(n*2,n*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,r)=>(n[r.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=pv.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={},r='"';for(lh.lastIndex=0;(i=lh.exec(e))!==null;){const a=i[1].trim();let o=i[2];const l=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=$a(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":tt.warn(`${e}: attribute ${a} is missing quotes`)}n[a]=o}return n}}const mv="com.apple.hls.interstitial";function gv(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function vv(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class za{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:i,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){tt.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=at(new ft({}),r,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 r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);de(r.getTime())&&(this._endDate=r)}}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?(tt.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===mv}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 _v=10;class ch{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?de(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||_v}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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Sr(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function hh(s,e){return!s&&!e?!0:!s||!e?!1:Sr(s,e)}function Xn(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Wa(s){switch(s){case"AES-128":case"AES-256":return Zi.cbc;case"AES-256-CTR":return Zi.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Ka(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Xa(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function Ev(s){const e=Xa(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function uh(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function dh(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",a=n[1];r?(i.splice(-1,1),t=Ka(a)):t=Ev(a)}}return t}const yr=typeof self<"u"?self:void 0;var pt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ct={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Tr(s){switch(s){case Ct.FAIRPLAY:return pt.FAIRPLAY;case Ct.PLAYREADY:return pt.PLAYREADY;case Ct.WIDEVINE:return pt.WIDEVINE;case Ct.CLEARKEY:return pt.CLEARKEY}}function Ya(s){switch(s){case pt.FAIRPLAY:return Ct.FAIRPLAY;case pt.PLAYREADY:return Ct.PLAYREADY;case pt.WIDEVINE:return Ct.WIDEVINE;case pt.CLEARKEY:return Ct.CLEARKEY}}function gs(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[pt.FAIRPLAY,pt.WIDEVINE,pt.PLAYREADY,pt.CLEARKEY].filter(n=>!!e[n]):[];return!i[pt.WIDEVINE]&&t&&i.push(pt.WIDEVINE),i}const qa=function(s){return yr!=null&&(s=yr.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function xv(s,e,t,i){let n;switch(s){case pt.FAIRPLAY:n=["cenc","sinf"];break;case pt.WIDEVINE:case pt.PLAYREADY:n=["cenc"];break;case pt.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Sv(n,e,t,i)}function Sv(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function yv(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function fh(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=Ka(o).subarray(0,16);return uh(l),l}}return null}let Yn={};class Bi{static clearKeyUriToKeyIdMap(){Yn={}}static setKeyIdForUri(e,t){Yn[e]=t}static addKeyIdForUri(e){const t=Object.keys(Yn).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Yn[e]=i,i}constructor(e,t,i,n=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Xn(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(vc(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Sr(e.keyFormatVersions,this.keyFormatVersions)&&hh(e.iv,this.iv)&&hh(e.keyId,this.keyId)}isSupported(){if(this.method){if(Xn(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ct.FAIRPLAY:case Ct.WIDEVINE:case Ct.PLAYREADY:case Ct.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Xn(this.method)){let r=this.iv;return r||(typeof e!="number"&&(tt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Av(e)),new Bi(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Yn[this.uri];if(r&&!Sr(this.keyId,r)&&Bi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=dh(this.uri);if(i)switch(this.keyFormat){case Ct.WIDEVINE:if(this.pssh=i,!this.keyId){const r=C0(i.buffer);if(r.length){var n;const a=r[0];this.keyId=(n=a.kids)!=null&&n.length?a.kids[0]:null}}this.keyId||(this.keyId=ph(t));break;case Ct.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=I0(r,null,i),this.keyId=fh(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Tv(t),r||(r=ph(t),r||(r=Yn[this.uri])),r&&(this.keyId=r,Bi.setKeyIdForUri(this.uri,r))}return this}}function Tv(s){const e=s==null?void 0:s[Ct.WIDEVINE];return e?e.keyId:null}function ph(s){const e=s==null?void 0:s[Ct.PLAYREADY];if(e){const t=dh(e.uri);if(t)return fh(t)}return null}function Av(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const mh=/#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,gh=/#EXT-X-MEDIA:(.*)/g,bv=/^#EXT(?:INF|-X-TARGETDURATION):/m,ja=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Rv=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 gi{static findGroup(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.id===t)return n}}static resolve(e,t){return Ca.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return bv.test(e)}static parseMasterPlaylist(e,t){const i=ah(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];if(mh.lastIndex=0,!e.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let a;for(;(a=mh.exec(e))!=null;)if(a[1]){var o;const c=new ft(a[1],n),h=$a(n,a[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:gi.resolve(h,t)},d=c.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),xh(c.CODECS,u);const f=c["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},xh(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),n.levels.push(u)}else if(a[3]){const c=a[3],h=a[4];switch(c){case"SESSION-DATA":{const u=new ft(h,n),d=u["DATA-ID"];d&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[d]=u);break}case"SESSION-KEY":{const u=_h(h,t,n);u.encrypted&&u.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(u)):tt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new ft(h,n);oh(n,u,t)}break}case"CONTENT-STEERING":{const u=new ft(h,n);n.contentSteering={uri:gi.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Eh(h);break}}}const l=r.length>0&&r.length<n.levels.length;return n.levels=l?r:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,i){let n;const r={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(gh.lastIndex=0;(n=gh.exec(e))!==null;){const c=new ft(n[1],i),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=c.LANGUAGE,p=c["ASSOC-LANGUAGE"],v=c.CHANNELS,m=c.CHARACTERISTICS,g=c["INSTREAM-ID"],E={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?gi.resolve(c.URI,t):""};if(p&&(E.assocLang=p),v&&(E.channels=v),m&&(E.characteristics=m),g&&(E.instreamId=g),u!=null&&u.length){const _=gi.findGroup(u,E.groupId)||u[0];Sh(E,_,"audioCodec"),Sh(E,_,"textCodec")}d.push(E)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){var o;const l={url:t},c=new ch(t),h=c.fragments,u=[];let d=null,f=0,p=0,v=0,m=0,g=0,E=null,_=new or(n,l),T,b,R,A=-1,C=!1,S=null,y;if(ja.lastIndex=0,c.m3u8=e,c.hasVariableRefs=ah(e),((o=ja.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(T=ja.exec(e))!==null;){C&&(C=!1,_=new or(n,l),_.playlistOffset=v,_.setStart(v),_.sn=f,_.cc=m,g&&(_.bitrate=g),_.level=i,d&&(_.initSegment=d,d.rawProgramDateTime&&(_.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),S&&(_.setByteRange(S),S=null)));const D=T[1];if(D){_.duration=parseFloat(D);const F=(" "+T[2]).slice(1);_.title=F||null,_.tagList.push(F?["INF",D,F]:["INF",D])}else if(T[3]){if(de(_.duration)){_.playlistOffset=v,_.setStart(v),R&&Th(_,R,c),_.sn=f,_.level=i,_.cc=m,h.push(_);const F=(" "+T[3]).slice(1);_.relurl=$a(c,F),Qa(_,E,u),E=_,v+=_.duration,f++,p=0,C=!0}}else{if(T=T[0].match(Rv),!T){tt.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<T.length&&T[b]===void 0;b++);const F=(" "+T[b]).slice(1),O=(" "+T[b+1]).slice(1),$=T[b+2]?(" "+T[b+2]).slice(1):null;switch(F){case"BYTERANGE":E?_.setByteRange(O,E):_.setByteRange(O);break;case"PROGRAM-DATE-TIME":_.rawProgramDateTime=O,_.tagList.push(["PROGRAM-DATE-TIME",O]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":c.type&&Gi(c,F,T),c.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?Gi(c,F,T):h.length>0&&Ah(c,F,T),f=c.startSN=parseInt(O);break;case"SKIP":{c.skippedSegments&&Gi(c,F,T);const k=new ft(O,c),B=k.decimalInteger("SKIPPED-SEGMENTS");if(de(B)){c.skippedSegments+=B;for(let P=B;P--;)h.push(null);f+=B}const X=k.enumeratedString("RECENTLY-REMOVED-DATERANGES");X&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(X.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&Gi(c,F,T),c.targetduration=Math.max(parseInt(O),1);break;case"VERSION":c.version!==null&&Gi(c,F,T),c.version=parseInt(O);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||Gi(c,F,T),c.live=!1;break;case"#":(O||$)&&_.tagList.push($?[O,$]:[O]);break;case"DISCONTINUITY":m++,_.tagList.push(["DIS"]);break;case"GAP":_.gap=!0,_.tagList.push([F]);break;case"BITRATE":_.tagList.push([F,O]),g=parseInt(O)*1e3,de(g)?_.bitrate=g:g=0;break;case"DATERANGE":{const k=new ft(O,c),B=new za(k,c.dateRanges[k.ID],c.dateRangeTagCount);c.dateRangeTagCount++,B.isValid||c.skippedSegments?c.dateRanges[B.id]=B:tt.warn(`Ignoring invalid DATERANGE tag: "${O}"`),_.tagList.push(["EXT-X-DATERANGE",O]);break}case"DEFINE":{{const k=new ft(O,c);"IMPORT"in k?fv(c,k,a):oh(c,k,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?Gi(c,F,T):h.length>0&&Ah(c,F,T),c.startCC=m=parseInt(O);break;case"KEY":{const k=_h(O,t,c);if(k.isSupported()){if(k.method==="NONE"){R=void 0;break}R||(R={});const B=R[k.keyFormat];B!=null&&B.matches(k)||(B&&(R=at({},R)),R[k.keyFormat]=k)}else tt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${O}"`);break}case"START":c.startTimeOffset=Eh(O);break;case"MAP":{const k=new ft(O,c);if(_.duration){const B=new or(n,l);yh(B,k,i,R),d=B,_.initSegment=d,d.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=d.rawProgramDateTime)}else{const B=_.byteRangeEndOffset;if(B){const X=_.byteRangeStartOffset;S=`${B-X}@${X}`}else S=null;yh(_,k,i,R),d=_,C=!0}d.cc=m;break}case"SERVER-CONTROL":{y&&Gi(c,F,T),y=new ft(O),c.canBlockReload=y.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=y.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&y.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=y.optionalFloat("PART-HOLD-BACK",0),c.holdBack=y.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&Gi(c,F,T);const k=new ft(O);c.partTarget=k.decimalFloatingPoint("PART-TARGET");break}case"PART":{let k=c.partList;k||(k=c.partList=[]);const B=p>0?k[k.length-1]:void 0,X=p++,P=new ft(O,c),V=new Ec(P,_,l,X,B);k.push(V),_.duration+=V.duration;break}case"PRELOAD-HINT":{const k=new ft(O,c);c.preloadHint=k;break}case"RENDITION-REPORT":{const k=new ft(O,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(k);break}default:tt.warn(`line parsed but not handled: ${T}`);break}}}E&&!E.relurl?(h.pop(),v-=E.duration,c.partList&&(c.fragmentHint=E)):c.partList&&(Qa(_,E,u),_.cc=m,c.fragmentHint=_,R&&Th(_,R,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const w=h.length,N=h[0],Y=h[w-1];if(v+=c.skippedSegments*c.targetduration,v>0&&w&&Y){c.averagetargetduration=v/w;const D=Y.sn;c.endSN=D!=="initSegment"?D:0,c.live||(Y.endList=!0),A>0&&(Lv(h,A),N&&u.unshift(N))}return c.fragmentHint&&(v+=c.fragmentHint.duration),c.totalduration=v,u.length&&c.dateRangeTagCount&&N&&vh(u,c),c.endCC=m,c}}function vh(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];s.push(o),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],c=l.startDate.getTime();l.tagAnchor=i.ref;for(let h=t;h--;){var a;if(((a=s[h])==null?void 0:a.sn)<e.startSN)break;const u=Mv(e,c,s,h,n);if(u!==-1){l.tagAnchor=e.fragments[u].ref;break}}}}function Mv(s,e,t,i,n){const r=t[i];if(r){const o=r.programDateTime;if(e>=o||i===0){var a;const l=(((a=t[i+1])==null?void 0:a.start)||n)-r.start;if(e<=o+l*1e3){const c=t[i].sn-s.startSN;if(c<0)return-1;const h=s.fragments;if(h.length>t.length){const d=(t[i+1]||h[h.length-1]).sn-s.startSN;for(let f=d;f>c;f--){const p=h[f].programDateTime;if(e>=p&&e<p+h[f].duration*1e3)return f}}return c}}}return-1}function _h(s,e,t){var i,n;const r=new ft(s,t),a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(n=r.KEYFORMAT)!=null?n:"identity";o&&r.IV&&!l&&tt.error(`Invalid IV: ${r.IV}`);const u=o?gi.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Bi(a,u,h,d,l,r.KEYID)}function Eh(s){const t=new ft(s).decimalFloatingPoint("TIME-OFFSET");return de(t)?t:null}function xh(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(r=>Fa(r,i));n.length&&(e[`${i}Codec`]=n.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function Sh(s,e,t){const i=e[t];i&&(s[t]=i)}function Lv(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Qa(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function yh(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function Th(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}function Gi(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Ah(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Za(s,e){const t=e.startPTS;if(de(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function bh(s,e,t,i,n,r,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let l=t,c=i;const h=e.startPTS,u=e.endPTS;if(de(h)){const g=Math.abs(h-t);s&&g>s.totalduration?a.warn(`media timestamps and playlist times differ by ${g}s for level ${e.level} ${s.url}`):de(e.deltaPTS)?e.deltaPTS=Math.max(g,e.deltaPTS):e.deltaPTS=g,l=Math.max(t,h),t=Math.min(t,h),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,c=Math.min(i,u),i=Math.max(i,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=c,e.endDTS=r;const f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let p;const v=f-s.startSN,m=s.fragments;for(m[v]=e,p=v;p>0;p--)Za(m[p],m[p-1]);for(p=v;p<m.length-1;p++)Za(m[p],m[p+1]);return s.fragmentHint&&Za(m[m.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,d}function Iv(s,e,t){if(s===e)return;let i=null;const n=s.fragments;for(let h=n.length-1;h>=0;h--){const u=n[h].initSegment;if(u){i=u;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;Dv(s,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const p=h.cc-u.cc;for(let v=d;v<f.length;v++)f[v].cc+=p;e.endCC=f[f.length-1].cc}de(h.startPTS)&&de(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,i=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(h.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Cv(s.dateRanges,e,t));const h=s.fragments.filter(u=>u.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Qa(o[u],o[u-1],h);vh(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const h=Ih(s,e.startSN-1);e.startCC=(l=h==null?void 0:h.cc)!=null?l:a[0].cc}wv(s.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?bh(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Mh(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const h=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=h),e.driftEndTime=c,e.driftEnd=h}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function Cv(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=at({},s);n&&n.forEach(l=>{delete r[l]});const o=Object.keys(r).length;return o?(Object.keys(i).forEach(l=>{const c=r[l],h=new za(i[l].attr,c);h.isValid?(r[l]=h,c||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${lt(i[l].attr)}"`)}),r):i}function wv(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],o=e[n+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Dv(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=n;c<=r;c++){const h=l[a+c];let u=o[c];if(i&&!u&&h&&(u=e.fragments[c]=h),h&&u){t(h,u,c,o);const d=h.relurl,f=u.relurl;if(d&&Pv(d,f)){e.playlistParsingError=Rh(`media sequence mismatch ${u.sn}:`,s,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=Rh(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,s,e,h,u);return}}}}function Rh(s,e,t,i,n){return new Error(`${s} ${n.url}
|
|
3697
3697
|
Playlist starting @${e.startSN}
|
|
3698
3698
|
${e.m3u8}
|
|
3699
3699
|
|
|
3700
3700
|
Playlist starting @${t.startSN}
|
|
3701
|
-
${t.m3u8}`)}function Mh(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let a=0;if(r&&i<n.length)a=n[i].start;else if(r&&e.startSN===s.endSN+1)a=s.fragmentEnd;else if(r&&t)a=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=s.fragmentStart;else return;Ja(e,a)}function Ja(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e)}}function Lh(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const i=s.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ih(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function Ch(s,e,t){return s?wh(s.partList,e,t):null}function wh(s,e,t){if(s)for(let i=s.length;i--;){const n=s[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function Dh(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Pv(s,e){return s!==e&&e?Ph(s)!==Ph(e):!1}function Ph(s){return s.replace(/\?[^?]*$/,"")}function vs(s,e){for(let i=0,n=s.length;i<n;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function Fv(s,e){return!!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function Fh(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Oh(s,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Fh(t[i],s);e.fragmentHint&&Fh(e.fragmentHint,s),e.alignedSliding=!0}function Ov(s,e){s&&(Uh(e,s),e.alignedSliding||Ar(e,s),!e.alignedSliding&&!e.skippedSegments&&Mh(s,e,!1))}function Uh(s,e){if(!Fv(e,s))return;const t=Math.min(e.endCC,s.endCC),i=vs(e.fragments,t),n=vs(s.fragments,t);if(!i||!n)return;tt.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=i.start-n.start;Oh(r,s)}function Ar(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,r;const a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(n=vs(i,a),r=vs(t,a)),(!n||!r)&&(n=i[Math.floor(i.length/2)],r=vs(t,n.cc)||t[Math.floor(t.length/2)]);const o=n.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-n.start);Oh(c,s)}function Ht(s,e,t){qt(s,e,t),s.addEventListener(e,t)}function qt(s,e,t){s.removeEventListener(e,t)}const Uv={toString:function(s){let e="";const t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},te={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 br extends nh{constructor(e,t,i,n,r){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=te.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:a,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,u=l?l.currentTime:0,d=Fe.bufferInfo(c||l,u,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${de(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===te.ENDED)this.resetLoadingState();else if(o){const p=a.maxFragLookUpTolerance,v=o.start-p,m=o.start+o.duration+p;if(f||m<d.start||v>d.end){const g=u>m;(u<v||g)&&(g&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(u>p&&(this.lastCurrentTime=u),!this.loadingParts){const v=Math.max(d.end,u),m=this.shouldLoadParts(this.getLevelDetails(),v);m&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${v.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===te.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new uv(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ha(e.config)}registerListeners(){const{hls:e}=this;e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===te.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=te.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Fe.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>n&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const h=l[l.length-1];return Fe.isBuffered(this.media,h.start+h.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Ht(i,"seeking",this.onMediaSeeking),Ht(i,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===te.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),qt(n,"seeking",this.onMediaSeeking),qt(n,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=te.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===te.FRAG_LOADING||!this.fragCurrent&&a===te.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=te.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(x.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===bt.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===bt.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(x.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:a}=i,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Xn(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Wa(o.method)).catch(c=>{throw n.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:r}),c}).then(c=>{const h=self.performance.now();return n.trigger(x.FRAG_DECRYPTED,{frag:r,payload:c,stats:{tstart:l,tdecrypt:h}}),i.payload=c,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==te.STOPPED&&(this.state=te.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(x.ERROR,{type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?Uv.toString(Fe.getBuffered(i)):"(detached)"})`),Et(e)){var n;if(e.type!==ge.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=te.IDLE;return}}const r=(n=this.levels)==null?void 0:n[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=te.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(l=>!l),o=new Er(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=te.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(x.KEY_LOADED,d),this.state===te.KEY_LOADING&&(this.state=te.IDLE),d}),this.hls.trigger(x.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(Et(e)&&(!l||e.sn!==l.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=d)}if(i=Math.max(e.start,i||0),this.loadingParts&&Et(e)){const d=a.partList;if(d&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(d,e,i);if(f>-1){const p=d[f];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=te.FRAG_LOADING;let v;return o?v=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,p,t,n)).catch(m=>this.handleFragLoadError(m)):v=this.doFragPartsLoad(e,p,t,n).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(x.FRAG_LOADING,{frag:e,part:p,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}if(Et(e)&&this.loadingParts){var c;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(c=a.partList)==null?void 0:c.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=te.FRAG_LOADING;const h=this.config.progressive&&e.type!==ge.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,n)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?n:void 0),o]).then(([d])=>(!h&&n&&n(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(x.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((r,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,n).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(x.FRAG_LOADED,d);const p=Ch(i.details,e.sn,u.index+1)||wh(c,e.sn,u.index+1);if(p)h(p);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===H.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ee.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(x.ERROR,t)}else this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==te.PARSING){!this.fragCurrent&&this.state!==te.STOPPED&&this.state!==te.ERROR&&(this.state=te.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=c),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===ge.SUBTITLE)return!1;const a=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:a}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const o=t[n],l=o.details,c=a>-1?Ch(l,r,a):null,h=c?c.fragment:Ih(l,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:c,level:o}):null}bufferFragmentData(e,t,i,n,r){if(this.state!==te.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=ci(a,o)),!l.length)return;const c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:n,offset:h,parent:t.type,data:l};if(this.hls.trigger(x.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Fe.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Fe.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const a=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,a)}getFwdBufferInfoAtPos(e,t,i,n){const r=Fe.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,n);return Fe.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const n=e.nextStart;if(n&&i.start>n){const r=e.buffered;if(r){let a=e.len;const o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<i.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return r>=n?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=ge.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const u=r.initialLiveManifestSize;if(n<u)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const d=this.config.startPosition,f=this.hls.startPosition,p=this.hls.liveSyncPosition,v=((c=l)==null?void 0:c.start)||0;let m,g;f!==-1&&f>=a?(m=f,g=f===d?"config":"next load start"):p!==null?(m=p,g="live edge"):(m=e,g="buffer pos"),m<v&&(m=v,g="live frag start"),m<a&&(m=a,g="playlist start"),(this.startPosition!=m||this.nextLoadPosition!=m)&&(this.log(`Setting startPosition to ${m.toFixed(3)} ${f===-1?"":`(from ${d}) `}based on ${g}. live edge: ${p} live frag start: ${v.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=m)}}else e<=a&&(l=i[0]);if(!l){const u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(l,t);if(!h&&l){const u=l.sn-t.startSN;h=this.filterReplacedPrimary(i[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return i===bt.OK||i===bt.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,i,n,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(o!==null&&i.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Nh(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Nh(this.config)&&e.type!==ge.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const a=n.event;if(a){if(a.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 r=i==null?void 0:i.playerQueue;if(r)for(let a=r.length;a--;){const o=r[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,n>-1&&i<c.start)break;const h=c.loaded;h?n=-1:(r||(c.independent||a)&&c.fragment===t)&&(c.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${c.start}`),n=o),r=h}return n}loadedEndOfParts(e,t){let i;for(let n=e.length;n--;){if(i=e[n],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(n=ev(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Xc(e,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=n,h=i.partList,u=!!(this.loadingParts&&h!=null&&h.length&&l);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let d;if(e<t){var f;const v=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=pn(r,a,e,v)}else d=a[a.length-1];if(d){const p=d.sn-i.startSN,v=this.fragmentTracker.getState(d);if((v===bt.OK||v===bt.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!i.live)&&d.level===r.level){const g=a[p+1];d.sn<o&&this.fragmentTracker.getState(g)!==bt.OK?d=g:d=null}}return d}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&de(r);if(a||!o&&!r){Ov(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;a!==null&&de(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Et(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==te.FRAG_LOADING_WAITING_RETRY)&&(this.state=te.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const g=this.getCurrentContext(t.chunkMeta);g&&(t.frag=g.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const a=t.details===H.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const o=t.errorAction;if(!o){this.state=te.ERROR;return}const{action:l,flags:c,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&l===It.RetryRequest,p=d&&!o.resolved&&c===Yt.MoveAllAlternatesMatchingHost,v=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&p&&Et(n)&&!n.endList&&v&&!qc(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((f||p)&&h<u.maxNumRetry){var m;const g=Va((m=t.response)==null?void 0:m.code),E=Ga(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=te.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,g){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${E}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&l!==It.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===It.SendAlternateToPenaltyBox?this.state=te.WAITING_LEVEL:this.state=te.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!Va(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=te.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===te.PARSING||this.state===te.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===ge.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==te.STOPPED&&(this.state=te.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Fe.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===te.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==te.STOPPED&&(this.state=te.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const h=e.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const d=n?0:bh(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(x.LEVEL_PTS_UPDATED,{details:r,level:i,drift:d,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)){var o;const l=((o=this.transmuxer)==null?void 0:o.error)===null;if((i.fragmentError===0||l&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),l){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(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=te.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(x.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ge.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Nh(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class kh{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Nv(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Nv(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<s.length;n++){const r=s[n];t.set(r,i),i+=r.length}return t}var eo={exports:{}},Bh;function kv(){return Bh||(Bh=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new n(h,u||l,d),p=t?t+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,p){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],g=arguments.length,E,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),g){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,d),!0;case 5:return m.fn.call(m.context,h,u,d,f),!0;case 6:return m.fn.call(m.context,h,u,d,f,p),!0}for(_=1,E=new Array(g-1);_<g;_++)E[_-1]=arguments[_];m.fn.apply(m.context,E)}else{var T=m.length,b;for(_=0;_<T;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),g){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,h);break;case 3:m[_].fn.call(m[_].context,h,u);break;case 4:m[_].fn.call(m[_].context,h,u,d);break;default:if(!E)for(b=1,E=new Array(g-1);b<g;b++)E[b-1]=arguments[b];m[_].fn.apply(m[_].context,E)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var p=this._events[f];if(p.fn)p.fn===h&&(!d||p.once)&&(!u||p.context===u)&&a(this,f);else{for(var v=0,m=[],g=p.length;v<g;v++)(p[v].fn!==h||d&&!p[v].once||u&&p[v].context!==u)&&m.push(p[v]);m.length?this._events[f]=m.length===1?m[0]:m:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o}(eo)),eo.exports}var Bv=kv(),to=p0(Bv);const _s="1.6.16",qn={};function Gv(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Vv(){const s=qn[_s];if(s)return s.clientCount++,s;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 qn[_s]=n,n}function Hv(s){const e=qn[s];if(e)return e.clientCount++,e;const t=new self.URL(s,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return qn[s]=n,n}function $v(s){const e=qn[s||_s];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete qn[s||_s],n&&self.URL.revokeObjectURL(n),i.terminate()}}function Gh(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function io(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function Rr(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function Es(s,e){const t=e;let i=0;for(;io(s,e);){i+=10;const n=Rr(s,e+6);i+=n,Gh(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)}function zv(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);s.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,c="mp4a.40."+o,h=n[a];let u=a;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|l<<3];return tt.log(`manifest codec:${i}, parsed codec:${c}, channels:${l}, rate:${h} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:h,channelCount:l,codec:c,parsedCodec:c,manifestCodec:i}}function Vh(s,e){return s[e]===255&&(s[e+1]&246)===240}function Hh(s,e){return s[e+1]&1?7:9}function no(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function Wv(s,e){return e+5<s.length}function Mr(s,e){return e+1<s.length&&Vh(s,e)}function Kv(s,e){return Wv(s,e)&&Vh(s,e)&&no(s,e)<=s.length-e}function Xv(s,e){if(Mr(s,e)){const t=Hh(s,e);if(e+t>=s.length)return!1;const i=no(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Mr(s,n)}return!1}function $h(s,e,t,i,n){if(!s.samplerate){const r=zv(e,t,i,n);if(!r)return;at(s,r)}}function zh(s){return 9216e4/s}function Yv(s,e){const t=Hh(s,e);if(e+t<=s.length){const i=no(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Wh(s,e,t,i,n){const r=zh(s.samplerate),a=i+n*r,o=Yv(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,p=Math.max(0,t+f-e.length);p?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const v={unit:l,pts:a};return p||s.samples.push(v),{sample:v,length:f,missing:p}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}function qv(s,e){return io(s,e)&&Rr(s,e+6)+10<=s.length-e}function jv(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function so(s,e=0,t=1/0){return Qv(s,e,t,Uint8Array)}function Qv(s,e,t,i){const n=Zv(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=Jv(s)?s.byteOffset:0,o=(a+s.byteLength)/r,l=(a+e)/r,c=Math.floor(Math.max(0,Math.min(l,o))),h=Math.floor(Math.min(c+Math.max(t,0),o));return new i(n,c,h-c)}function Zv(s){return s instanceof ArrayBuffer?s:s.buffer}function Jv(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function e_(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=s.data.subarray(1).indexOf(0);if(i===-1)return;const n=ti(so(s.data,1,i)),r=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=ti(so(s.data,3+i,a));let l;return n==="-->"?l=ti(so(s.data,4+i+a)):l=jv(s.data.subarray(4+i+a)),e.mimeType=n,e.pictureType=r,e.description=o,e.data=l,e}function t_(s){if(s.size<2)return;const e=ti(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function i_(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=ti(s.data.subarray(t),!0);t+=i.length+1;const n=ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=ti(s.data.subarray(1));return{key:s.type,info:"",data:e}}function n_(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=ti(s.data.subarray(t),!0);t+=i.length+1;const n=ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=ti(s.data);return{key:s.type,info:"",data:e}}function s_(s){return s.type==="PRIV"?t_(s):s.type[0]==="W"?n_(s):s.type==="APIC"?e_(s):i_(s)}function r_(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Rr(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const Lr=10,a_=10;function Kh(s){let e=0;const t=[];for(;io(s,e);){const i=Rr(s,e+6);s[e+5]>>6&1&&(e+=Lr),e+=Lr;const n=e+i;for(;e+a_<n;){const r=r_(s.subarray(e)),a=s_(r);a&&t.push(a),e+=r.size+Lr}Gh(s,e)&&(e+=Lr)}return t}function Xh(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function o_(s){if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function ro(s){const e=Kh(s);for(let t=0;t<e.length;t++){const i=e[t];if(Xh(i))return o_(i)}}let jt=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function bi(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ao{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=ci(this.cachedData,e),this.cachedData=null);let i=Es(e,0),n=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?ro(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=l_(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:jt.audioId3,duration:Number.POSITIVE_INFINITY});n<c;){if(this.canParse(e,n)){const h=this.appendFrame(a,e,n);h?(this.frameIndex++,this.lastPTS=h.sample.pts,n+=h.length,r=n):n=c}else qv(e,n)?(i=Es(e,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:jt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,r=n):n++;if(n===c&&r!==c){const h=e.slice(r);this.cachedData?this.cachedData=ci(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:bi(),id3Track:o,textTrack:bi()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:bi(),id3Track:this._id3Track,textTrack:bi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const l_=(s,e,t)=>{if(de(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Ir=null;const c_=[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],h_=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],u_=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],d_=[0,1,1,4];function Yh(s,e,t,i,n){if(t+24>e.length)return;const r=qh(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+n*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function qh(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=c_[l*14+n-1]*1e3,u=h_[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=u_[t][i],p=d_[i],v=f*8*p,m=Math.floor(f*c/u+a)*p;if(Ir===null){const _=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ir=_?parseInt(_[1]):0}return!!Ir&&Ir<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:u,channelCount:d,frameLength:m,samplesPerFrame:v}}}function oo(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function jh(s,e){return e+1<s.length&&oo(s,e)}function f_(s,e){return oo(s,e)&&4<=s.length-e}function Qh(s,e){if(e+1<s.length&&oo(s,e)){const i=qh(s,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const r=e+n;return r===s.length||jh(s,r)}return!1}class p_ extends ao{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Es(e,0);let n=(i==null?void 0:i.length)||0;if(Qh(e,n))return!1;for(let r=e.length;n<r;n++)if(Xv(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Kv(e,t)}appendFrame(e,t,i){$h(e,this.observer,t,i,e.manifestCodec);const n=Wh(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const Zh=(s,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,n[0]=(a[0]&r[0])>>l,t=t?t<<o|n[0]:n[0],e+=1,i-=o}return t};class m_ extends ao{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=Jh(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Es(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&ro(t)!==void 0&&Zh(e,i)<16}}function Jh(s,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,v=[2,1,2,3,3,4,4,5][u]+f,m=e[t+5]>>3,g=e[t+5]&7,E=new Uint8Array([r<<6|m<<1|g>>2,(g&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),_=1536/o*9e4,T=i+n*_,b=e.subarray(t,t+h);return s.config=E,s.channelCount=v,s.samplerate=o,s.samples.push({unit:b,pts:T}),h}class g_ extends ao{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Es(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&ro(t)!==void 0&&Zh(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(Qh(e,i))return tt.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return f_(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Yh(e,t,i,this.basePTS,this.frameIndex)}}const v_=/\/emsg[-/]ID3/i;class __{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,n){const r=this.videoTrack=bi("video",1),a=this.audioTrack=bi("audio",1),o=this.txtTrack=bi("text",1);if(this.id3Track=bi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Rc(e);if(l.video){const{id:c,timescale:h,codec:u,supplemental:d}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=yc.text,r.sampleDuration=0,r.duration=a.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return _0(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ci(this.remainderData,e));const o=b0(i);this.remainderData=o.remainder,n.samples=o.valid||new Uint8Array}else n.samples=i;const a=this.extractID3Track(n,t);return r.samples=Ic(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=Ic(e,t),{videoTrack:t,audioTrack:bi(),id3Track:n,textTrack:bi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=We(e.samples,["emsg"]);n&&n.forEach(r=>{const a=M0(r);if(v_.test(a.schemeIdUri)){const o=eu(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:jt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=eu(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:jt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function eu(s,e){return de(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class E_{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ha(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Zi.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)i.set(e.subarray(r,r+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)e.set(i.subarray(n,n+16),r);return e}decryptAvcSample(e,t,i,n,r){const a=Cc(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(n)}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}class tu{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const a=r,o=[];let l=0,c,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,l=1);l<n;){if(c=t[l++],!r){r=c?0:1;continue}if(r===1){r=c?0:2;continue}if(!c)r=3;else if(c===1){if(h=l-r-1,d>=0){const p={data:t.subarray(d,h),type:f};o.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(a&&l<=4-a&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-a)),h>0&&(p.data=ci(p.data,t.subarray(0,h)),p.state=0))}l<n?(u=this.getNALuType(t,l),d=l,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const p={data:t.subarray(d,n),type:f,state:r};o.push(p)}if(o.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=ci(p.data,t))}return e.naluState=r,o}}class xs{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&tt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class x_ extends tu{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,o,l=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(c=>{var h,u;switch(c.type){case 1:{let v=!1;o=!0;const m=c.data;if(l&&m.length>4){const g=this.readSliceType(m);(g===2||g===4||g===7||g===9)&&(v=!0)}if(v){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=v;break}case 5:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Pa(c.data,1,i.pts,t.samples);break}case 7:{var f,p;o=!0,l=!0;const v=c.data,m=this.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||((f=e.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];const g=v.subarray(1,4);let E="avc1.";for(let _=0;_<3;_++){let T=g[_].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break}case 8:o=!0,e.pps=[c.data];break;case 9:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(c)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new xs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let a=0;a<e;a++)n!==0&&(r=t.readEG(),n=(i+r+256)%256),i=n===0?i:n}readSPS(e){const t=new xs(e);let i=0,n=0,r=0,a=0,o,l,c;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),v=t.skipEG.bind(t),m=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);h();const E=h();if(u(5),p(3),h(),m(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const C=d();if(C===3&&p(1),m(),m(),p(1),f())for(l=C!==3?8:12,c=0;c<l;c++)f()&&(c<6?g(16,t):g(64,t))}m();const _=d();if(_===0)d();else if(_===1)for(p(1),v(),v(),o=d(),c=0;c<o;c++)v();m(),p(1);const T=d(),b=d(),R=u(1);R===0&&p(1),p(1),f()&&(i=d(),n=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((T+1)*16-i*2-n*2),height:(2-R)*(b+1)*16-(R?2:4)*(r+a),pixelRatio:A}}}class S_ extends tu{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,o,l=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(c=>{var h,u;switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Pa(c.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=at(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(c.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in f.params)e.params[p]=f.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(c.data);for(const p in f)e.params[p]=f[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}a&&o&&a.units.push(c)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new xs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new xs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=t.readUByte(),g=t.readUByte(),E=[],_=[];for(let le=0;le<i;le++)E.push(t.readBoolean()),_.push(t.readBoolean());if(i>0)for(let le=i;le<8;le++)t.readBits(2);for(let le=0;le<i;le++)E[le]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),_[le]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const b=t.readUEG(),R=t.readUEG(),A=t.readBoolean();let C=0,S=0,y=0,w=0;A&&(C+=t.readUEG(),S+=t.readUEG(),y+=t.readUEG(),w+=t.readUEG());const U=t.readUEG(),X=t.readUEG(),P=t.readUEG(),F=t.readBoolean();for(let le=F?0:i;le<=i;le++)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 $e=0;$e<4;$e++)for(let Me=0;Me<($e===3?2:6);Me++)if(!t.readBoolean())t.readUEG();else{const M=Math.min(64,1<<4+($e<<1));$e>1&&t.readEG();for(let K=0;K<M;K++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let B=0;for(let le=0;le<N;le++){let $e=!1;if(le!==0&&($e=t.readBoolean()),$e){le===N&&t.readUEG(),t.readBoolean(),t.readUEG();let Me=0;for(let I=0;I<=B;I++){const M=t.readBoolean();let K=!1;M||(K=t.readBoolean()),(M||K)&&Me++}B=Me}else{const Me=t.readUEG(),I=t.readUEG();B=Me+I;for(let M=0;M<Me;M++)t.readUEG(),t.readBoolean();for(let M=0;M<I;M++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const le=t.readUEG();for(let $e=0;$e<le;$e++){for(let Me=0;Me<P+4;Me++)t.readBits(1);t.readBits(1)}}let V=0,W=1,$=1,ee=!0,ie=1,oe=0;t.readBoolean(),t.readBoolean();let me=!1;if(t.readBoolean()){if(t.readBoolean()){const ne=t.readUByte(),re=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ae=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ne>0&&ne<16?(W=re[ne-1],$=ae[ne-1]):ne===255&&(W=t.readBits(16),$=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(),me=t.readBoolean(),me&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),oe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const ae=t.readBoolean(),ye=t.readBoolean();let ue=!1;(ae||ye)&&(ue=t.readBoolean(),ue&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ue&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let _e=0;_e<=i;_e++){ee=t.readBoolean();const Ie=ee||t.readBoolean();let ke=!1;Ie?t.readEG():ke=t.readBoolean();const se=ke?1:t.readUEG()+1;if(ae)for(let Ze=0;Ze<se;Ze++)t.readUEG(),t.readUEG(),ue&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ye)for(let Ze=0;Ze<se;Ze++)t.readUEG(),t.readUEG(),ue&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),V=t.readUEG())}let be=b,Te=R;if(A){let le=1,$e=1;T===1?le=$e=2:T==2&&(le=2),be=b-le*S-le*C,Te=R-$e*w-$e*y}const Ge=n?["A","B","C"][n]:"",Y=o<<24|l<<16|c<<8|h;let Rt=0;for(let le=0;le<32;le++)Rt=(Rt|(Y>>le&1)<<31-le)>>>0;let Re=Rt.toString(16);return a===1&&Re==="2"&&(Re="6"),{codecString:`hvc1.${Ge}${a}.${Re}.${r?"H":"L"}${g}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[u,d,f,p,v,m],general_level_idc:g,bit_depth:U+8,bit_depth_luma_minus8:U,bit_depth_chroma_minus8:X,min_spatial_segmentation_idc:V,chroma_format_idc:T,frame_rate:{fixed:ee,fps:oe/ie}},width:be,height:Te,pixelRatio:[W,$]}}readPPS(e){const t=new xs(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(),r=t.readBoolean();let a=1;return r&&n?a=0:r?a=3:n&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const wt=188;class Ji{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=Ji.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(wt*5,t-wt)+1,n=0;for(;n<i;){let r=!1,a=-1,o=0;for(let l=n;l<t;l+=wt)if(e[l]===71&&(t-l===wt||e[l+wt]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+wt*99,e.length-wt)+1)),r||(r=lo(e,l)===0),r&&o>1&&(a===0&&o>2||l+wt>i))return a}else{if(o)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:yc[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ji.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Ji.createTrack("audio",n),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,f=l.pid,p=o.pesData,v=l.pesData,m=null,g=this.pmtParsed,E=this._pmtId,_=e.length;if(this.remainderData&&(e=ci(this.remainderData,e),_=e.length,this.remainderData=null),_<wt&&!n)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const T=Math.max(0,Ji.syncOffset(e));_-=(_-T)%wt,_<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,_,e.buffer.byteLength-_));let b=0;for(let A=T;A<_;A+=wt)if(e[A]===71){const C=!!(e[A+1]&64),S=lo(e,A),y=(e[A+3]&48)>>4;let w;if(y>1){if(w=A+5+e[A+4],w===A+wt)continue}else w=A+4;switch(S){case h:C&&(u&&(r=jn(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,c,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,A+wt)),u.size+=A+wt-w);break;case d:if(C){if(p&&(r=jn(p,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}p={data:[],size:0}}p&&(p.data.push(e.subarray(w,A+wt)),p.size+=A+wt-w);break;case f:C&&(v&&(r=jn(v,this.logger))&&this.parseID3PES(l,r),v={data:[],size:0}),v&&(v.data.push(e.subarray(w,A+wt)),v.size+=A+wt-w);break;case 0:C&&(w+=e[w]+1),E=this._pmtId=y_(e,w);break;case E:{C&&(w+=e[w]+1);const U=T_(e,w,this.typeSupported,i,this.observer,this.logger);h=U.videoPid,h>0&&(a.pid=h,a.segmentCodec=U.segmentVideoCodec),d=U.audioPid,d>0&&(o.pid=d,o.segmentCodec=U.segmentAudioCodec),f=U.id3Pid,f>0&&(l.pid=f),m!==null&&!g&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,A=T-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=S;break}}else b++;b>0&&co(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=p,l.pesData=v;const R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return n&&this.extractRemainingSamples(R),R}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,a=i.pesData,o=t.pesData,l=n.pesData;let c;if(a&&(c=jn(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,c,!0),i.pesData=null)):i.pesData=a,o&&(c=jn(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=jn(l,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new E_(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new x_:e==="hevc"&&(this.videoParser=new S_))}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const u=n.missing,d=n.sample.unit.byteLength;if(u===-1)r=ci(n.sample.unit,r);else{const f=d-u;n.sample.unit.set(r.subarray(0,u),f),e.samples.push(n.sample),i=n.missing}}let a,o;for(a=i,o=r.length;a<o-1&&!Mr(r,a);a++);if(a!==i){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",co(this.observer,new Error(u),d,this.logger),!d)return}$h(e,this.observer,r,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const u=zh(e.samplerate);l=n.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;a<o;)if(h=Wh(e,r,a,l,c),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;a<o-1&&!Mr(r,a);a++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<n;)if(jh(i,a)){const l=Yh(e,i,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let a=0,o=0,l;for(;o<r&&(l=Jh(e,i,o,n,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=at({},t,{type:this._videoTrack?jt.emsg:jt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function lo(s,e){return((s[e+1]&31)<<8)+s[e+2]}function y_(s,e){return(s[e+10]&31)<<8|s[e+11]}function T_(s,e,t,i,n,r){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],l=e+3+o-4,c=(s[e+10]&15)<<8|s[e+11];for(e+=12+c;e<l;){const h=lo(s,e),u=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){ho("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!i){ho("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3");break;case 193:if(!i){ho("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(s[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3");break}const v=s[d+1]+2;d+=v,f-=v}}break;case 194:case 135:return co(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return a}function co(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ho(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function jn(s,e){let t=0,i,n,r,a,o;const l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=ci(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const h=i[7];h&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,h&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>54e5&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=i[8];let u=r+9;if(s.size<=u)return null;s.size-=u;const d=new Uint8Array(s.size);for(let f=0,p=l.length;f<p;f++){i=l[f];let v=i.byteLength;if(u)if(u>v){u-=v;continue}else i=i.subarray(u),v-=u,u=0;d.set(i,t),t+=v}return n&&(n-=r+3),{data:d,pts:a,dts:o,len:n}}return null}class A_{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 en=Math.pow(2,32)-1;class G{static init(){G.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 G.types)G.types.hasOwnProperty(e)&&(G.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);G.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);G.STTS=G.STSC=G.STCO=r,G.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),G.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),G.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),G.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);G.FTYP=G.box(G.types.ftyp,a,l,a,o),G.DINF=G.box(G.types.dinf,G.box(G.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),n=0,i=8;n<r;n++)a.set(t[n],i),i+=t[n].byteLength;return a}static hdlr(e){return G.box(G.types.hdlr,G.HDLR_TYPES[e])}static mdat(e){return G.box(G.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(en+1)),n=Math.floor(t%(en+1));return G.box(G.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return G.box(G.types.mdia,G.mdhd(e.timescale||0,e.duration||0),G.hdlr(e.type),G.minf(e))}static mfhd(e){return G.box(G.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"?G.box(G.types.minf,G.box(G.types.smhd,G.SMHD),G.DINF,G.stbl(e)):G.box(G.types.minf,G.box(G.types.vmhd,G.VMHD),G.DINF,G.stbl(e))}static moof(e,t,i){return G.box(G.types.moof,G.mfhd(e),G.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=G.trak(e[t]);return G.box.apply(null,[G.types.moov,G.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(G.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=G.trex(e[t]);return G.box.apply(null,[G.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(en+1)),n=Math.floor(t%(en+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return G.box(G.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n<t.length;n++)r=t[n].flags,i[n+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return G.box(G.types.sdtp,i)}static stbl(e){return G.box(G.types.stbl,G.stsd(e),G.box(G.types.stts,G.STTS),G.box(G.types.stsc,G.STSC),G.box(G.types.stsz,G.STSZ),G.box(G.types.stco,G.STCO))}static avc1(e){let t=[],i=[],n,r,a;for(n=0;n<e.sps.length;n++)r=e.sps[n],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n<e.pps.length;n++)r=e.pps[n],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=G.box(G.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return G.box(G.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&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 G.box(G.types.mp4a,G.audioStsd(e),G.box(G.types.esds,G.esds(e)))}static mp3(e){return G.box(G.types[".mp3"],G.audioStsd(e))}static ac3(e){return G.box(G.types["ac-3"],G.audioStsd(e),G.box(G.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return G.box(G.types.stsd,G.STSD,G.mp4a(e));if(t==="ac3"&&e.config)return G.box(G.types.stsd,G.STSD,G.ac3(e));if(t==="mp3"&&e.codec==="mp3")return G.box(G.types.stsd,G.STSD,G.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return G.box(G.types.stsd,G.STSD,G.avc1(e));if(t==="hevc"&&e.vps)return G.box(G.types.stsd,G.STSD,G.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,a=Math.floor(i/(en+1)),o=Math.floor(i%(en+1));return G.box(G.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=G.sdtp(e),n=e.id,r=Math.floor(t/(en+1)),a=Math.floor(t%(en+1));return G.box(G.types.traf,G.box(G.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),G.box(G.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),G.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,G.box(G.types.trak,G.tkhd(e),G.mdia(e))}static trex(e){const t=e.id;return G.box(G.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,a=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<n;o++)l=i[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return G.box(G.types.trun,a)}static initSegment(e){G.types||G.init();const t=G.moov(e);return ci(G.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let a=r.length;for(let p=0;p<i.length;p+=1){a+=3;for(let v=0;v<i[p].length;v+=1)a+=2+i[p][v].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=i.length-1;for(let p=0;p<i.length;p+=1){o.set(new Uint8Array([32+p|(p===l?128:0),0,i[p].length]),a),a+=3;for(let v=0;v<i[p].length;v+=1)o.set(new Uint8Array([i[p][v].length>>8,i[p][v].length&255]),a),a+=2,o.set(i[p][v],a),a+=i[p][v].length}const c=G.box(G.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return G.box(G.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,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}G.types=void 0,G.HDLR_TYPES=void 0,G.STTS=void 0,G.STSC=void 0,G.STCO=void 0,G.STSZ=void 0,G.VMHD=void 0,G.SMHD=void 0,G.STSD=void 0,G.FTYP=void 0,G.DINF=void 0;const iu=9e4;function uo(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function b_(s,e,t=1,i=!1){return uo(s,e,1/t,i)}function Ss(s,e=!1){return uo(s,1e3,1/iu,e)}function R_(s,e=1){return uo(s,iu,1/e)}function nu(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const M_=10*1e3,L_=1024,I_=1152,C_=1536;let Qn=null,fo=null;function su(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Cr extends li{constructor(e,t,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Qn===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qn=a?parseInt(a[1]):0}if(fo===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);fo=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&nu(t)} > ${e&&nu(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=ii(o,i),l=o-r),l>0?r:o},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,a,o,l){let c,h,u,d,f,p,v=r,m=r;const g=e.pid>-1,E=t.pid>-1,_=t.samples.length,T=e.samples.length>0,b=o&&_>0||_>1;if((!g||T)&&(!E||b)||this.ISGenerated||o){if(this.ISGenerated){var A,C,S,y;const P=this.videoTrackConfig;(P&&(t.width!==P.width||t.height!==P.height||((A=t.pixelRatio)==null?void 0:A[0])!==((C=P.pixelRatio)==null?void 0:C[0])||((S=t.pixelRatio)==null?void 0:S[1])!==((y=P.pixelRatio)==null?void 0:y[1]))||!P&&b||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,a));const w=this.isVideoContiguous;let U=-1,X;if(b&&(U=w_(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,U>0){this.warn(`Dropped ${U} out of ${_} video samples due to a missing keyframe`);const P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(U),t.dropped+=U,m+=(t.samples[0].pts-P)/t.inputTimeScale,X=m}else U===-1&&(this.warn(`No keyframe found out of ${_} video samples`),p=!1);if(this.ISGenerated){if(T&&b){const P=this.getVideoStartPts(t.samples),D=(ii(e.samples[0].pts,P)-P)/t.inputTimeScale;v+=Math.max(0,D),m+=Math.max(0,-D)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,v,this.isAudioContiguous,a,E||b||l===ge.AUDIO?m:void 0),b){const P=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,m,w,P)}}else b&&(c=this.remuxVideo(t,m,w,0));c&&(c.firstKeyFrame=U,c.independent=U!==-1,c.firstKeyFramePTS=X)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=ru(i,r,this._initPTS,this._initDTS)),n.samples.length&&(d=au(n,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:p,text:d,id3:f}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let a=ii(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${n}`);a<r+t;)a+=8589934592;return a-r}generateIS(e,t,i,n){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let h=!c||n,u="audio/mp4",d,f,p,v=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):G.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(v=e.id,p=e.inputTimeScale,!c||p!==c.timescale?d=f=this.computeInitPts(r[0].pts,p,i,"audio"):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:G.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(v=t.id,p=t.inputTimeScale,!c||p!==c.timescale){const m=this.getVideoStartPts(a),g=ii(a[0].dts,m),E=this.computeInitPts(g,p,i,"video"),_=this.computeInitPts(m,p,i,"video");f=Math.min(f,E),d=Math.min(d,_)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(c&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${i} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/p} (${d}/${p}) trackId: ${v}`),this._initPTS={baseTime:d,timescale:p,trackId:v},this._initDTS={baseTime:f,timescale:p,trackId:v}):d=p=void 0,{tracks:l,initPTS:d,timescale:p,trackId:v}}remuxVideo(e,t,i,n){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS,h=c.baseTime*r/c.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,p,v,m=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,E=!1;if(!i||u===null){const V=h+t*r,W=a[0].pts-ii(a[0].dts,a[0].pts);Qn&&u!==null&&Math.abs(V-W-(u+h))<15e3?i=!0:u=V-W-h}const _=u+h;for(let V=0;V<l;V++){const W=a[V];W.pts=ii(W.pts,_),W.dts=ii(W.dts,_),W.dts<a[V>0?V-1:V].dts&&(E=!0)}E&&a.sort(function(V,W){const $=V.dts-W.dts,ee=V.pts-W.pts;return $||ee}),p=a[0].dts,v=a[a.length-1].dts;const T=v-p,b=T?Math.round(T/(l-1)):f||e.inputTimeScale/30;if(i){const V=p-_,W=V>b,$=V<-1;if((W||$)&&(W?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ss(V,!0)} ms (${V}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ss(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!$||_>=a[0].pts||Qn)){p=_;const ee=a[0].pts-V;if(W)a[0].dts=p,a[0].pts=ee;else{let ie=!0;for(let oe=0;oe<a.length&&!(a[oe].dts>ee&&ie);oe++){const me=a[oe].pts;if(a[oe].dts-=V,a[oe].pts-=V,oe<a.length-1){const Se=a[oe+1].pts,be=a[oe].pts,Te=Se<=be,Ge=Se<=me;ie=Te==Ge}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ss(ee,!0)}/${Ss(p,!0)}, delta: ${Ss(V,!0)} ms`)}}p=Math.max(0,p);let R=0,A=0,C=p;for(let V=0;V<l;V++){const W=a[V],$=W.units,ee=$.length;let ie=0;for(let oe=0;oe<ee;oe++)ie+=$[oe].data.length;A+=ie,R+=ee,W.length=ie,W.dts<C?(W.dts=C,C+=b/4|0||1):C=W.dts,m=Math.min(W.pts,m),g=Math.max(W.pts,g)}v=a[l-1].dts;const S=A+4*R+8;let y;try{y=new Uint8Array(S)}catch(V){this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MUX_ERROR,details:H.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:S,reason:`fail allocating video mdat ${S}`});return}const w=new DataView(y.buffer);w.setUint32(0,S),y.set(G.types.mdat,4);let U=!1,X=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){const W=a[V],$=W.units;let ee=0;for(let me=0,Se=$.length;me<Se;me++){const be=$[me],Te=be.data,Ge=be.data.byteLength;w.setUint32(d,Ge),d+=4,y.set(Te,d),d+=Ge,ee+=4+Ge}let ie;if(V<l-1)f=a[V+1].dts-W.dts,ie=a[V+1].pts-W.pts;else{const me=this.config,Se=V>0?W.dts-a[V-1].dts:b;if(ie=V>0?W.pts-a[V-1].pts:b,me.stretchShortVideoTrack&&this.nextAudioTs!==null){const be=Math.floor(me.maxBufferHole*r),Te=(n?m+n*r:this.nextAudioTs+h)-W.pts;Te>be?(f=Te-Se,f<0?f=Se:U=!0,this.log(`It is approximately ${Te/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Se}else f=Se}const oe=Math.round(W.pts-W.dts);X=Math.min(X,f),F=Math.max(F,f),P=Math.min(P,ie),D=Math.max(D,ie),o.push(su(W.key,f,ee,oe))}if(o.length){if(Qn){if(Qn<70){const V=o[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(fo&&D-P<F-X&&b/F<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let V=p;for(let W=0,$=o.length;W<$;W++){const ee=V+o[W].duration,ie=V+o[W].cts;if(W<$-1){const oe=ee+o[W+1].cts;o[W].duration=oe-ie}else o[W].duration=W?o[W-1].duration:b;o[W].cts=0,V=ee}}}f=U||!f?b:f;const k=v+f;this.nextVideoTs=u=k-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const q={data1:G.moof(e.sequenceNumber++,p,at(e,{samples:o})),data2:y,startPTS:(m-h)/r,endPTS:(g+f-h)/r,startDTS:(p-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,q}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return I_;case"ac3":return C_;default:return L_}}remuxAudio(e,t,i,n,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),h=c*l,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=r!==void 0;let v=e.samples,m=d?0:8,g=this.nextAudioTs||-1;const E=u.baseTime*a/u.timescale,_=E+t*a;if(this.isAudioContiguous=i=i||v.length&&g>0&&(n&&Math.abs(_-(g+E))<9e3||Math.abs(ii(v[0].pts,_)-(g+E))<20*h),v.forEach(function(D){D.pts=ii(D.pts,_)}),!i||g<0){const D=v.length;if(v=v.filter(k=>k.pts>=0),D!==v.length&&this.warn(`Removed ${v.length-D} of ${D} samples (initPTS ${E} / ${a})`),!v.length)return;r===0?g=0:n&&!p?g=Math.max(0,_-E):g=v[0].pts-E}if(e.segmentCodec==="aac"){const D=this.config.maxAudioFramesDrift;for(let k=0,N=g+E;k<v.length;k++){const B=v[k],q=B.pts,V=q-N,W=Math.abs(1e3*V/a);if(V<=-D*h&&p)k===0&&(this.warn(`Audio frame @ ${(q/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*V/a)} ms.`),this.nextAudioTs=g=q-E,N=q);else if(V>=D*h&&W<M_&&p){let $=Math.round(V/h);for(N=q-$*h;N<0&&$&&h;)$--,N+=h;k===0&&(this.nextAudioTs=g=N-E),this.warn(`Injecting ${$} audio frames @ ${((N-E)/a).toFixed(3)}s due to ${Math.round(1e3*V/a)} ms gap.`);for(let ee=0;ee<$;ee++){let ie=A_.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=B.unit.subarray()),v.splice(k,0,{unit:ie,pts:N}),N+=h,k++}}B.pts=N,N+=h}}let T=null,b=null,R,A=0,C=v.length;for(;C--;)A+=v[C].unit.byteLength;for(let D=0,k=v.length;D<k;D++){const N=v[D],B=N.unit;let q=N.pts;if(b!==null){const W=f[D-1];W.duration=Math.round((q-b)/l)}else if(i&&e.segmentCodec==="aac"&&(q=g+E),T=q,A>0){A+=m;try{R=new Uint8Array(A)}catch(W){this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MUX_ERROR,details:H.REMUX_ALLOC_ERROR,fatal:!1,error:W,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(R.buffer).setUint32(0,A),R.set(G.types.mdat,4))}else return;R.set(B,m);const V=B.byteLength;m+=V,f.push(su(!0,c,V,0)),b=q}const S=f.length;if(!S)return;const y=f[f.length-1];g=b-E,this.nextAudioTs=g+l*y.duration;const w=d?new Uint8Array(0):G.moof(e.sequenceNumber++,T/l,at({},e,{samples:f}));e.samples=[];const U=(T-E)/a,X=this.nextAudioTs/a,F={data1:w,data2:R,startPTS:U,endPTS:X,startDTS:U,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,F}}function ii(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function w_(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function ru(s,e,t,i){const n=s.samples.length;if(!n)return;const r=s.inputTimeScale;for(let o=0;o<n;o++){const l=s.samples[o];l.pts=ii(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=ii(l.dts-i.baseTime*r/i.timescale,e*r)/r}const a=s.samples;return s.samples=[],{samples:a}}function au(s,e,t){const i=s.samples.length;if(!i)return;const n=s.inputTimeScale;for(let a=0;a<i;a++){const o=s.samples[a];o.pts=ii(o.pts-t.baseTime*n/t.timescale,e*n)/n}s.samples.sort((a,o)=>a.pts-o.pts);const r=s.samples;return s.samples=[],{samples:r}}class D_ extends li{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:a}=this.initData=Rc(e);if(t)y0(e,t);else{const l=r||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}r&&(i=ou(r,ot.AUDIO,this)),a&&(n=ou(a,ot.VIDEO,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,i,n,r,a){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((l=p)!=null&&l.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const v=A0(d,p,this),m=p.audio?v[p.audio.id]:null,g=p.video?v[p.video.id]:null,E=wr(g,1/0),_=wr(m,1/0),T=wr(g,0,!0),b=wr(m,0,!0);let R=r,A=0;const C=m&&(!g||!c&&_<E||c&&c.trackId===p.audio.id),S=C?m:g;if(S){const N=S.timescale,B=S.start-r*N,q=C?p.audio.id:p.video.id;R=S.start/N,A=C?b-_:T-E,(a||!c)&&(P_(c,R,r,A)||N!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${B/N} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${R-r} (${B}/${N}) trackId: ${q}`),c=null,f.initPTS=B,f.timescale=N,f.trackId=q)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=R,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const y=R-c.baseTime/c.timescale,w=y+A;A>0?this.lastEndTime=w:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const U=!!p.audio,X=!!p.video;let P="";U&&(P+="audio"),X&&(P+="video");const F=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),D={data1:d,startPTS:y,startDTS:y,endPTS:w,endDTS:w,type:P,hasAudio:U,hasVideo:X,nb:1,dropped:0,encrypted:F};u.audio=U&&!X?D:void 0,u.video=X?D:void 0;const k=g==null?void 0:g.sampleCount;if(k){const N=g.keyFrameIndex,B=N!==-1;D.nb=k,D.dropped=N===0||this.isVideoContiguous?0:B?N:k,D.independent=B,D.firstKeyFrame=N,B&&g.keyFrameStart&&(D.firstKeyFramePTS=(g.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(u.independent=B),this.isVideoContiguous||(this.isVideoContiguous=B),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${k} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=ru(i,r,c,c),n.samples.length&&(u.text=au(n,r,c)),u}}function wr(s,e,t=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function P_(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function ou(s,e,t){const i=s.codec;return i&&i.length>4?i:e===ot.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?dr(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Vi;try{Vi=self.performance.now.bind(self.performance)}catch{Vi=Date.now}const Dr=[{demux:__,remux:D_},{demux:Ji,remux:Cr},{demux:p_,remux:Cr},{demux:g_,remux:Cr}];Dr.splice(2,0,{demux:m_,remux:Cr});class lu{constructor(e,t,i,n,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=Vi();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=n||o,{audioCodec:v,videoCodec:m,defaultInitPts:g,duration:E,initSegmentData:_}=l,T=F_(a,t);if(T&&Xn(T.method)){const C=this.getDecrypter(),S=Wa(T.method);if(C.isSync()){let y=C.softwareDecrypt(a,T.key.buffer,T.iv.buffer,S);if(i.part>-1){const U=C.flush();y=U&&U.buffer}if(!y)return r.executeEnd=Vi(),po(i);a=new Uint8Array(y)}else return this.asyncResult=!0,this.decryptionPromise=C.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,S).then(y=>{const w=this.push(y,null,i);return this.decryptionPromise=null,w}),this.decryptionPromise}const b=this.needsProbing(h,u);if(b){const C=this.configureTransmuxer(a);if(C)return this.logger.warn(`[transmuxer] ${C.message}`),this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message}),r.executeEnd=Vi(),po(i)}(h||u||p||b)&&this.resetInitSegment(_,v,m,E,t),(h||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();const R=this.transmux(a,T,f,d,i);this.asyncResult=ys(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Vi(),R}flush(e){const t=e.transmuxing;t.executeStart=Vi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=n;if(i){const u=i.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=Vi();const u=[po(e)];return this.asyncResult?Promise.resolve(u):u}const h=l.flush(o);return ys(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===ge.MAIN?"level":"track"} ${i.level}`);const h=this.remuxer.remux(n,r,a,o,c,l,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Vi()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,n),o.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let u=0,d=Dr.length;u<d;u++){var a;if((a=Dr[u].demux)!=null&&a.probe(e,this.logger)){r=Dr[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=r.remux,h=r.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(i,t,n,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(i,t,n,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ha(this.config)),e}}function F_(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const po=s=>({remuxResult:{},chunkMeta:s});function ys(s){return"then"in s&&s.then instanceof Function}class O_{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class U_{constructor(e,t,i,n,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=a}}let cu=0;class hu{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=cu++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,h=this.hls;if(!(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{h.logger[c.data.logType]&&h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===x.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new to,this.observer.on(x.FRAG_DECRYPTED,a),this.observer.on(x.ERROR,a);const o=Fc(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||Gv()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Hv(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Vv());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:lt(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new lu(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new lu(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=cu++;const t=this.hls.config,i=Fc(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:lt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),$v(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:p}=this,v=a?a.start:r.start,m=r.decryptdata,g=this.frag,E=!(g&&r.cc===g.cc),_=!(g&&c.level===g.level),T=g?c.sn-g.sn:-1,b=this.part?c.part-this.part.index:-1,R=T===0&&c.id>1&&c.id===(g==null?void 0:g.stats.chunkCount),A=!_&&(T===1||T===0&&(b===1||R&&b<=0)),C=self.performance.now();(_||T||r.stats.parsing.start===0)&&(r.stats.parsing.start=C),a&&(b||!A)&&(a.stats.parsing.start=C);const S=!(g&&((u=r.initSegment)==null?void 0:u.url)===((d=g.initSegment)==null?void 0:d.url)),y=new U_(E,A,l,_,v,S);if(!A||E||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===ge.MAIN?"level":"track"}: ${c.level} id: ${c.id}
|
|
3701
|
+
${t.m3u8}`)}function Mh(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let a=0;if(r&&i<n.length)a=n[i].start;else if(r&&e.startSN===s.endSN+1)a=s.fragmentEnd;else if(r&&t)a=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=s.fragmentStart;else return;Ja(e,a)}function Ja(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e)}}function Lh(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const i=s.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ih(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function Ch(s,e,t){return s?wh(s.partList,e,t):null}function wh(s,e,t){if(s)for(let i=s.length;i--;){const n=s[i];if(n.index===t&&n.fragment.sn===e)return n}return null}function Dh(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Pv(s,e){return s!==e&&e?Ph(s)!==Ph(e):!1}function Ph(s){return s.replace(/\?[^?]*$/,"")}function vs(s,e){for(let i=0,n=s.length;i<n;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function Fv(s,e){return!!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function Fh(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Oh(s,e){const t=e.fragments;for(let i=0,n=t.length;i<n;i++)Fh(t[i],s);e.fragmentHint&&Fh(e.fragmentHint,s),e.alignedSliding=!0}function Ov(s,e){s&&(Uh(e,s),e.alignedSliding||Ar(e,s),!e.alignedSliding&&!e.skippedSegments&&Mh(s,e,!1))}function Uh(s,e){if(!Fv(e,s))return;const t=Math.min(e.endCC,s.endCC),i=vs(e.fragments,t),n=vs(s.fragments,t);if(!i||!n)return;tt.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=i.start-n.start;Oh(r,s)}function Ar(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let n,r;const a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(n=vs(i,a),r=vs(t,a)),(!n||!r)&&(n=i[Math.floor(i.length/2)],r=vs(t,n.cc)||t[Math.floor(t.length/2)]);const o=n.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-n.start);Oh(c,s)}function Ht(s,e,t){qt(s,e,t),s.addEventListener(e,t)}function qt(s,e,t){s.removeEventListener(e,t)}const Uv={toString:function(s){let e="";const t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},te={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 br extends nh{constructor(e,t,i,n,r){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=te.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:a,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,u=l?l.currentTime:0,d=Fe.bufferInfo(c||l,u,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${de(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===te.ENDED)this.resetLoadingState();else if(o){const p=a.maxFragLookUpTolerance,v=o.start-p,m=o.start+o.duration+p;if(f||m<d.start||v>d.end){const g=u>m;(u<v||g)&&(g&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(u>p&&(this.lastCurrentTime=u),!this.loadingParts){const v=Math.max(d.end,u),m=this.shouldLoadParts(this.getLevelDetails(),v);m&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${v.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===te.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new uv(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ha(e.config)}registerListeners(){const{hls:e}=this;e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===te.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=te.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Fe.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>n&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const h=l[l.length-1];return Fe.isBuffered(this.media,h.start+h.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Ht(i,"seeking",this.onMediaSeeking),Ht(i,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===te.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),qt(n,"seeking",this.onMediaSeeking),qt(n,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=te.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const n=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===te.FRAG_LOADING||!this.fragCurrent&&a===te.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=te.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(x.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===bt.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===bt.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(x.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:a}=i,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Xn(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Wa(o.method)).catch(c=>{throw n.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:r}),c}).then(c=>{const h=self.performance.now();return n.trigger(x.FRAG_DECRYPTED,{frag:r,payload:c,stats:{tstart:l,tdecrypt:h}}),i.payload=c,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==te.STOPPED&&(this.state=te.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(x.ERROR,{type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?Uv.toString(Fe.getBuffered(i)):"(detached)"})`),Et(e)){var n;if(e.type!==ge.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=te.IDLE;return}}const r=(n=this.levels)==null?void 0:n[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=te.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(l=>!l),o=new Er(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=te.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(x.KEY_LOADED,d),this.state===te.KEY_LOADING&&(this.state=te.IDLE),d}),this.hls.trigger(x.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(Et(e)&&(!l||e.sn!==l.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=d)}if(i=Math.max(e.start,i||0),this.loadingParts&&Et(e)){const d=a.partList;if(d&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(d,e,i);if(f>-1){const p=d[f];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=te.FRAG_LOADING;let v;return o?v=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,p,t,n)).catch(m=>this.handleFragLoadError(m)):v=this.doFragPartsLoad(e,p,t,n).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(x.FRAG_LOADING,{frag:e,part:p,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}if(Et(e)&&this.loadingParts){var c;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(c=a.partList)==null?void 0:c.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),de(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=te.FRAG_LOADING;const h=this.config.progressive&&e.type!==ge.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,n)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?n:void 0),o]).then(([d])=>(!h&&n&&n(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(x.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,n){return new Promise((r,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,n).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(x.FRAG_LOADED,d);const p=Ch(i.details,e.sn,u.index+1)||wh(c,e.sn,u.index+1);if(p)h(p);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ee.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(x.ERROR,t)}else this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==te.PARSING){!this.fragCurrent&&this.state!==te.STOPPED&&this.state!==te.ERROR&&(this.state=te.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=c),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===ge.SUBTITLE)return!1;const a=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:a}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const o=t[n],l=o.details,c=a>-1?Ch(l,r,a):null,h=c?c.fragment:Ih(l,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:c,level:o}):null}bufferFragmentData(e,t,i,n,r){if(this.state!==te.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=ci(a,o)),!l.length)return;const c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:n,offset:h,parent:t.type,data:l};if(this.hls.trigger(x.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Fe.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Fe.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!de(n))return null;const a=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,a)}getFwdBufferInfoAtPos(e,t,i,n){const r=Fe.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,n);return Fe.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const n=e.nextStart;if(n&&i.start>n){const r=e.buffered;if(r){let a=e.len;const o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<i.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return r>=n?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=ge.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const u=r.initialLiveManifestSize;if(n<u)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const d=this.config.startPosition,f=this.hls.startPosition,p=this.hls.liveSyncPosition,v=((c=l)==null?void 0:c.start)||0;let m,g;f!==-1&&f>=a?(m=f,g=f===d?"config":"next load start"):p!==null?(m=p,g="live edge"):(m=e,g="buffer pos"),m<v&&(m=v,g="live frag start"),m<a&&(m=a,g="playlist start"),(this.startPosition!=m||this.nextLoadPosition!=m)&&(this.log(`Setting startPosition to ${m.toFixed(3)} ${f===-1?"":`(from ${d}) `}based on ${g}. live edge: ${p} live frag start: ${v.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=m)}}else e<=a&&(l=i[0]);if(!l){const u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(l,t);if(!h&&l){const u=l.sn-t.startSN;h=this.filterReplacedPrimary(i[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return i===bt.OK||i===bt.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,i,n,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(o!==null&&i.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Nh(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Nh(this.config)&&e.type!==ge.SUBTITLE){const i=this.hls.interstitialsManager,n=i==null?void 0:i.bufferingItem;if(n){const a=n.event;if(a){if(a.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 r=i==null?void 0:i.playerQueue;if(r)for(let a=r.length;a--;){const o=r[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,n>-1&&i<c.start)break;const h=c.loaded;h?n=-1:(r||(c.independent||a)&&c.fragment===t)&&(c.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${c.start}`),n=o),r=h}return n}loadedEndOfParts(e,t){let i;for(let n=e.length;n--;){if(i=e[n],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(n=ev(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Xc(e,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=n,h=i.partList,u=!!(this.loadingParts&&h!=null&&h.length&&l);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let d;if(e<t){var f;const v=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=pn(r,a,e,v)}else d=a[a.length-1];if(d){const p=d.sn-i.startSN,v=this.fragmentTracker.getState(d);if((v===bt.OK||v===bt.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!i.live)&&d.level===r.level){const g=a[p+1];d.sn<o&&this.fragmentTracker.getState(g)!==bt.OK?d=g:d=null}}return d}alignPlaylists(e,t,i){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&de(r);if(a||!o&&!r){Ov(i,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const n=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;a!==null&&de(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Et(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==te.FRAG_LOADING_WAITING_RETRY)&&(this.state=te.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const g=this.getCurrentContext(t.chunkMeta);g&&(t.frag=g.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const a=t.details===z.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const o=t.errorAction;if(!o){this.state=te.ERROR;return}const{action:l,flags:c,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&l===It.RetryRequest,p=d&&!o.resolved&&c===Yt.MoveAllAlternatesMatchingHost,v=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&p&&Et(n)&&!n.endList&&v&&!qc(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((f||p)&&h<u.maxNumRetry){var m;const g=Va((m=t.response)==null?void 0:m.code),E=Ga(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=te.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,g){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${E}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&l!==It.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===It.SendAlternateToPenaltyBox?this.state=te.WAITING_LEVEL:this.state=te.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!Va(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=te.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===te.PARSING||this.state===te.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===ge.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==te.STOPPED&&(this.state=te.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Fe.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===te.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==te.STOPPED&&(this.state=te.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const h=e.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const d=n?0:bh(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(x.LEVEL_PTS_UPDATED,{details:r,level:i,drift:d,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)){var o;const l=((o=this.transmuxer)==null?void 0:o.error)===null;if((i.fragmentError===0||l&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),l){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(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=te.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(x.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ge.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Nh(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class kh{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Nv(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Nv(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n<s.length;n++){const r=s[n];t.set(r,i),i+=r.length}return t}var eo={exports:{}},Bh;function kv(){return Bh||(Bh=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new n(h,u||l,d),p=t?t+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,p){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],g=arguments.length,E,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),g){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,d),!0;case 5:return m.fn.call(m.context,h,u,d,f),!0;case 6:return m.fn.call(m.context,h,u,d,f,p),!0}for(_=1,E=new Array(g-1);_<g;_++)E[_-1]=arguments[_];m.fn.apply(m.context,E)}else{var T=m.length,b;for(_=0;_<T;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),g){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,h);break;case 3:m[_].fn.call(m[_].context,h,u);break;case 4:m[_].fn.call(m[_].context,h,u,d);break;default:if(!E)for(b=1,E=new Array(g-1);b<g;b++)E[b-1]=arguments[b];m[_].fn.apply(m[_].context,E)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var p=this._events[f];if(p.fn)p.fn===h&&(!d||p.once)&&(!u||p.context===u)&&a(this,f);else{for(var v=0,m=[],g=p.length;v<g;v++)(p[v].fn!==h||d&&!p[v].once||u&&p[v].context!==u)&&m.push(p[v]);m.length?this._events[f]=m.length===1?m[0]:m:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o}(eo)),eo.exports}var Bv=kv(),to=p0(Bv);const _s="1.6.16",qn={};function Gv(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Vv(){const s=qn[_s];if(s)return s.clientCount++,s;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 qn[_s]=n,n}function Hv(s){const e=qn[s];if(e)return e.clientCount++,e;const t=new self.URL(s,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return qn[s]=n,n}function $v(s){const e=qn[s||_s];if(e&&e.clientCount--===1){const{worker:i,objectURL:n}=e;delete qn[s||_s],n&&self.URL.revokeObjectURL(n),i.terminate()}}function Gh(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function io(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function Rr(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function Es(s,e){const t=e;let i=0;for(;io(s,e);){i+=10;const n=Rr(s,e+6);i+=n,Gh(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)}function zv(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);s.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,c="mp4a.40."+o,h=n[a];let u=a;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|l<<3];return tt.log(`manifest codec:${i}, parsed codec:${c}, channels:${l}, rate:${h} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:h,channelCount:l,codec:c,parsedCodec:c,manifestCodec:i}}function Vh(s,e){return s[e]===255&&(s[e+1]&246)===240}function Hh(s,e){return s[e+1]&1?7:9}function no(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function Wv(s,e){return e+5<s.length}function Mr(s,e){return e+1<s.length&&Vh(s,e)}function Kv(s,e){return Wv(s,e)&&Vh(s,e)&&no(s,e)<=s.length-e}function Xv(s,e){if(Mr(s,e)){const t=Hh(s,e);if(e+t>=s.length)return!1;const i=no(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Mr(s,n)}return!1}function $h(s,e,t,i,n){if(!s.samplerate){const r=zv(e,t,i,n);if(!r)return;at(s,r)}}function zh(s){return 9216e4/s}function Yv(s,e){const t=Hh(s,e);if(e+t<=s.length){const i=no(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Wh(s,e,t,i,n){const r=zh(s.samplerate),a=i+n*r,o=Yv(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,p=Math.max(0,t+f-e.length);p?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const v={unit:l,pts:a};return p||s.samples.push(v),{sample:v,length:f,missing:p}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}function qv(s,e){return io(s,e)&&Rr(s,e+6)+10<=s.length-e}function jv(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function so(s,e=0,t=1/0){return Qv(s,e,t,Uint8Array)}function Qv(s,e,t,i){const n=Zv(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=Jv(s)?s.byteOffset:0,o=(a+s.byteLength)/r,l=(a+e)/r,c=Math.floor(Math.max(0,Math.min(l,o))),h=Math.floor(Math.min(c+Math.max(t,0),o));return new i(n,c,h-c)}function Zv(s){return s instanceof ArrayBuffer?s:s.buffer}function Jv(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function e_(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=s.data.subarray(1).indexOf(0);if(i===-1)return;const n=ti(so(s.data,1,i)),r=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=ti(so(s.data,3+i,a));let l;return n==="-->"?l=ti(so(s.data,4+i+a)):l=jv(s.data.subarray(4+i+a)),e.mimeType=n,e.pictureType=r,e.description=o,e.data=l,e}function t_(s){if(s.size<2)return;const e=ti(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function i_(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=ti(s.data.subarray(t),!0);t+=i.length+1;const n=ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=ti(s.data.subarray(1));return{key:s.type,info:"",data:e}}function n_(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=ti(s.data.subarray(t),!0);t+=i.length+1;const n=ti(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=ti(s.data);return{key:s.type,info:"",data:e}}function s_(s){return s.type==="PRIV"?t_(s):s.type[0]==="W"?n_(s):s.type==="APIC"?e_(s):i_(s)}function r_(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Rr(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const Lr=10,a_=10;function Kh(s){let e=0;const t=[];for(;io(s,e);){const i=Rr(s,e+6);s[e+5]>>6&1&&(e+=Lr),e+=Lr;const n=e+i;for(;e+a_<n;){const r=r_(s.subarray(e)),a=s_(r);a&&t.push(a),e+=r.size+Lr}Gh(s,e)&&(e+=Lr)}return t}function Xh(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function o_(s){if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function ro(s){const e=Kh(s);for(let t=0;t<e.length;t++){const i=e[t];if(Xh(i))return o_(i)}}let jt=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function bi(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ao{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=ci(this.cachedData,e),this.cachedData=null);let i=Es(e,0),n=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?ro(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&de(l))&&(this.basePTS=l_(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:jt.audioId3,duration:Number.POSITIVE_INFINITY});n<c;){if(this.canParse(e,n)){const h=this.appendFrame(a,e,n);h?(this.frameIndex++,this.lastPTS=h.sample.pts,n+=h.length,r=n):n=c}else qv(e,n)?(i=Es(e,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:jt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=i.length,r=n):n++;if(n===c&&r!==c){const h=e.slice(r);this.cachedData?this.cachedData=ci(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:bi(),id3Track:o,textTrack:bi()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:bi(),id3Track:this._id3Track,textTrack:bi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const l_=(s,e,t)=>{if(de(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Ir=null;const c_=[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],h_=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],u_=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],d_=[0,1,1,4];function Yh(s,e,t,i,n){if(t+24>e.length)return;const r=qh(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+n*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function qh(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=c_[l*14+n-1]*1e3,u=h_[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=u_[t][i],p=d_[i],v=f*8*p,m=Math.floor(f*c/u+a)*p;if(Ir===null){const _=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ir=_?parseInt(_[1]):0}return!!Ir&&Ir<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:u,channelCount:d,frameLength:m,samplesPerFrame:v}}}function oo(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function jh(s,e){return e+1<s.length&&oo(s,e)}function f_(s,e){return oo(s,e)&&4<=s.length-e}function Qh(s,e){if(e+1<s.length&&oo(s,e)){const i=qh(s,e);let n=4;i!=null&&i.frameLength&&(n=i.frameLength);const r=e+n;return r===s.length||jh(s,r)}return!1}class p_ extends ao{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Es(e,0);let n=(i==null?void 0:i.length)||0;if(Qh(e,n))return!1;for(let r=e.length;n<r;n++)if(Xv(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Kv(e,t)}appendFrame(e,t,i){$h(e,this.observer,t,i,e.manifestCodec);const n=Wh(e,t,i,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const Zh=(s,e)=>{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,n[0]=(a[0]&r[0])>>l,t=t?t<<o|n[0]:n[0],e+=1,i-=o}return t};class m_ extends ao{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const n=Jh(e,t,i,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Es(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&ro(t)!==void 0&&Zh(e,i)<16}}function Jh(s,e,t,i,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,v=[2,1,2,3,3,4,4,5][u]+f,m=e[t+5]>>3,g=e[t+5]&7,E=new Uint8Array([r<<6|m<<1|g>>2,(g&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),_=1536/o*9e4,T=i+n*_,b=e.subarray(t,t+h);return s.config=E,s.channelCount=v,s.samplerate=o,s.samples.push({unit:b,pts:T}),h}class g_ extends ao{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Es(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&ro(t)!==void 0&&Zh(e,i)<=16)return!1;for(let n=e.length;i<n;i++)if(Qh(e,i))return tt.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return f_(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Yh(e,t,i,this.basePTS,this.frameIndex)}}const v_=/\/emsg[-/]ID3/i;class __{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,n){const r=this.videoTrack=bi("video",1),a=this.audioTrack=bi("audio",1),o=this.txtTrack=bi("text",1);if(this.id3Track=bi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Rc(e);if(l.video){const{id:c,timescale:h,codec:u,supplemental:d}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=yc.text,r.sampleDuration=0,r.duration=a.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return _0(e)}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ci(this.remainderData,e));const o=b0(i);this.remainderData=o.remainder,n.samples=o.valid||new Uint8Array}else n.samples=i;const a=this.extractID3Track(n,t);return r.samples=Ic(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=Ic(e,t),{videoTrack:t,audioTrack:bi(),id3Track:n,textTrack:bi()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=We(e.samples,["emsg"]);n&&n.forEach(r=>{const a=M0(r);if(v_.test(a.schemeIdUri)){const o=eu(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:jt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=eu(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:jt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function eu(s,e){return de(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class E_{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ha(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Zi.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)i.set(e.subarray(r,r+16),n);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let n=0;for(let r=32;r<e.length-16;r+=160,n+=16)e.set(i.subarray(n,n+16),r);return e}decryptAvcSample(e,t,i,n,r){const a=Cc(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(n)}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}class tu{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const a=r,o=[];let l=0,c,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,l=1);l<n;){if(c=t[l++],!r){r=c?0:1;continue}if(r===1){r=c?0:2;continue}if(!c)r=3;else if(c===1){if(h=l-r-1,d>=0){const p={data:t.subarray(d,h),type:f};o.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(a&&l<=4-a&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-a)),h>0&&(p.data=ci(p.data,t.subarray(0,h)),p.state=0))}l<n?(u=this.getNALuType(t,l),d=l,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const p={data:t.subarray(d,n),type:f,state:r};o.push(p)}if(o.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=ci(p.data,t))}return e.naluState=r,o}}class xs{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&tt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class x_ extends tu{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,o,l=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(c=>{var h,u;switch(c.type){case 1:{let v=!1;o=!0;const m=c.data;if(l&&m.length>4){const g=this.readSliceType(m);(g===2||g===4||g===7||g===9)&&(v=!0)}if(v){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=v;break}case 5:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Pa(c.data,1,i.pts,t.samples);break}case 7:{var f,p;o=!0,l=!0;const v=c.data,m=this.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||((f=e.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];const g=v.subarray(1,4);let E="avc1.";for(let _=0;_<3;_++){let T=g[_].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break}case 8:o=!0,e.pps=[c.data];break;case 9:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(c)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new xs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let a=0;a<e;a++)n!==0&&(r=t.readEG(),n=(i+r+256)%256),i=n===0?i:n}readSPS(e){const t=new xs(e);let i=0,n=0,r=0,a=0,o,l,c;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),v=t.skipEG.bind(t),m=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);h();const E=h();if(u(5),p(3),h(),m(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const C=d();if(C===3&&p(1),m(),m(),p(1),f())for(l=C!==3?8:12,c=0;c<l;c++)f()&&(c<6?g(16,t):g(64,t))}m();const _=d();if(_===0)d();else if(_===1)for(p(1),v(),v(),o=d(),c=0;c<o;c++)v();m(),p(1);const T=d(),b=d(),R=u(1);R===0&&p(1),p(1),f()&&(i=d(),n=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((T+1)*16-i*2-n*2),height:(2-R)*(b+1)*16-(R?2:4)*(r+a),pixelRatio:A}}}class S_ extends tu{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,o,l=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(c=>{var h,u;switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Pa(c.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=at(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(c.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in f.params)e.params[p]=f.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(c.data);for(const p in f)e.params[p]=f[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}a&&o&&a.units.push(c)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new xs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new xs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=t.readUByte(),g=t.readUByte(),E=[],_=[];for(let le=0;le<i;le++)E.push(t.readBoolean()),_.push(t.readBoolean());if(i>0)for(let le=i;le<8;le++)t.readBits(2);for(let le=0;le<i;le++)E[le]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),_[le]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const b=t.readUEG(),R=t.readUEG(),A=t.readBoolean();let C=0,S=0,y=0,w=0;A&&(C+=t.readUEG(),S+=t.readUEG(),y+=t.readUEG(),w+=t.readUEG());const N=t.readUEG(),Y=t.readUEG(),D=t.readUEG(),F=t.readBoolean();for(let le=F?0:i;le<=i;le++)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 $e=0;$e<4;$e++)for(let Me=0;Me<($e===3?2:6);Me++)if(!t.readBoolean())t.readUEG();else{const M=Math.min(64,1<<4+($e<<1));$e>1&&t.readEG();for(let K=0;K<M;K++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const k=t.readUEG();let B=0;for(let le=0;le<k;le++){let $e=!1;if(le!==0&&($e=t.readBoolean()),$e){le===k&&t.readUEG(),t.readBoolean(),t.readUEG();let Me=0;for(let I=0;I<=B;I++){const M=t.readBoolean();let K=!1;M||(K=t.readBoolean()),(M||K)&&Me++}B=Me}else{const Me=t.readUEG(),I=t.readUEG();B=Me+I;for(let M=0;M<Me;M++)t.readUEG(),t.readBoolean();for(let M=0;M<I;M++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const le=t.readUEG();for(let $e=0;$e<le;$e++){for(let Me=0;Me<D+4;Me++)t.readBits(1);t.readBits(1)}}let P=0,V=1,G=1,J=!0,ie=1,oe=0;t.readBoolean(),t.readBoolean();let me=!1;if(t.readBoolean()){if(t.readBoolean()){const ne=t.readUByte(),re=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ae=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ne>0&&ne<16?(V=re[ne-1],G=ae[ne-1]):ne===255&&(V=t.readBits(16),G=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(),me=t.readBoolean(),me&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),oe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const ae=t.readBoolean(),ye=t.readBoolean();let ue=!1;(ae||ye)&&(ue=t.readBoolean(),ue&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ue&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let _e=0;_e<=i;_e++){J=t.readBoolean();const Ie=J||t.readBoolean();let ke=!1;Ie?t.readEG():ke=t.readBoolean();const se=ke?1:t.readUEG()+1;if(ae)for(let Ze=0;Ze<se;Ze++)t.readUEG(),t.readUEG(),ue&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ye)for(let Ze=0;Ze<se;Ze++)t.readUEG(),t.readUEG(),ue&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),P=t.readUEG())}let be=b,Te=R;if(A){let le=1,$e=1;T===1?le=$e=2:T==2&&(le=2),be=b-le*S-le*C,Te=R-$e*w-$e*y}const Ge=n?["A","B","C"][n]:"",q=o<<24|l<<16|c<<8|h;let Rt=0;for(let le=0;le<32;le++)Rt=(Rt|(q>>le&1)<<31-le)>>>0;let Re=Rt.toString(16);return a===1&&Re==="2"&&(Re="6"),{codecString:`hvc1.${Ge}${a}.${Re}.${r?"H":"L"}${g}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[u,d,f,p,v,m],general_level_idc:g,bit_depth:N+8,bit_depth_luma_minus8:N,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:P,chroma_format_idc:T,frame_rate:{fixed:J,fps:oe/ie}},width:be,height:Te,pixelRatio:[V,G]}}readPPS(e){const t=new xs(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(),r=t.readBoolean();let a=1;return r&&n?a=0:r?a=3:n&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const wt=188;class Ji{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=Ji.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(wt*5,t-wt)+1,n=0;for(;n<i;){let r=!1,a=-1,o=0;for(let l=n;l<t;l+=wt)if(e[l]===71&&(t-l===wt||e[l+wt]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+wt*99,e.length-wt)+1)),r||(r=lo(e,l)===0),r&&o>1&&(a===0&&o>2||l+wt>i))return a}else{if(o)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:yc[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ji.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Ji.createTrack("audio",n),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,f=l.pid,p=o.pesData,v=l.pesData,m=null,g=this.pmtParsed,E=this._pmtId,_=e.length;if(this.remainderData&&(e=ci(this.remainderData,e),_=e.length,this.remainderData=null),_<wt&&!n)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const T=Math.max(0,Ji.syncOffset(e));_-=(_-T)%wt,_<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,_,e.buffer.byteLength-_));let b=0;for(let A=T;A<_;A+=wt)if(e[A]===71){const C=!!(e[A+1]&64),S=lo(e,A),y=(e[A+3]&48)>>4;let w;if(y>1){if(w=A+5+e[A+4],w===A+wt)continue}else w=A+4;switch(S){case h:C&&(u&&(r=jn(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,c,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,A+wt)),u.size+=A+wt-w);break;case d:if(C){if(p&&(r=jn(p,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}p={data:[],size:0}}p&&(p.data.push(e.subarray(w,A+wt)),p.size+=A+wt-w);break;case f:C&&(v&&(r=jn(v,this.logger))&&this.parseID3PES(l,r),v={data:[],size:0}),v&&(v.data.push(e.subarray(w,A+wt)),v.size+=A+wt-w);break;case 0:C&&(w+=e[w]+1),E=this._pmtId=y_(e,w);break;case E:{C&&(w+=e[w]+1);const N=T_(e,w,this.typeSupported,i,this.observer,this.logger);h=N.videoPid,h>0&&(a.pid=h,a.segmentCodec=N.segmentVideoCodec),d=N.audioPid,d>0&&(o.pid=d,o.segmentCodec=N.segmentAudioCodec),f=N.id3Pid,f>0&&(l.pid=f),m!==null&&!g&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,A=T-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=S;break}}else b++;b>0&&co(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=p,l.pesData=v;const R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return n&&this.extractRemainingSamples(R),R}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,a=i.pesData,o=t.pesData,l=n.pesData;let c;if(a&&(c=jn(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,c,!0),i.pesData=null)):i.pesData=a,o&&(c=jn(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=jn(l,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new E_(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new x_:e==="hevc"&&(this.videoParser=new S_))}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const u=n.missing,d=n.sample.unit.byteLength;if(u===-1)r=ci(n.sample.unit,r);else{const f=d-u;n.sample.unit.set(r.subarray(0,u),f),e.samples.push(n.sample),i=n.missing}}let a,o;for(a=i,o=r.length;a<o-1&&!Mr(r,a);a++);if(a!==i){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",co(this.observer,new Error(u),d,this.logger),!d)return}$h(e,this.observer,r,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(n){const u=zh(e.samplerate);l=n.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;a<o;)if(h=Wh(e,r,a,l,c),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;a<o-1&&!Mr(r,a);a++);}parseMPEGPES(e,t){const i=t.data,n=i.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<n;)if(jh(i,a)){const l=Yh(e,i,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const i=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let a=0,o=0,l;for(;o<r&&(l=Jh(e,i,o,n,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=at({},t,{type:this._videoTrack?jt.emsg:jt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function lo(s,e){return((s[e+1]&31)<<8)+s[e+2]}function y_(s,e){return(s[e+10]&31)<<8|s[e+11]}function T_(s,e,t,i,n,r){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],l=e+3+o-4,c=(s[e+10]&15)<<8|s[e+11];for(e+=12+c;e<l;){const h=lo(s,e),u=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){ho("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!i){ho("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3");break;case 193:if(!i){ho("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(s[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3");break}const v=s[d+1]+2;d+=v,f-=v}}break;case 194:case 135:return co(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return a}function co(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ho(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function jn(s,e){let t=0,i,n,r,a,o;const l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=ci(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const h=i[7];h&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,h&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>54e5&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=i[8];let u=r+9;if(s.size<=u)return null;s.size-=u;const d=new Uint8Array(s.size);for(let f=0,p=l.length;f<p;f++){i=l[f];let v=i.byteLength;if(u)if(u>v){u-=v;continue}else i=i.subarray(u),v-=u,u=0;d.set(i,t),t+=v}return n&&(n-=r+3),{data:d,pts:a,dts:o,len:n}}return null}class A_{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 en=Math.pow(2,32)-1;class H{static init(){H.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in H.types)H.types.hasOwnProperty(e)&&(H.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);H.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);H.STTS=H.STSC=H.STCO=r,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 a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);H.FTYP=H.box(H.types.ftyp,a,l,a,o),H.DINF=H.box(H.types.dinf,H.box(H.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),n=0,i=8;n<r;n++)a.set(t[n],i),i+=t[n].byteLength;return a}static hdlr(e){return H.box(H.types.hdlr,H.HDLR_TYPES[e])}static mdat(e){return H.box(H.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(en+1)),n=Math.floor(t%(en+1));return H.box(H.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return H.box(H.types.mdia,H.mdhd(e.timescale||0,e.duration||0),H.hdlr(e.type),H.minf(e))}static mfhd(e){return H.box(H.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?H.box(H.types.minf,H.box(H.types.smhd,H.SMHD),H.DINF,H.stbl(e)):H.box(H.types.minf,H.box(H.types.vmhd,H.VMHD),H.DINF,H.stbl(e))}static moof(e,t,i){return H.box(H.types.moof,H.mfhd(e),H.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trak(e[t]);return H.box.apply(null,[H.types.moov,H.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(H.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=H.trex(e[t]);return H.box.apply(null,[H.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(en+1)),n=Math.floor(t%(en+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return H.box(H.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n<t.length;n++)r=t[n].flags,i[n+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return H.box(H.types.sdtp,i)}static stbl(e){return H.box(H.types.stbl,H.stsd(e),H.box(H.types.stts,H.STTS),H.box(H.types.stsc,H.STSC),H.box(H.types.stsz,H.STSZ),H.box(H.types.stco,H.STCO))}static avc1(e){let t=[],i=[],n,r,a;for(n=0;n<e.sps.length;n++)r=e.sps[n],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n<e.pps.length;n++)r=e.pps[n],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=H.box(H.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return H.box(H.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,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,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return H.box(H.types.mp4a,H.audioStsd(e),H.box(H.types.esds,H.esds(e)))}static mp3(e){return H.box(H.types[".mp3"],H.audioStsd(e))}static ac3(e){return H.box(H.types["ac-3"],H.audioStsd(e),H.box(H.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return H.box(H.types.stsd,H.STSD,H.mp4a(e));if(t==="ac3"&&e.config)return H.box(H.types.stsd,H.STSD,H.ac3(e));if(t==="mp3"&&e.codec==="mp3")return H.box(H.types.stsd,H.STSD,H.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return H.box(H.types.stsd,H.STSD,H.avc1(e));if(t==="hevc"&&e.vps)return H.box(H.types.stsd,H.STSD,H.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,a=Math.floor(i/(en+1)),o=Math.floor(i%(en+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,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=H.sdtp(e),n=e.id,r=Math.floor(t/(en+1)),a=Math.floor(t%(en+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,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),H.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,H.box(H.types.trak,H.tkhd(e),H.mdia(e))}static trex(e){const t=e.id;return H.box(H.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,a=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<n;o++)l=i[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return H.box(H.types.trun,a)}static initSegment(e){H.types||H.init();const t=H.moov(e);return ci(H.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let a=r.length;for(let p=0;p<i.length;p+=1){a+=3;for(let v=0;v<i[p].length;v+=1)a+=2+i[p][v].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=i.length-1;for(let p=0;p<i.length;p+=1){o.set(new Uint8Array([32+p|(p===l?128:0),0,i[p].length]),a),a+=3;for(let v=0;v<i[p].length;v+=1)o.set(new Uint8Array([i[p][v].length>>8,i[p][v].length&255]),a),a+=2,o.set(i[p][v],a),a+=i[p][v].length}const c=H.box(H.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=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,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,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([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&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 iu=9e4;function uo(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function b_(s,e,t=1,i=!1){return uo(s,e,1/t,i)}function Ss(s,e=!1){return uo(s,1e3,1/iu,e)}function R_(s,e=1){return uo(s,iu,1/e)}function nu(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const M_=10*1e3,L_=1024,I_=1152,C_=1536;let Qn=null,fo=null;function su(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Cr extends li{constructor(e,t,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Qn===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qn=a?parseInt(a[1]):0}if(fo===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);fo=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&nu(t)} > ${e&&nu(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=ii(o,i),l=o-r),l>0?r:o},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,a,o,l){let c,h,u,d,f,p,v=r,m=r;const g=e.pid>-1,E=t.pid>-1,_=t.samples.length,T=e.samples.length>0,b=o&&_>0||_>1;if((!g||T)&&(!E||b)||this.ISGenerated||o){if(this.ISGenerated){var A,C,S,y;const D=this.videoTrackConfig;(D&&(t.width!==D.width||t.height!==D.height||((A=t.pixelRatio)==null?void 0:A[0])!==((C=D.pixelRatio)==null?void 0:C[0])||((S=t.pixelRatio)==null?void 0:S[1])!==((y=D.pixelRatio)==null?void 0:y[1]))||!D&&b||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,a));const w=this.isVideoContiguous;let N=-1,Y;if(b&&(N=w_(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,N>0){this.warn(`Dropped ${N} out of ${_} video samples due to a missing keyframe`);const D=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(N),t.dropped+=N,m+=(t.samples[0].pts-D)/t.inputTimeScale,Y=m}else N===-1&&(this.warn(`No keyframe found out of ${_} video samples`),p=!1);if(this.ISGenerated){if(T&&b){const D=this.getVideoStartPts(t.samples),O=(ii(e.samples[0].pts,D)-D)/t.inputTimeScale;v+=Math.max(0,O),m+=Math.max(0,-O)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,v,this.isAudioContiguous,a,E||b||l===ge.AUDIO?m:void 0),b){const D=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,m,w,D)}}else b&&(c=this.remuxVideo(t,m,w,0));c&&(c.firstKeyFrame=N,c.independent=N!==-1,c.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=ru(i,r,this._initPTS,this._initDTS)),n.samples.length&&(d=au(n,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:p,text:d,id3:f}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let a=ii(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${n}`);a<r+t;)a+=8589934592;return a-r}generateIS(e,t,i,n){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let h=!c||n,u="audio/mp4",d,f,p,v=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):H.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(v=e.id,p=e.inputTimeScale,!c||p!==c.timescale?d=f=this.computeInitPts(r[0].pts,p,i,"audio"):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:H.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(v=t.id,p=t.inputTimeScale,!c||p!==c.timescale){const m=this.getVideoStartPts(a),g=ii(a[0].dts,m),E=this.computeInitPts(g,p,i,"video"),_=this.computeInitPts(m,p,i,"video");f=Math.min(f,E),d=Math.min(d,_)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(c&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${i} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/p} (${d}/${p}) trackId: ${v}`),this._initPTS={baseTime:d,timescale:p,trackId:v},this._initDTS={baseTime:f,timescale:p,trackId:v}):d=p=void 0,{tracks:l,initPTS:d,timescale:p,trackId:v}}remuxVideo(e,t,i,n){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS,h=c.baseTime*r/c.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,p,v,m=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,E=!1;if(!i||u===null){const P=h+t*r,V=a[0].pts-ii(a[0].dts,a[0].pts);Qn&&u!==null&&Math.abs(P-V-(u+h))<15e3?i=!0:u=P-V-h}const _=u+h;for(let P=0;P<l;P++){const V=a[P];V.pts=ii(V.pts,_),V.dts=ii(V.dts,_),V.dts<a[P>0?P-1:P].dts&&(E=!0)}E&&a.sort(function(P,V){const G=P.dts-V.dts,J=P.pts-V.pts;return G||J}),p=a[0].dts,v=a[a.length-1].dts;const T=v-p,b=T?Math.round(T/(l-1)):f||e.inputTimeScale/30;if(i){const P=p-_,V=P>b,G=P<-1;if((V||G)&&(V?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ss(P,!0)} ms (${P}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ss(-P,!0)} ms (${P}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!G||_>=a[0].pts||Qn)){p=_;const J=a[0].pts-P;if(V)a[0].dts=p,a[0].pts=J;else{let ie=!0;for(let oe=0;oe<a.length&&!(a[oe].dts>J&&ie);oe++){const me=a[oe].pts;if(a[oe].dts-=P,a[oe].pts-=P,oe<a.length-1){const Se=a[oe+1].pts,be=a[oe].pts,Te=Se<=be,Ge=Se<=me;ie=Te==Ge}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ss(J,!0)}/${Ss(p,!0)}, delta: ${Ss(P,!0)} ms`)}}p=Math.max(0,p);let R=0,A=0,C=p;for(let P=0;P<l;P++){const V=a[P],G=V.units,J=G.length;let ie=0;for(let oe=0;oe<J;oe++)ie+=G[oe].data.length;A+=ie,R+=J,V.length=ie,V.dts<C?(V.dts=C,C+=b/4|0||1):C=V.dts,m=Math.min(V.pts,m),g=Math.max(V.pts,g)}v=a[l-1].dts;const S=A+4*R+8;let y;try{y=new Uint8Array(S)}catch(P){this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:P,bytes:S,reason:`fail allocating video mdat ${S}`});return}const w=new DataView(y.buffer);w.setUint32(0,S),y.set(H.types.mdat,4);let N=!1,Y=Number.POSITIVE_INFINITY,D=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let P=0;P<l;P++){const V=a[P],G=V.units;let J=0;for(let me=0,Se=G.length;me<Se;me++){const be=G[me],Te=be.data,Ge=be.data.byteLength;w.setUint32(d,Ge),d+=4,y.set(Te,d),d+=Ge,J+=4+Ge}let ie;if(P<l-1)f=a[P+1].dts-V.dts,ie=a[P+1].pts-V.pts;else{const me=this.config,Se=P>0?V.dts-a[P-1].dts:b;if(ie=P>0?V.pts-a[P-1].pts:b,me.stretchShortVideoTrack&&this.nextAudioTs!==null){const be=Math.floor(me.maxBufferHole*r),Te=(n?m+n*r:this.nextAudioTs+h)-V.pts;Te>be?(f=Te-Se,f<0?f=Se:N=!0,this.log(`It is approximately ${Te/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Se}else f=Se}const oe=Math.round(V.pts-V.dts);Y=Math.min(Y,f),F=Math.max(F,f),D=Math.min(D,ie),O=Math.max(O,ie),o.push(su(V.key,f,J,oe))}if(o.length){if(Qn){if(Qn<70){const P=o[0].flags;P.dependsOn=2,P.isNonSync=0}}else if(fo&&O-D<F-Y&&b/F<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let P=p;for(let V=0,G=o.length;V<G;V++){const J=P+o[V].duration,ie=P+o[V].cts;if(V<G-1){const oe=J+o[V+1].cts;o[V].duration=oe-ie}else o[V].duration=V?o[V-1].duration:b;o[V].cts=0,P=J}}}f=N||!f?b:f;const $=v+f;this.nextVideoTs=u=$-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const X={data1:H.moof(e.sequenceNumber++,p,at(e,{samples:o})),data2:y,startPTS:(m-h)/r,endPTS:(g+f-h)/r,startDTS:(p-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,X}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return I_;case"ac3":return C_;default:return L_}}remuxAudio(e,t,i,n,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),h=c*l,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=r!==void 0;let v=e.samples,m=d?0:8,g=this.nextAudioTs||-1;const E=u.baseTime*a/u.timescale,_=E+t*a;if(this.isAudioContiguous=i=i||v.length&&g>0&&(n&&Math.abs(_-(g+E))<9e3||Math.abs(ii(v[0].pts,_)-(g+E))<20*h),v.forEach(function(O){O.pts=ii(O.pts,_)}),!i||g<0){const O=v.length;if(v=v.filter($=>$.pts>=0),O!==v.length&&this.warn(`Removed ${v.length-O} of ${O} samples (initPTS ${E} / ${a})`),!v.length)return;r===0?g=0:n&&!p?g=Math.max(0,_-E):g=v[0].pts-E}if(e.segmentCodec==="aac"){const O=this.config.maxAudioFramesDrift;for(let $=0,k=g+E;$<v.length;$++){const B=v[$],X=B.pts,P=X-k,V=Math.abs(1e3*P/a);if(P<=-O*h&&p)$===0&&(this.warn(`Audio frame @ ${(X/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*P/a)} ms.`),this.nextAudioTs=g=X-E,k=X);else if(P>=O*h&&V<M_&&p){let G=Math.round(P/h);for(k=X-G*h;k<0&&G&&h;)G--,k+=h;$===0&&(this.nextAudioTs=g=k-E),this.warn(`Injecting ${G} audio frames @ ${((k-E)/a).toFixed(3)}s due to ${Math.round(1e3*P/a)} ms gap.`);for(let J=0;J<G;J++){let ie=A_.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=B.unit.subarray()),v.splice($,0,{unit:ie,pts:k}),k+=h,$++}}B.pts=k,k+=h}}let T=null,b=null,R,A=0,C=v.length;for(;C--;)A+=v[C].unit.byteLength;for(let O=0,$=v.length;O<$;O++){const k=v[O],B=k.unit;let X=k.pts;if(b!==null){const V=f[O-1];V.duration=Math.round((X-b)/l)}else if(i&&e.segmentCodec==="aac"&&(X=g+E),T=X,A>0){A+=m;try{R=new Uint8Array(A)}catch(V){this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(R.buffer).setUint32(0,A),R.set(H.types.mdat,4))}else return;R.set(B,m);const P=B.byteLength;m+=P,f.push(su(!0,c,P,0)),b=X}const S=f.length;if(!S)return;const y=f[f.length-1];g=b-E,this.nextAudioTs=g+l*y.duration;const w=d?new Uint8Array(0):H.moof(e.sequenceNumber++,T/l,at({},e,{samples:f}));e.samples=[];const N=(T-E)/a,Y=this.nextAudioTs/a,F={data1:w,data2:R,startPTS:N,endPTS:Y,startDTS:N,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,F}}function ii(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function w_(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function ru(s,e,t,i){const n=s.samples.length;if(!n)return;const r=s.inputTimeScale;for(let o=0;o<n;o++){const l=s.samples[o];l.pts=ii(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=ii(l.dts-i.baseTime*r/i.timescale,e*r)/r}const a=s.samples;return s.samples=[],{samples:a}}function au(s,e,t){const i=s.samples.length;if(!i)return;const n=s.inputTimeScale;for(let a=0;a<i;a++){const o=s.samples[a];o.pts=ii(o.pts-t.baseTime*n/t.timescale,e*n)/n}s.samples.sort((a,o)=>a.pts-o.pts);const r=s.samples;return s.samples=[],{samples:r}}class D_ extends li{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:a}=this.initData=Rc(e);if(t)y0(e,t);else{const l=r||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}r&&(i=ou(r,ot.AUDIO,this)),a&&(n=ou(a,ot.VIDEO,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,i,n,r,a){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};de(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((l=p)!=null&&l.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const v=A0(d,p,this),m=p.audio?v[p.audio.id]:null,g=p.video?v[p.video.id]:null,E=wr(g,1/0),_=wr(m,1/0),T=wr(g,0,!0),b=wr(m,0,!0);let R=r,A=0;const C=m&&(!g||!c&&_<E||c&&c.trackId===p.audio.id),S=C?m:g;if(S){const k=S.timescale,B=S.start-r*k,X=C?p.audio.id:p.video.id;R=S.start/k,A=C?b-_:T-E,(a||!c)&&(P_(c,R,r,A)||k!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${B/k} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${R-r} (${B}/${k}) trackId: ${X}`),c=null,f.initPTS=B,f.timescale=k,f.trackId=X)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=R,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const y=R-c.baseTime/c.timescale,w=y+A;A>0?this.lastEndTime=w:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const N=!!p.audio,Y=!!p.video;let D="";N&&(D+="audio"),Y&&(D+="video");const F=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),O={data1:d,startPTS:y,startDTS:y,endPTS:w,endDTS:w,type:D,hasAudio:N,hasVideo:Y,nb:1,dropped:0,encrypted:F};u.audio=N&&!Y?O:void 0,u.video=Y?O:void 0;const $=g==null?void 0:g.sampleCount;if($){const k=g.keyFrameIndex,B=k!==-1;O.nb=$,O.dropped=k===0||this.isVideoContiguous?0:B?k:$,O.independent=B,O.firstKeyFrame=k,B&&g.keyFrameStart&&(O.firstKeyFramePTS=(g.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(u.independent=B),this.isVideoContiguous||(this.isVideoContiguous=B),O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${k}/${$} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=ru(i,r,c,c),n.samples.length&&(u.text=au(n,r,c)),u}}function wr(s,e,t=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function P_(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function ou(s,e,t){const i=s.codec;return i&&i.length>4?i:e===ot.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?dr(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Vi;try{Vi=self.performance.now.bind(self.performance)}catch{Vi=Date.now}const Dr=[{demux:__,remux:D_},{demux:Ji,remux:Cr},{demux:p_,remux:Cr},{demux:g_,remux:Cr}];Dr.splice(2,0,{demux:m_,remux:Cr});class lu{constructor(e,t,i,n,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=Vi();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=n||o,{audioCodec:v,videoCodec:m,defaultInitPts:g,duration:E,initSegmentData:_}=l,T=F_(a,t);if(T&&Xn(T.method)){const C=this.getDecrypter(),S=Wa(T.method);if(C.isSync()){let y=C.softwareDecrypt(a,T.key.buffer,T.iv.buffer,S);if(i.part>-1){const N=C.flush();y=N&&N.buffer}if(!y)return r.executeEnd=Vi(),po(i);a=new Uint8Array(y)}else return this.asyncResult=!0,this.decryptionPromise=C.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,S).then(y=>{const w=this.push(y,null,i);return this.decryptionPromise=null,w}),this.decryptionPromise}const b=this.needsProbing(h,u);if(b){const C=this.configureTransmuxer(a);if(C)return this.logger.warn(`[transmuxer] ${C.message}`),this.observer.emit(x.ERROR,x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message}),r.executeEnd=Vi(),po(i)}(h||u||p||b)&&this.resetInitSegment(_,v,m,E,t),(h||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();const R=this.transmux(a,T,f,d,i);this.asyncResult=ys(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Vi(),R}flush(e){const t=e.transmuxing;t.executeStart=Vi();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=n;if(i){const u=i.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=Vi();const u=[po(e)];return this.asyncResult?Promise.resolve(u):u}const h=l.flush(o);return ys(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===ge.MAIN?"level":"track"} ${i.level}`);const h=this.remuxer.remux(n,r,a,o,c,l,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Vi()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,n),o.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let u=0,d=Dr.length;u<d;u++){var a;if((a=Dr[u].demux)!=null&&a.probe(e,this.logger)){r=Dr[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=r.remux,h=r.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(i,t,n,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(i,t,n,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ha(this.config)),e}}function F_(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const po=s=>({remuxResult:{},chunkMeta:s});function ys(s){return"then"in s&&s.then instanceof Function}class O_{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class U_{constructor(e,t,i,n,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=a}}let cu=0;class hu{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=cu++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,h=this.hls;if(!(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{h.logger[c.data.logType]&&h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===x.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new to,this.observer.on(x.FRAG_DECRYPTED,a),this.observer.on(x.ERROR,a);const o=Fc(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||Gv()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Hv(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Vv());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:lt(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new lu(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new lu(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=cu++;const t=this.hls.config,i=Fc(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:lt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),$v(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:p}=this,v=a?a.start:r.start,m=r.decryptdata,g=this.frag,E=!(g&&r.cc===g.cc),_=!(g&&c.level===g.level),T=g?c.sn-g.sn:-1,b=this.part?c.part-this.part.index:-1,R=T===0&&c.id>1&&c.id===(g==null?void 0:g.stats.chunkCount),A=!_&&(T===1||T===0&&(b===1||R&&b<=0)),C=self.performance.now();(_||T||r.stats.parsing.start===0)&&(r.stats.parsing.start=C),a&&(b||!A)&&(a.stats.parsing.start=C);const S=!(g&&((u=r.initSegment)==null?void 0:u.url)===((d=g.initSegment)==null?void 0:d.url)),y=new U_(E,A,l,_,v,S);if(!A||E||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===ge.MAIN?"level":"track"}: ${c.level} id: ${c.id}
|
|
3702
3702
|
discontinuity: ${E}
|
|
3703
3703
|
trackSwitch: ${_}
|
|
3704
3704
|
contiguous: ${A}
|
|
3705
3705
|
accurateTimeOffset: ${l}
|
|
3706
3706
|
timeOffset: ${v}
|
|
3707
|
-
initSegmentChange: ${S}`);const w=new O_(i,n,t,o,h);this.configureTransmuxer(w)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:y},e instanceof ArrayBuffer?[e]:[]);else if(p){const w=p.push(e,m,c,y);ys(w)?w.then(U=>{this.handleTransmuxComplete(U)}).catch(U=>{this.transmuxerError(U,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);ys(n)?n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const uu=100;class du extends br{constructor(e,t,i){super(e,t,i,"audio-stream-controller",ge.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(x.BUFFER_RESET,this.onBufferReset,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(x.BUFFER_RESET,this.onBufferReset,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){if(i===ge.MAIN){const o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:r,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===te.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==o)&&this.syncWithAnchor(t,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===te.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(n==null?void 0:n.cc)===t.cc)return;const r=(n||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Xc(a,r,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===te.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=te.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(uu),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=te.IDLE):this.state=te.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case te.IDLE:this.doTickIdle();break;case te.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e==null?void 0:e[t],n=i==null?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=te.WAITING_INIT_PTS}break}case te.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case te.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=te.FRAG_LOADING;const o=n.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=te.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=te.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,ot.AUDIO,ge.AUDIO));const h=this.getFwdBufferInfo(c,ge.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(x.BUFFER_EOS,{type:"audio"}),this.state=te.ENDED;return}const u=h.len,d=t.maxBufferLength,f=l.fragments,p=f[0].start,v=this.getLoadPosition(),m=this.flushing?v:h.end;if(this.switchingTrack&&n){const _=v;l.PTSKnown&&_<p&&(h.end>p||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}if(u>=d&&!this.switchingTrack&&m<f[f.length-1].start)return;let g=this.getNextFragment(m,l);if(g&&this.isLoopLoading(g,m)&&(g=this.getNextFragmentLoopLoading(g,l,h,ge.MAIN,d)),!g){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,d,g))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&Et(g)&&!g.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===bt.OK&&(this.mainFragLoading=E=null),E&&Et(E))){if(g.start>E.end){const T=this.fragmentTracker.getFragAtPos(m,ge.MAIN);T&&T.end>E.end&&(E=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(g.start>E.end)return}this.loadFragment(g,o,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new zn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==te.STOPPED&&(this.setInterval(uu),this.state=te.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(x.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:a,groupId:o,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||r.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==te.STOPPED&&(this.state=te.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=n[a];let u=0;if(r.live||(i=h.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Uh(r,c),r.alignedSliding||Ar(r,c),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(x.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===te.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=te.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new hu(this.hls,ge.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],p=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const m=n?n.index:-1,g=m!==-1,E=new Er(i.level,i.sn,i.stats.chunkCount,r.byteLength,m,g);d.push(r,p,u,"",i,n,h.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:v}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new kh,complete:!1};v.push(new Uint8Array(r)),this.state!==te.STOPPED&&(this.state=te.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ge.MAIN&&Et(t.frag)&&(this.mainFragLoading=t,this.state===te.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==ge.AUDIO){!this.audioOnly&&i.type===ge.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Et(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(x.AUDIO_TRACK_SWITCHED,et({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case H.FRAG_GAP:case H.FRAG_PARSING_ERROR:case H.FRAG_DECRYPT_ERROR:case H.FRAG_LOAD_ERROR:case H.FRAG_LOAD_TIMEOUT:case H.KEY_LOAD_ERROR:case H.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.AUDIO,t);break;case H.AUDIO_TRACK_LOAD_ERROR:case H.AUDIO_TRACK_LOAD_TIMEOUT:case H.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Ye.AUDIO_TRACK&&(this.state=te.IDLE);break;case H.BUFFER_ADD_CODEC_ERROR:case H.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case H.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case H.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ot.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ot.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===te.ENDED&&(this.state=te.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,ge.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:p,initSegment:v}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=te.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),v!=null&&v.tracks){const m=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(h,v.tracks,m,a),n.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:v.tracks})}if(d){const{startPTS:m,endPTS:g,startDTS:E,endDTS:_}=d;c&&(c.elementaryStreams[ot.AUDIO]={startPTS:m,endPTS:g,startDTS:E,endDTS:_}),l.setElementaryStreamInfo(ot.AUDIO,m,g,E,_),this.bufferFragmentData(d,l,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){const m=at({id:i,frag:l,details:u},p);n.trigger(x.FRAG_PARSING_METADATA,m)}if(f){const m=at({id:i,frag:l,details:u},f);n.trigger(x.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i,n){if(this.state!==te.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=ge.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(x.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:o};this.hls.trigger(x.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===bt.NOT_LOADED||n===bt.PARTIAL){var r;if(!Et(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=te.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ar(t.details,a)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;dn({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:o},e,fn)||(mr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(x.AUDIO_TRACK_SWITCHED,et({},e))}}class Pr extends li{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let r=-1;for(let a=0;a<n.length;a++){const o=n[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=n[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=i&&Bc(i);return new Ba(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;n.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const h=Math.max(l||0,0);n.appliedTimelineOffset=h,n.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(n.live||i!=null&&i.live){const h="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){Iv(i,n,this);const E=n.playlistParsingError;if(E){this.warn(E);const _=this.hls;if(!_.config.ignorePlaylistParsingErrors){var c;const{networkDetails:T}=t;_.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:H.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:E,reason:E.message,level:t.level||void 0,parent:(c=n.fragments[0])==null?void 0:c.type,networkDetails:T,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(n.edge-d)*1e3,p=Lh(n,f);if(n.requestScheduled+p<a?n.requestScheduled=a:n.requestScheduled+=p,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let v,m,g;if(n.canBlockReload&&n.endSN&&n.advanced){const E=this.hls.config.lowLatencyMode,_=n.lastPartSn,T=n.endSN,b=n.lastPartIndex,R=b!==-1,A=_===T;R?A?(m=T+1,g=E?0:b):(m=_,g=E?b+1:n.maxPartIndex):m=T+1;const C=n.age,S=C+n.ageHeader;let y=Math.min(S-n.partTarget,n.targetduration*1.5);if(y>0){if(S>n.targetduration*3)this.log(`Playlist last advanced ${C.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,g=void 0;else if(i!=null&&i.tuneInGoal&&S-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${y} with playlist age: ${n.age}`),y=0;else{const w=Math.floor(y/n.targetduration);if(m+=w,g!==void 0){const U=Math.round(y%n.targetduration/n.partTarget);g+=U}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${C.toFixed(2)}s goal: ${y} skip sn ${w} to part ${g}`)}n.tuneInGoal=y}if(v=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g),E||!A){n.requestScheduled=a,this.loadingPlaylist(h,v);return}}else(n.canBlockReload||n.canSkipUntil)&&(v=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g));v&&m!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(p-o*2,p/2)),this.scheduleLoading(h,v,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=n.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const o=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,n){let r=Bc(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=ms.No),new Ba(i,n,r)}checkRetry(e){const t=e.details,i=gr(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=n||{},l=!!n&&!!o&&(r===It.RetryRequest||!n.resolved&&r===It.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=Ga(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function fu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Ts(s[t].attrs,e[t].attrs))return!1;return!0}function Ts(s,e,t){const i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>s[n]!==e[n])}function mo(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class pu extends Pr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(x.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Ai(l,o,fn);if(d>-1)r=o[d];else{const f=Ai(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(x.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===Ye.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&dn(e,n,fn))return n;const r=Ai(e,this.tracksInGroup,fn);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=J0(e,t.levels,i,a,fn);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Ai(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(x.AUDIO_TRACK_SWITCHING,et({},n)),r))return;const a=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||dn(e,n,fn)))return i}if(e){const{name:i,lang:n,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(dn({name:i,lang:n,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,fn))return c}for(let c=0;c<t.length;c++){const h=t[c];if(Ts(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(Ts(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&mr(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(x.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class N_{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
3707
|
+
initSegmentChange: ${S}`);const w=new O_(i,n,t,o,h);this.configureTransmuxer(w)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:y},e instanceof ArrayBuffer?[e]:[]);else if(p){const w=p.push(e,m,c,y);ys(w)?w.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);ys(n)?n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const uu=100;class du extends br{constructor(e,t,i){super(e,t,i,"audio-stream-controller",ge.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(x.BUFFER_RESET,this.onBufferReset,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(x.BUFFER_RESET,this.onBufferReset,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){if(i===ge.MAIN){const o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:r,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===te.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==o)&&this.syncWithAnchor(t,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===te.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(n==null?void 0:n.cc)===t.cc)return;const r=(n||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Xc(a,r,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===te.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=te.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(uu),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=te.IDLE):this.state=te.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case te.IDLE:this.doTickIdle();break;case te.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e==null?void 0:e[t],n=i==null?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=te.WAITING_INIT_PTS}break}case te.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case te.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=te.FRAG_LOADING;const o=n.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=te.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=te.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,ot.AUDIO,ge.AUDIO));const h=this.getFwdBufferInfo(c,ge.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(x.BUFFER_EOS,{type:"audio"}),this.state=te.ENDED;return}const u=h.len,d=t.maxBufferLength,f=l.fragments,p=f[0].start,v=this.getLoadPosition(),m=this.flushing?v:h.end;if(this.switchingTrack&&n){const _=v;l.PTSKnown&&_<p&&(h.end>p||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}if(u>=d&&!this.switchingTrack&&m<f[f.length-1].start)return;let g=this.getNextFragment(m,l);if(g&&this.isLoopLoading(g,m)&&(g=this.getNextFragmentLoopLoading(g,l,h,ge.MAIN,d)),!g){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,d,g))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&Et(g)&&!g.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===bt.OK&&(this.mainFragLoading=E=null),E&&Et(E))){if(g.start>E.end){const T=this.fragmentTracker.getFragAtPos(m,ge.MAIN);T&&T.end>E.end&&(E=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(g.start>E.end)return}this.loadFragment(g,o,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new zn(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==te.STOPPED&&(this.setInterval(uu),this.state=te.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(x.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:a,groupId:o,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||r.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==te.STOPPED&&(this.state=te.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=n[a];let u=0;if(r.live||(i=h.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Uh(r,c),r.alignedSliding||Ar(r,c),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(x.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===te.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=te.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new hu(this.hls,ge.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],p=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const m=n?n.index:-1,g=m!==-1,E=new Er(i.level,i.sn,i.stats.chunkCount,r.byteLength,m,g);d.push(r,p,u,"",i,n,h.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:v}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new kh,complete:!1};v.push(new Uint8Array(r)),this.state!==te.STOPPED&&(this.state=te.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ge.MAIN&&Et(t.frag)&&(this.mainFragLoading=t,this.state===te.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==ge.AUDIO){!this.audioOnly&&i.type===ge.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Et(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(x.AUDIO_TRACK_SWITCHED,et({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.AUDIO,t);break;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Ye.AUDIO_TRACK&&(this.state=te.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ot.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ot.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===te.ENDED&&(this.state=te.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,ge.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:p,initSegment:v}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=te.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),v!=null&&v.tracks){const m=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(h,v.tracks,m,a),n.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:v.tracks})}if(d){const{startPTS:m,endPTS:g,startDTS:E,endDTS:_}=d;c&&(c.elementaryStreams[ot.AUDIO]={startPTS:m,endPTS:g,startDTS:E,endDTS:_}),l.setElementaryStreamInfo(ot.AUDIO,m,g,E,_),this.bufferFragmentData(d,l,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){const m=at({id:i,frag:l,details:u},p);n.trigger(x.FRAG_PARSING_METADATA,m)}if(f){const m=at({id:i,frag:l,details:u},f);n.trigger(x.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i,n){if(this.state!==te.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=ge.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(x.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:o};this.hls.trigger(x.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===bt.NOT_LOADED||n===bt.PARTIAL){var r;if(!Et(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=te.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ar(t.details,a)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;dn({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:o},e,fn)||(mr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(x.AUDIO_TRACK_SWITCHED,et({},e))}}class Pr extends li{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t==null?void 0:t.renditionReports;if(n){let r=-1;for(let a=0;a<n.length;a++){const o=n[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=n[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=i&&Bc(i);return new Ba(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;n.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const h=Math.max(l||0,0);n.appliedTimelineOffset=h,n.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(n.live||i!=null&&i.live){const h="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){Iv(i,n,this);const E=n.playlistParsingError;if(E){this.warn(E);const _=this.hls;if(!_.config.ignorePlaylistParsingErrors){var c;const{networkDetails:T}=t;_.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:E,reason:E.message,level:t.level||void 0,parent:(c=n.fragments[0])==null?void 0:c.type,networkDetails:T,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(n.edge-d)*1e3,p=Lh(n,f);if(n.requestScheduled+p<a?n.requestScheduled=a:n.requestScheduled+=p,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let v,m,g;if(n.canBlockReload&&n.endSN&&n.advanced){const E=this.hls.config.lowLatencyMode,_=n.lastPartSn,T=n.endSN,b=n.lastPartIndex,R=b!==-1,A=_===T;R?A?(m=T+1,g=E?0:b):(m=_,g=E?b+1:n.maxPartIndex):m=T+1;const C=n.age,S=C+n.ageHeader;let y=Math.min(S-n.partTarget,n.targetduration*1.5);if(y>0){if(S>n.targetduration*3)this.log(`Playlist last advanced ${C.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,g=void 0;else if(i!=null&&i.tuneInGoal&&S-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${y} with playlist age: ${n.age}`),y=0;else{const w=Math.floor(y/n.targetduration);if(m+=w,g!==void 0){const N=Math.round(y%n.targetduration/n.partTarget);g+=N}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${C.toFixed(2)}s goal: ${y} skip sn ${w} to part ${g}`)}n.tuneInGoal=y}if(v=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g),E||!A){n.requestScheduled=a,this.loadingPlaylist(h,v);return}}else(n.canBlockReload||n.canSkipUntil)&&(v=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g));v&&m!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(p-o*2,p/2)),this.scheduleLoading(h,v,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=n.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const o=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,n){let r=Bc(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=ms.No),new Ba(i,n,r)}checkRetry(e){const t=e.details,i=gr(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=n||{},l=!!n&&!!o&&(r===It.RetryRequest||!n.resolved&&r===It.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=Ga(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}function fu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Ts(s[t].attrs,e[t].attrs))return!1;return!0}function Ts(s,e,t){const i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>s[n]!==e[n])}function mo(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class pu extends Pr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(x.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Ai(l,o,fn);if(d>-1)r=o[d];else{const f=Ai(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(x.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===Ye.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&dn(e,n,fn))return n;const r=Ai(e,this.tracksInGroup,fn);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=J0(e,t.levels,i,a,fn);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Ai(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(x.AUDIO_TRACK_SWITCHING,et({},n)),r))return;const a=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(!(this.selectDefaultTrack&&!n.default)&&(!e||dn(e,n,fn)))return i}if(e){const{name:i,lang:n,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(dn({name:i,lang:n,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,fn))return c}for(let c=0;c<t.length;c++){const h=t[c];if(Ts(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(Ts(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&mr(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(x.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}}class N_{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
3708
3708
|
${this.list("video")}
|
|
3709
3709
|
${this.list("audio")}
|
|
3710
3710
|
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i==null?void 0:i.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const mu=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,gu="HlsJsTrackRemovedError";class k_ extends Error{constructor(e){super(e),this.name=gu}}class vu extends li{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:r}=this;i&&this.log("Media source opened"),!(!n||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(x.MEDIA_ATTACHED,{media:n,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=f0(Ni(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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.BUFFER_RESET,this.onBufferReset,this),e.on(x.BUFFER_APPENDING,this.onBufferAppending,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.BUFFER_EOS,this.onBufferEos,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.FRAG_PARSED,this.onFragParsed,this),e.on(x.FRAG_CHANGED,this.onFragChanged,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.BUFFER_RESET,this.onBufferReset,this),e.off(x.BUFFER_APPENDING,this.onBufferAppending,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.BUFFER_EOS,this.onBufferEos,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.FRAG_PARSED,this.onFragParsed,this),e.off(x.FRAG_CHANGED,this.onFragChanged,this),e.off(x.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?at(i,n.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=at({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const n=Ni(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,_u(i),B_(i,o),i.load()}catch{i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,r=n?Object.keys(n):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
3711
3711
|
required tracks: ${lt(i,(l,c)=>l==="initSegment"?void 0:c)};
|
|
3712
|
-
transfer tracks: ${lt(n,(l,c)=>l==="initSegment"?void 0:c)}}`),!gc(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,h=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(x.MEDIA_DETACHING,{}),this.onMediaAttaching(x.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{const c=l,h=n[c];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const m=Fe.getBuffered(u);d.detectEvictedFragments(c,m,f,null,!0)}const p=go(c),v=[c,u];this.sourceBuffers[p]=v,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),r.removeSourceBuffer(l[c]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&_u(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(x.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[go(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new N_(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!n[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var c,h;const u=t[l],{id:d,codec:f,levelCodec:p,container:v,metadata:m,supplemental:g}=u;let E=n[l];const _=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],T=_!=null&&_.buffer?_:E,b=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),R=T==null?void 0:T.levelCodec;E||(E=n[l]={buffer:void 0,listeners:[],codec:f,supplemental:g,container:v,levelCodec:p,metadata:m,id:d});const A=fr(b,R),C=A==null?void 0:A.replace(mu,"$1");let S=fr(f,p);const y=(h=S)==null?void 0:h.replace(mu,"$1");S&&A&&C!==y&&(l.slice(0,5)==="audio"&&(S=dr(S,this.appendSource)),this.log(`switching codec ${b} to ${S}`),S!==(E.pendingCodec||E.codec)&&(E.pendingCodec=S),E.container=v,this.appendChangeType(l,v,S))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),o.changeType(n),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,ge.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Fe.isBuffered(l.buffer,n)||((o=this.fragmentTracker.getAppendedFrag(n,ge.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:a,frag:o,part:l,chunkMeta:c,offset:h}=t,u=c.buffering[r],{sn:d,cc:f}=o,p=self.performance.now();u.start=p;const v=o.stats.buffering,m=l?l.stats.buffering:null;v.start===0&&(v.start=p),m&&m.start===0&&(m.start=p);const g=i.audio;let E=!1;r==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const _=i.video,T=_==null?void 0:_.buffer;if(T&&d!=="initSegment"){const A=l||o,C=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(_.ending||_.ended)){const y=A.start+A.duration*.05,w=T.buffered,U=this.currentOp("video");!w.length&&!U?this.blockAudio(A):!U&&!Fe.isBuffered(T,y)&&this.lastVideoAppendEnd<y&&this.blockAudio(A)}else if(r==="video"){const S=A.end;if(C){const y=C.frag.start;(S>y||S<this.lastVideoAppendEnd||Fe.isBuffered(T,y))&&this.unblockAudio()}this.lastVideoAppendEnd=S}}const b=(l||o).start,R={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const C=(A=this.tracks[r])==null?void 0:A.buffer;C&&(E?this.updateTimestampOffset(C,b,.1,r,d,f):h!==void 0&&de(h)&&this.updateTimestampOffset(C,h,1e-6,r,d,f)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,v.first===0&&(v.first=A),m&&m.first===0&&(m.first=A);const C={};this.sourceBuffers.forEach(([S,y])=>{S&&(C[S]=Fe.getBuffered(y))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(x.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:C})},onError:A=>{var C;const S={type:Ee.MEDIA_ERROR,parent:o.type,details:H.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:c,error:A,err:A,fatal:!1},y=(C=this.media)==null?void 0:C.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)S.details=H.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!y)S.errorAction=Wn(!0);else if(A.name===gu&&this.sourceBufferCount===0)S.errorAction=Wn(!0);else{const w=++this.appendErrors[r];this.warn(`Failed ${w}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${y||"no media error"})`),(w>=this.hls.config.appendErrorMaxRetry||y)&&(S.fatal=!0)}this.hls.trigger(x.ERROR,S)}};this.log(`queuing "${r}" append sn: ${d}${l?" p: "+l.index:""} of ${o.type===ge.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(R,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(x.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,n,r),a)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[ot.AUDIOVIDEO]?r.push("audiovideo"):(a[ot.AUDIO]&&r.push("audio"),a[ot.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const c=n?n.stats:i.stats;this.hls.trigger(x.FRAG_BUFFERED,{frag:i,part:n,stats:c,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(x.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(x.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}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(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===H.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,a=t.levelTargetDuration,o=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(o)&&o>=0){const c=Math.max(o,a),h=Math.floor(r/a)*a-c;this.flushBackBuffer(r,a,h)}const l=n.frontBufferFlushThreshold;if(de(l)&&l>0){const c=Math.max(n.maxBufferLength,l),h=Math.max(c,a),u=Math.floor(r/a)*a+h;this.flushFrontBuffer(r,a,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=Fe.getBuffered(r);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(x.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger(x.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const a=Fe.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(i>l||e>=l&&e<=c)return;this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),h=Math.max(c,n);return{duration:1/0,start:c,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return de(r)?{duration:r}:null;const a=this.media.duration,o=de(i.duration)?i.duration:0;return n>o&&n>a||!de(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${lt(i)}`),this.tracksReady){var n;const r=(n=this.transferData)==null?void 0:n.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(x.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(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${lt(o)}`);try{const h=i.addSourceBuffer(c),u=go(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var n;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&fs(i,"video")&&(n=F0(n,i));const r=fr(n,e.levelCodec);return r?t.slice(0,5)==="audio"?dr(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(x.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,a){const o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!n||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,c=de(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(i,l,c);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new k_(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const a=i.bind(this,e);n.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function _u(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function B_(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function go(s){return s==="audio"?1:0}class Fr{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(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,Fr.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&n(l,e[o+1])){r=o;break}}return r}}const Qt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},G_={HLS:"h"};class Ri{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Ri?i:new Ri(i))),this.value=e,this.params=t}}const V_="Dict";function H_(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function $_(s,e,t,i){return new Error(`failed to ${s} "${H_(e)}" as ${t}`,{cause:i})}function Mi(s,e,t){return $_("serialize",s,e,t)}class Eu{constructor(e){this.description=e}}const xu="Bare Item",z_="Boolean";function W_(s){if(typeof s!="boolean")throw Mi(s,z_);return s?"?1":"?0"}function K_(s){return btoa(String.fromCharCode(...s))}const X_="Byte Sequence";function Y_(s){if(ArrayBuffer.isView(s)===!1)throw Mi(s,X_);return`:${K_(s)}:`}const q_="Integer";function j_(s){return s<-999999999999999||999999999999999<s}function Su(s){if(j_(s))throw Mi(s,q_);return s.toString()}function Q_(s){return`@${Su(s.getTime()/1e3)}`}function yu(s,e){if(s<0)return-yu(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const n=Math.floor(s*t);return(n%2===0?n:n+1)/t}else return Math.round(s*t)/t}const Z_="Decimal";function J_(s){const e=yu(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Mi(s,Z_);const t=e.toString();return t.includes(".")?t:`${t}.0`}const eE="String",tE=/[\x00-\x1f\x7f]+/;function iE(s){if(tE.test(s))throw Mi(s,eE);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function nE(s){return s.description||s.toString().slice(7,-1)}const sE="Token";function Tu(s){const e=nE(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Mi(e,sE);return e}function vo(s){switch(typeof s){case"number":if(!de(s))throw Mi(s,xu);return Number.isInteger(s)?Su(s):J_(s);case"string":return iE(s);case"symbol":return Tu(s);case"boolean":return W_(s);case"object":if(s instanceof Date)return Q_(s);if(s instanceof Uint8Array)return Y_(s);if(s instanceof Eu)return Tu(s);default:throw Mi(s,xu)}}const rE="Key";function _o(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Mi(s,rE);return s}function Eo(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${_o(e)}`:`;${_o(e)}=${vo(t)}`).join("")}function Au(s){return s instanceof Ri?`${vo(s.value)}${Eo(s.params)}`:vo(s)}function aE(s){return`(${s.value.map(Au).join(" ")})${Eo(s.params)}`}function oE(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Mi(s,V_);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Ri||(r=new Ri(r));let a=_o(n);return r.value===!0?a+=Eo(r.params):(a+="=",Array.isArray(r.value)?a+=aE(r):a+=Au(r)),a}).join(`,${i}`)}function bu(s,e){return oE(s,e)}const Li="CMCD-Object",gt="CMCD-Request",mn="CMCD-Session",tn="CMCD-Status",lE={br:Li,ab:Li,d:Li,ot:Li,tb:Li,tpb:Li,lb:Li,tab:Li,lab:Li,url:Li,pb:gt,bl:gt,tbl:gt,dl:gt,ltc:gt,mtp:gt,nor:gt,nrr:gt,rc:gt,sn:gt,sta:gt,su:gt,ttfb:gt,ttfbb:gt,ttlb:gt,cmsdd:gt,cmsds:gt,smrt:gt,df:gt,cs:gt,ts:gt,cid:mn,pr:mn,sf:mn,sid:mn,st:mn,v:mn,msd:mn,bs:tn,bsd:tn,cdn:tn,rtp:tn,bg:tn,pt:tn,ec:tn,e:tn},cE={REQUEST:gt};function hE(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(n=>e[n]=t),e},{})}function uE(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?hE(e):{};return i.reduce((r,a)=>{var o;const l=lE[a]||n[a]||cE.REQUEST,c=(o=r[l])!==null&&o!==void 0?o:r[l]={};return c[a]=s[a],r},t)}function dE(s){return["ot","sf","st","e","sta"].includes(s)}function fE(s){return typeof s=="number"?de(s):s!=null&&s!==""&&s!==!1}const Ru="event";function pE(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const n=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const Or=s=>Math.round(s),xo=(s,e)=>Array.isArray(s)?s.map(t=>xo(t,e)):s instanceof Ri&&typeof s.value=="string"?new Ri(xo(s.value,e),s.params):(e.baseUrl&&(s=pE(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Ur=s=>Or(s/100)*100,mE={br:Or,d:Or,bl:Ur,dl:Ur,mtp:Ur,nor:(s,e)=>{let t=s;return e.version>=2&&(s instanceof Ri&&typeof s.value=="string"?t=new Ri([s]):typeof s=="string"&&(t=[s])),xo(t,e)},rtp:Ur,tb:Or},Mu="request",Lu="response",So=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],gE=["e"],vE=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Nr(s){return vE.test(s)}function _E(s){return So.includes(s)||gE.includes(s)||Nr(s)}const Iu=["d","dl","nor","ot","rtp","su"];function EE(s){return So.includes(s)||Iu.includes(s)||Nr(s)}const xE=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function SE(s){return So.includes(s)||Iu.includes(s)||xE.includes(s)||Nr(s)}const yE=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function TE(s){return yE.includes(s)||Nr(s)}const AE={[Lu]:SE,[Ru]:_E,[Mu]:EE};function Cu(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||Mu,r=i===1?TE:AE[n];let a=Object.keys(s).filter(r);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=n===Lu||n===Ru;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const c=at({},mE,e.formatters),h={version:i,reportingMode:n,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let d=s[u];const f=c[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(i===1)return;d=i}u=="pr"&&d===1||(l&&u==="ts"&&!de(d)&&(d=Date.now()),fE(d)&&(dE(u)&&typeof d=="string"&&(d=new Eu(d)),t[u]=d))}),t}function bE(s,e={}){const t={};if(!s)return t;const i=Cu(s,e),n=uE(i,e==null?void 0:e.customHeaderMap);return Object.entries(n).reduce((r,[a,o])=>{const l=bu(o,{whitespace:!1});return l&&(r[a]=l),r},t)}function RE(s,e,t){return at(s,bE(e,t))}const ME="CMCD";function LE(s,e={}){return s?bu(Cu(s,e),{whitespace:!1}):""}function IE(s,e={}){if(!s)return"";const t=LE(s,e);return encodeURIComponent(t)}function CE(s,e={}){if(!s)return"";const t=IE(s,e);return`${ME}=${t}`}const wu=/CMCD=[^&#]+/;function wE(s,e,t){const i=CE(e,t);if(!i)return s;if(wu.test(s))return s.replace(wu,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class Du{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:Qt.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:a}=n,o=this.hls.levels[r.level],l=this.getObjectType(r),c={d:(a||r).duration*1e3,ot:l};(l===Qt.VIDEO||l===Qt.AUDIO||l==Qt.MUXED)&&(c.br=o.bitrate/1e3,c.tb=this.getTopBandwidth(l)/1e3,c.bl=this.getBufferLength(l));const h=a?this.getNextPart(a):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(c.nor=h.url),this.apply(n,c)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHED,this.onMediaDetached,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHED,this.onMediaDetached,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:G_.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){at(t,this.createData());const i=t.ot===Qt.INIT||t.ot===Qt.VIDEO||t.ot===Qt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((a,o)=>(n.includes(o)&&(a[o]=t[o]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),RE(e.headers,t,r)):e.url=wE(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=n;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===i&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Qt.TIMED_TEXT;if(e.sn==="initSegment")return Qt.INIT;if(t==="audio")return Qt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Qt.VIDEO:Qt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Qt.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Qt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Fe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const DE=3e5;class Pu extends li{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===It.SendAlternateToPenaltyBox&&i.flags===Yt.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&n?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),t.details===H.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${n&&n.length} priorities: ${lt(r)} penalized: ${lt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>DE&&delete i[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Dh(t),this.hls.trigger(x.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<n.length;r++)if(t===Ye.AUDIO_TRACK&&n[r].hasAudioGroup(e)||t===Ye.SUBTITLE_TRACK&&n[r].hasSubtitleGroup(e))return n[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new ft(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(i[u.AUDIO]=d,u.AUDIO=d),f&&(n[u.SUBTITLES]=f,u.SUBTITLES=f);const p=Ou(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),v=new zn({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:p,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let m=1;m<h.audioGroups.length;m++)v.addGroupId("audio",`${h.audioGroups[m]}_clone_${a}`);if(h.subtitleGroups)for(let m=1;m<h.subtitleGroups.length;m++)v.addGroupId("text",`${h.subtitleGroups[m]}_clone_${a}`);return v});t.push(...c),Fu(this.audioTracks,i,l,a),Fu(this.subtitleTracks,n,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:n.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${n}"`);const p=h.data;if((p==null?void 0:p.VERSION)!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":v,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":g}=p;if(v)try{this.uri=new self.URL(v,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${v}`);return}this.scheduleRefresh(this.uri||d.url),m&&this.clonePathways(m);const E={steeringManifest:p,url:n.toString()};this.hls.trigger(x.STEERING_MANIFEST_LOADED,E),g&&this.updatePathwayPriority(g)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let p=this.timeToLoad*1e3;if(h.code===429){const v=this.loader;if(typeof(v==null?void 0:v.getResponseHeader)=="function"){const m=v.getResponseHeader("Retry-After");m&&(p=parseFloat(m)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,p)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Fu(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const o=at({},a);return o.details=void 0,o.attrs=new ft(o.attrs),o.url=o.attrs.URI=Ou(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[n],o.attrs["PATHWAY-ID"]=i,o});s.push(...r)})}function Ou(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return n&&!o&&(l.host=n),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}class gn extends li{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=gn.CDMCleanupPromise?[gn.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=gs(this.config));const o=a.map(Ya).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Tr(a);if(i!=="sinf"||o!==pt.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{const f=At(new Uint8Array(n)),p=Ka(JSON.parse(f).sinf),v=Lc(p);if(!v)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(v.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const c=Ut(l),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[c];for(let f=0;f<u.length;f++){const p=u[f],v=p.decryptdata;if(!v.keyId)continue;const m=Ut(v.keyId);if(Sr(l,v.keyId)||v.uri.replace(/-/g,"").indexOf(c)!==-1){if(d=h[m],!d)continue;if(v.pssh)break;delete h[m],v.pssh=new Uint8Array(n),v.keyId=l,d=h[c]=d.then(()=>this.generateRequestWithPreferredKeySession(p,i,n,"encrypted-event-key-match")),d.catch(g=>this.handleError(g));break}}d||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(x.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(x.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t==null?void 0:t[e];if(n)return n.licenseUrl;if(e===pt.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t==null?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,n,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof ni?o(u):o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return qa===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){var n;const r=xv(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(n=a)==null?void 0:n.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${lt(r)}`),o=this.requestMediaKeySystemAccess(e,r);const l=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 h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ut(e.keyId||[])} keyUri: ${e.uri}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=kr(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ut(e.decryptdata.keyId||[])}
|
|
3713
|
-
} (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ya(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const r=Ya(n);r?t(r):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}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){const t=gs(this.config),i=e.map(Tr).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const n=PE(e,t[i]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,i=kr(t),n=this.bannedKeyIds[i];if(n||this.getKeyStatus(t)==="internal-error"){const o=Uu(n||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const a=this.keyIdToKeySessionPromise[i];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(l,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:c,decryptdata:t}))))).then(l=>{const c="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,c,h,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof ni){const l=et({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);const c=new ni(l,o.message);this.handleError(c,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof ni){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ut(i.keyId||[])})`:""}`),this.hls.trigger(x.ERROR,e.data)}else this.error(e.message),this.hls.trigger(x.ERROR,{type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=kr(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Tr(e.keyFormat),r=n?[n]:gs(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=gs(this.config)),e.length===0)throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${lt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r;const a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const p=a.call(this.hls,t,i,e);if(!p)throw new Error("Invalid response from configured generateRequest filter");t=p.initDataType,i=p.initData?p.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(p){if(this.warn(p.message),this.hls&&this.hls.config.debug)throw p}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const o=kr(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);const c=new to,h=e._onmessage=p=>{const v=e.mediaKeysSession;if(!v){c.emit("error",new Error("invalid state"));return}const{messageType:m,message:g}=p;this.log(`"${m}" message event for session "${v.sessionId}" message size: ${g.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,g).catch(E=>{c.eventNames().length?c.emit("error",E):this.handleError(E)}):m==="license-release"?e.keySystem===pt.FAIRPLAY&&this.updateKeySession(e,Xa("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${m}"`)},u=(p,v)=>{v.keyStatus=p;let m;p.startsWith("usable")?c.emit("resolved"):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?m=Uu(p,v.decryptdata):p==="expired"?m=new Error(`key expired (keyId: ${o})`):p==="released"?m=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${o})`),m&&(c.eventNames().length?c.emit("error",m):this.handleError(m))},d=e._onkeystatuseschange=p=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const m=this.getKeyStatuses(e);if(!Object.keys(m).some(T=>m[T]!=="status-pending"))return;if(m[o]==="expired"){this.log(`Expired key ${lt(m)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=m[o];if(E)u(E,e);else{var _;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(_=e.keyStatusTimeouts)[o]||(_[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const b=this.getKeyStatus(e.decryptdata);if(b&&b!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${b} from other session.`),u(b,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",u(E,e)},1e3)),this.log(`No status for keyId ${o} (${lt(m)}).`)}};Ht(e.mediaKeysSession,"message",h),Ht(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((p,v)=>{c.on("error",v),c.on("resolved",p)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(p=>{throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>f).catch(p=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw p}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,n)=>{if(typeof n=="string"&&typeof i=="object"){const o=n;n=i,i=o}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===pt.PLAYREADY&&r.length===16){const o=Ut(r);t[o]=i,uh(r)}const a=Ut(r);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{a(d.data)},onError:(d,f,p,v)=>{o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:et({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,p)=>{o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,p)=>{o(new Error("aborted"))}};n.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,p=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&p&&e.setRequestHeader(f,p)}}const l=n.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Xa(atob(c))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(h){this.error(h)}n(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new ni({type:Ee.KEY_SYSTEM_ERROR,details:H.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==pt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Ht(i,"encrypted",this.onMediaEncrypted),Ht(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(qt(e,"encrypted",this.onMediaEncrypted),qt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Bi.clearKeyUriToKeyIdMap();const r=n.length;gn.CDMCleanupPromise=Promise.all(n.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ut((n==null?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(c=>self.clearTimeout(a[c]));const{drmSystemOptions:o}=this.config;return(yv(o)?new Promise((c,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(c).catch(h)}):Promise.resolve()).catch(c=>{this.log(`Could not remove session: ${c}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${c}`)})}).then(()=>t.close()).catch(c=>{this.log(`Could not close session: ${c}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}gn.CDMCleanupPromise=void 0;function kr(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Ut(s.keyId)}function PE(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class ni extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Uu(s,e){const t=s==="output-restricted",i=t?H.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:H.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ni({type:Ee.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class Nu{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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(x.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(x.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function ku(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function Bu(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){tt.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){tt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Zn(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function yo(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=OE(s.cues,e,t);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&s.removeCue(r[a])}n==="disabled"&&(s.mode=n)}function FE(s,e){if(e<=s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),e<s[r].startTime)n=r-1;else if(e>s[r].startTime&&i<t)i=r+1;else return r;return s[i].startTime-e<e-s[n].startTime?i:n}function OE(s,e,t){const i=[],n=FE(s,e);if(n>-1)for(let r=n,a=s.length;r<a;r++){const o=s[r];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Br(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}class Gu extends Pr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Br(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];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(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(x.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Br(i.textTracks).forEach(a=>{Zn(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Ai(o,a);if(h>-1)r=a[h];else{const u=Ai(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(x.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const r=t[n];if(!(i&&!r.default||!i&&!e)&&(!e||dn(r,e)))return n}if(e){for(let n=0;n<t.length;n++){const r=t[n];if(Ts(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const r=t[n];if(Ts(e.attrs,r.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(mo(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Ye.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&dn(e,i))return i;const n=Ai(e,this.tracksInGroup);if(n>-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=Ai(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(x.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Br(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>mo(i,r))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==n&&(r.mode="disabled")}),n){const r=this.subtitleDisplay?"showing":"hidden";n.mode!==r&&(n.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!de(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:h}=n;this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:h});const u=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(u)}}function UE(){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 r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?r:r&3|8).toString(16)})}}}function As(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Jn=.025;let Gr=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function NE(s,e,t){return`${s.identifier}-${t+1}-${As(e)}`}class kE{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return To(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=To(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=de(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return To(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)<Jn))}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"?Gr.Range:Gr.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 BE(this)}}function To(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<Jn)?e.start:e.start+e.duration}function Vu(s,e,t){const i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function Ao(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function BE(s){return`["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function es(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class GE{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(x.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const a=()=>{this.hasDetails=!0};r.once(x.LEVEL_LOADED,a),r.once(x.AUDIO_TRACK_LOADED,a),r.once(x.SUBTITLE_TRACK_LOADED,a),r.on(x.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(x.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(x.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Vu(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=Fe.bufferInfo(e,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Fe.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;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>11111111111111112e-21&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,i){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,i){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${es(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Hu=.033;class VE extends li{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;n<i.length;n++){let r=i[n];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return n}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let n=e;n<=t&&i[n];n++){const r=i[n].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var i;if(((i=t[n].event)==null?void 0:i.identifier)===e)return n}return-1}findAssetIndex(e,t){const i=e.assetList,n=i.length;if(n>1)for(let r=0;r<n;r++){const a=i[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===n-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,n=i[i.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:n}=i,r=this.events,a=this.parseDateRanges(n,{url:i.url},t),o=Object.keys(n),l=r?r.filter(c=>!o.includes(c.identifier)):[];a.length&&a.sort((c,h)=>{const u=c.cue.pre,d=c.cue.post,f=h.cue.pre,p=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!p)return 1;if(p&&!d)return-1;if(!u&&!f&&!d&&!p){const v=c.startTime,m=h.startTime;if(v!==m)return v-m}return c.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=a,l.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,a=this.parseSchedule(n,e);(i||t.length||(r==null?void 0:r.length)!==a.length||a.some((l,c)=>Math.abs(l.playout.start-r[c].playout.start)>.005||Math.abs(l.playout.end-r[c].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new kE(l,t),this.eventMap[o]=c,i===!1&&(c.appendInPlace=i)),n.push(c)}}return n}parseSchedule(e,t){const i=[],n=t.main.details,r=n.live?1/0:n.edge;let a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,c=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,p=e[u-1]||null,v=h.appendInPlace,m=f?r:h.startOffset,g=h.duration,E=h.timelineOccupancy===Gr.Range?g:0,_=h.resumptionOffset,T=(p==null?void 0:p.startTime)===m,b=m+h.cumulativeDuration;let R=v?b+g:m+_;if(d||!f&&m<=0){const C=c;c+=E,h.timelineStart=b;const S=a;a+=g,i.push({event:h,start:b,end:R,playout:{start:S,end:a},integrated:{start:C,end:c}})}else if(m<=r){if(!T){const y=m-l;if(y>Hu){const w=l,U=c;c+=y;const X=a;a+=y;const P={previousEvent:e[u-1]||null,nextEvent:h,start:w,end:w+y,playout:{start:X,end:a},integrated:{start:U,end:c}};i.push(P)}else y>0&&p&&(p.cumulativeDuration+=y,i[i.length-1].end=m)}f&&(R=b),h.timelineStart=b;const C=c;c+=E;const S=a;a+=g,i.push({event:h,start:b,end:R,playout:{start:S,end:a},integrated:{start:C,end:c}})}else return;const A=h.resumeTime;f||A>r?l=r:l=A}),l<r){var o;const h=l,u=c,d=r-l;c+=d;const f=a;a+=d,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:h+d,playout:{start:f,end:a},integrated:{start:u,end:c}})}this.setDurations(r,a,c)}else i.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,n=i.live?1/0:i.edge;let r=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,h=o.cue.post,u=c?0:h?n:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=pn(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Hu&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=de(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>Jn?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;const c=pn(null,o.fragments,i);if(!c)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(c.start-i)<Jn+h||Math.abs(c.end-i)<Jn+h?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,n=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,n||(n=o.duration===null),r||(r=!!o.error);const c=o.error?0:o.duration||0;i+=c}n&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function vi(s){return`[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}class HE{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let n;try{n=Vu(i,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,H.ASSET_LIST_LOAD_ERROR,d,i);this.hls.trigger(x.ERROR,f);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),l={responseType:"json",url:n.href},c=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{const m=d.data,g=m==null?void 0:m.ASSETS;if(!Array.isArray(g)){const E=this.assignAssetListError(e,H.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),p.url,f,v);this.hls.trigger(x.ERROR,E);return}e.assetListResponse=m,this.hls.trigger(x.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:v})},onError:(d,f,p,v)=>{const m=this.assignAssetListError(e,H.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,v,p);this.hls.trigger(x.ERROR,m)},onTimeout:(d,f,p)=>{const v=this.assignAssetListError(e,H.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,p);this.hls.trigger(x.ERROR,v)}};return o.load(l,h,u),this.hls.trigger(x.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,n,r,a){return e.error=i,{type:Ee.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:a,stats:r}}}function $u(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function ts(s,e){return`[${s}] Advancing timeline position to ${e}`}class $E extends li{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const a=n<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;const f=this.findItemIndex(o);let p=this.schedule.findItemIndexAtTime(i);if(p===-1&&(p=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${p})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&p>f){const v=this.schedule.findJumpRestrictedIndex(f+1,p);if(v>f){this.setSchedulePosition(v);return}}this.setSchedulePosition(p);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}const h=c.timelineStart,u=c.duration||0;if(a&&i<h||i>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,c)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const o=this.findItemIndex(n);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],c=r.durations,h=i.map(v=>v.identifier),u=!!(o.length||h.length);(u||n)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
3714
|
-
Schedule: ${l.map(v=>vi(v))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),i.forEach(v=>{v.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(v=>{if(v.interstitial.appendInPlace){const m=v.assetItem.timelineStart,g=v.timelineOffset-m;if(g)try{v.timelineOffset=m}catch(E){Math.abs(g)>Jn&&this.warn(`${E} ("${v.assetId}" ${v.timelineOffset}->${m})`)}}}),u||n){if(this.hls.trigger(x.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(a)&&h.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),p&&f!==d&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new HE(e),this.schedule=new VE(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(x.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(x.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(x.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(x.MEDIA_ENDED,this.onMediaEnded,this),e.on(x.ERROR,this.onError,this),e.on(x.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(x.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(x.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(x.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(x.MEDIA_ENDED,this.onMediaEnded,this),e.off(x.ERROR,this.onError,this),e.off(x.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){qt(e,"play",this.onPlay),qt(e,"pause",this.onPause),qt(e,"seeking",this.onSeeking),qt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Ht(i,"seeking",this.onSeeking),Ht(i,"timeupdate",this.onTimeupdate),Ht(i,"play",this.onPlay),Ht(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),n=(u,d,f,p,v)=>{if(u){let m=u[d].start;const g=u.event;if(g){if(d==="playout"||g.timelineOccupancy!==Gr.Point){const E=i(f);(E==null?void 0:E.interstitial)===g&&(m+=E.assetItem.startOffset+E[v])}}else{const E=p==="bufferedPos"?a():e[p];m+=E-u.start}return m}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var p;const v=e.schedule.findItemIndexAtTime(u),m=(p=e.schedule.items)==null?void 0:p[v];if(m){const g=m[d].start-m.start;return u+g}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,d)=>{var f,p;const v=e.effectivePlayingItem;if(v!=null&&(f=v.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const m=e.effectivePlayingItem,g=e.schedule.findItemIndexAtTime(u,d),E=(p=e.schedule.items)==null?void 0:p[g],_=e.getBufferingPlayer(),T=_==null?void 0:_.interstitial,b=T==null?void 0:T.appendInPlace,R=m&&e.itemsMatch(m,E);if(m&&(b||R)){const A=i(e.playingAsset),C=(A==null?void 0:A.media)||e.primaryMedia;if(C){const S=d==="primary"?C.currentTime:n(m,d,e.playingAsset,"timelinePos","currentTime"),y=u-S,w=(b?S:C.currentTime)+y;if(w>=0&&(!A||b||w<=A.duration)){C.currentTime=w;return}}}if(E){let A=u;if(d!=="primary"){const S=E[d].start,y=u-S;A=E.start+y}const C=!e.isInterstitial(E);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(C||E.event.appendInPlace)){const S=e.media||(b?_==null?void 0:_.media:null);S&&(S.currentTime=A)}else if(m){const S=e.findItemIndex(m);if(g>S){const w=e.schedule.findJumpRestrictedIndex(S+1,g);if(w>S){e.setSchedulePosition(w);return}}let y=0;if(C)e.timelinePos=A,e.checkBuffer();else{const w=E.event.assetList,U=u-(E[d]||E).start;for(let X=w.length;X--;){const P=w[X];if(P.duration&&U>=P.startOffset&&U<P.startOffset+P.duration){y=X;break}}}e.setSchedulePosition(g,y)}}},c=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return n(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=c(),d=e.effectivePlayingItem;return d&&d===u?n(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=c(),f=e.effectivePlayingItem;f&&f===d&&l(u+f.playout.start,"playout")},get duration(){const u=c();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=c())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=c())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return c()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.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(u){l(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u==null?void 0:u.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const p=u.playout.start+u.event.duration;l(p+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(t=n)==null?void 0:t.currentTime;if(!(r===void 0||!de(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${lt(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(i=this.detachedData)==null?void 0:i.mediaSource;let h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else if(c){const p=this.getBufferingPlayer();p?(r=p.transferMedia(),h=`${p}`):h="detached MediaSource"}else h="detached media";if(!r){if(c)r=this.detachedData,this.log(`using detachedData: MediaSource ${lt(r)}`);else if(!this.detachedData||a.media===t){const p=this.playerQueue;p.length>1&&p.forEach(v=>{if(o&&v.interstitial.appendInPlace!==l){const m=v.interstitial;this.clearInterstitial(v.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(d===r&&f){const p=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||p,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(ts("checkStart (preroll)",r));const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){this.log(ts("checkStart",r));const a=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(ts("checkStart (playing item)",n.start));const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=Ao(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,i){const n=Ao(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,o=r.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(ts("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const r=e.assetList[n];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const n=t.parentIdentifier,r=i.getEvent(n);if(r){const a=i.findEventIndex(n),o=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var i;const n=(i=this.schedule)==null?void 0:i.items;if(!n||this.playbackDisabled)return;const r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&vi(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const h=a.event,u=this.playingAsset,d=u==null?void 0:u.identifier,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,r)||t!==void 0&&d!==h.assetList[t].identifier)){var l;const p=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${h.assetList.length} ${es(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(x.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:p,event:h,schedule:n.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(d,r),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${vi(a)}`),h.hasPlayed=!0,this.hls.trigger(x.INTERSTITIAL_ENDED,{event:h,schedule:n.slice(0),scheduleIndex:e}),h.cue.once)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(r&&p){const v=this.findItemIndex(r);this.advanceSchedule(v,p,t,a,o)}return}}this.advanceSchedule(e,n,t,a,o)}advanceSchedule(e,t,i,n,r){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(i===void 0){i=a.findAssetIndex(h,this.timelinePos);const p=Ao(h,i-1);if(h.isAssetPastPlayoutLimit(p)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,i);return}i=p}const u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(h,i);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${vi(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(x.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[i];if(!f){this.advanceAfterAssetEnded(h,e,i||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const p=h.assetList.length;this.warn(`asset ${i+1}/${p} player destroyed ${h}`),d=this.createAssetPlayer(h,f,i),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,i,t,e,l),this.shouldPlay&&$u(d.media)}else o?(this.resumePrimary(o,e,n),this.shouldPlay&&$u(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${vi(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(ts("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${vi(e)}`),this.hls.trigger(x.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(i<n.fragmentStart||i>n.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Fe.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(ts("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(x.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(x.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=et(et({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=et(et({},this.altSelection),{},{audio:i});return}const r=et(et({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=et(et({},this.altSelection),{},{subtitles:i});return}const r=et(et({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=Hc(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Hc(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const r=t[n];if(r.cue.post){var i;const a=this.schedule.findEventIndex(r.identifier),o=(i=this.schedule.items)==null?void 0:i[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const n=(i=this.schedule)==null?void 0:i.items;if(e&&n){const r=this.findItemIndex(e,t);return n[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=Fe.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${vi(e)} (was ${vi(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const n=Fe.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((l===-1&&r&&e>=r.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${vi(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(x.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,a=e.cue.once;if(r){const l=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-l;d>0&&(c=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${c?` live-start: ${h} start-offset: ${c}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const u=this.assetListLoader.loadAssetList(e,c);u&&(e.assetListLoader=u)}else if(!a&&n){for(let c=t;c<n;c++){const h=e.assetList[c],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}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(x.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,n,r,a){const o={parentIdentifier:e.identifier,identifier:NE(e,a,t),duration:r,startOffset:i,timelineStart:n,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){const n=this.hls,r=n.userConfig;let a=r.videoPreference;const o=n.loadLevelObj||n.levels[n.currentLevel];(a||o)&&(a=at({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=n.audioTracks[n.audioTrack],c=n.subtitleTracks[n.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const b=t.duration;b&&T<b&&(h=T)}}const u=t.identifier,d=et(et({},r),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||r.audioPreference,subtitlePreference:c||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=at({},f,{contentId:As(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const p=new GE(this.HlsPlayerClass,d,e,t);this.playerQueue.push(p),e.assetList[i]=t;let v=!0;const m=T=>{if(T.live){var b;const C=new Error(`Interstitials MUST be VOD assets ${e}`),S={fatal:!0,type:Ee.OTHER_ERROR,details:H.INTERSTITIAL_ASSET_ITEM_ERROR,error:C},y=((b=this.schedule)==null?void 0:b.findEventIndex(e.identifier))||-1;this.handleAssetItemError(S,e,y,i,C.message);return}const R=T.edge-T.fragmentStart,A=t.duration;(v||A===null||R>A)&&(v=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${R}`),t.duration=R,this.updateSchedule())};p.on(x.LEVEL_UPDATED,(T,{details:b})=>m(b)),p.on(x.LEVEL_PTS_UPDATED,(T,{details:b})=>m(b)),p.on(x.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const g=(T,b)=>{const R=this.getAssetPlayer(u);if(R&&b.tracks){R.off(x.BUFFER_CODECS,g),R.tracks=b.tracks;const A=this.primaryMedia;this.bufferingAsset===R.assetItem&&A&&!R.media&&this.bufferAssetPlayer(R,A)}};p.on(x.BUFFER_CODECS,g);const E=()=>{var T;const b=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${b}`),!b||!this.schedule)return;const R=this.schedule.findEventIndex(e.identifier),A=(T=this.schedule.items)==null?void 0:T[R];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};p.on(x.BUFFERED_TO_END,E);const _=T=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,T)};return p.once(x.MEDIA_ENDED,_(i)),p.once(x.PLAYOUT_LIMIT_REACHED,_(1/0)),p.on(x.ERROR,(T,b)=>{if(!this.schedule)return;const R=this.getAssetPlayer(u);if(b.details===H.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),p.on(x.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const b=new Error(`Asset player destroyed unexpectedly ${u}`),R={fatal:!0,type:Ee.OTHER_ERROR,details:H.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${es(t)}`),this.hls.trigger(x.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const n=this.playerQueue[i];this.log(`clear ${n} toSegment: ${t&&vi(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==l)&&(h&&(this.clearAssetPlayer(h.identifier,i[n]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${es(o)}`),this.hls.trigger(x.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:a}=e,o=this.schedule.findEventIndex(r.identifier),l=(i=this.schedule.items)==null?void 0:i[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;const c=this.getBufferingPlayer();if(c===e)return;const h=r.appendInPlace;if(h&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const u=(c==null?void 0:c.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!gc(u,e.tracks)){const d=new Error(`Asset ${es(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:Ee.OTHER_ERROR,details:H.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},p=r.findAssetIndex(a);this.handleAssetItemError(f,r,o,p,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||n-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${n})`),l&&(c/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,n,r){if(e.details===H.BUFFER_STALLED_ERROR)return;const a=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&es(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,u=at({},e,{fatal:!1,errorAction:Wn(!0),asset:a,assetListIndex:n,event:t,schedule:h,scheduleIndex:i,player:c});if(this.hls.trigger(x.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,p=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(v=>!v.error))t.error=p;else for(let v=n;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,i,n):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;let n=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${vi(i)} error: ${e.error}`),n===-1&&(n=this.hls.startPosition);const a=this.updateItem(i,n);this.itemsMatch(i,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(n===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var i,n;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;const l=r.timelineStart,c=r.duration;let h=0;o.forEach((v,m)=>{const g=parseFloat(v.DURATION);this.createAsset(r,m,h,l+h,g,v.URI),h+=g}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${r}`);const u=this.waitingItem,d=(u==null?void 0:u.event.identifier)===a;this.updateSchedule();const f=(n=this.bufferingItem)==null?void 0:n.event;if(d){var p;const v=this.schedule.findEventIndex(a),m=(p=this.schedule.items)==null?void 0:p[v];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==v){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(m)}this.setSchedulePosition(v)}else if((f==null?void 0:f.identifier)===a){const v=r.assetList[0];if(v){const m=this.getAssetPlayer(v.identifier);if(f.appendInPlace){const g=this.primaryMedia;m&&g&&this.bufferAssetPlayer(m,g)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case H.ASSET_LIST_PARSING_ERROR:case H.ASSET_LIST_LOAD_ERROR:case H.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case H.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const zu=500;class Wu extends br{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",ge.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(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=te.IDLE,this.setInterval(zu),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragContextChanged(i)||(Et(i)&&(this.fragPrevious=i),this.state=te.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=i.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,r,ge.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===ge.SUBTITLE&&(t.details===H.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==te.STOPPED&&(this.state=te.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&fu(this.levels,t)){this.levels=t.map(i=>new zn(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new zn(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ge.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==te.STOPPED&&this.setInterval(zu)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Ar(a,u),c=a.fragmentStart):d&&(c=d.start,Ja(a,c));else{var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&d&&(c=d.start,Ja(a,c))}u&&!this.startFragRequested&&this.setStartPosition(u,c)}l.details=a,this.levelLastLoaded=l,o===n&&(this.hls.trigger(x.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===te.IDLE&&(pn(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Xn(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Wa(n.method)).catch(o=>{throw r.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(x.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=te.IDLE})}}doTick(){if(!this.media){this.state=te.IDLE;return}if(this.state===te.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),a=Fe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:o,len:l}=a,c=i.details,h=this.hls.maxBufferLength+c.levelTargetDuration;if(l>h)return;const u=c.fragments,d=u.length,f=c.edge;let p=null;const v=this.fragPrevious;if(o<f){const E=n.maxFragLookUpTolerance,_=o>f-E?0:E;p=pn(v,u,Math.max(u[0].start,o),_),!p&&v&&v.start<u[0].start&&(p=u[0])}else p=u[d-1];if(p=this.filterReplacedPrimary(p,i.details),!p)return;const m=p.sn-c.startSN,g=u[m-1];if(g&&g.cc===p.cc&&this.fragmentTracker.getState(g)===bt.NOT_LOADED&&(p=g),this.fragmentTracker.getState(p)===bt.NOT_LOADED){const E=this.mapToInitFragWhenRequired(p);E&&this.loadFragment(E,i,o)}}}loadFragment(e,t,i){Et(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new zE(this.tracksBuffered[this.currentTrackId]||[])}}class zE{constructor(e){this.buffered=void 0;const t=(i,n,r)=>{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const WE={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},Ku=s=>String.fromCharCode(WE[s]||s),_i=15,Hi=100,KE={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},XE={17:2,18:4,21:6,22:8,23:10,19:13,20:15},YE={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},qE={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jE=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class QE{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;tt.log(`${this.time} [${e}] ${i}`)}}}const vn=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Xu{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const n=t[i];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ZE{constructor(){this.uchar=" ",this.penState=new Xu}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 JE{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Xu,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Hi;t++)this.chars.push(new ZE);this.logger=e}equals(e){for(let t=0;t<Hi;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Hi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Hi;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>Hi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Hi)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ku(e);if(this.pos>=Hi){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<Hi;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Hi;i++){const n=this.chars[i].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class bo{constructor(e){this.rows=[],this.currRow=_i-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<_i;t++)this.rows.push(new JE(e));this.logger=e}reset(){for(let e=0;e<_i;e++)this.rows[e].clear();this.currRow=_i-1}equals(e){let t=!0;for(let i=0;i<_i;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<_i;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<_i;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 = "+lt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<_i;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[a].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 = "+lt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let r=0;r<_i;r++){const a=this.rows[r].getTextString();a&&(n=r+1,e?t.push("Row "+n+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
3712
|
+
transfer tracks: ${lt(n,(l,c)=>l==="initSegment"?void 0:c)}}`),!gc(n,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,h=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(x.MEDIA_DETACHING,{}),this.onMediaAttaching(x.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{const c=l,h=n[c];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const m=Fe.getBuffered(u);d.detectEvictedFragments(c,m,f,null,!0)}const p=go(c),v=[c,u];this.sourceBuffers[p]=v,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),r.removeSourceBuffer(l[c]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&_u(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(x.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[go(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new N_(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!n[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var c,h;const u=t[l],{id:d,codec:f,levelCodec:p,container:v,metadata:m,supplemental:g}=u;let E=n[l];const _=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],T=_!=null&&_.buffer?_:E,b=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),R=T==null?void 0:T.levelCodec;E||(E=n[l]={buffer:void 0,listeners:[],codec:f,supplemental:g,container:v,levelCodec:p,metadata:m,id:d});const A=fr(b,R),C=A==null?void 0:A.replace(mu,"$1");let S=fr(f,p);const y=(h=S)==null?void 0:h.replace(mu,"$1");S&&A&&C!==y&&(l.slice(0,5)==="audio"&&(S=dr(S,this.appendSource)),this.log(`switching codec ${b} to ${S}`),S!==(E.pendingCodec||E.codec)&&(E.pendingCodec=S),E.container=v,this.appendChangeType(l,v,S))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),o.changeType(n),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,ge.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>n||l!=null&&l.buffer&&Fe.isBuffered(l.buffer,n)||((o=this.fragmentTracker.getAppendedFrag(n,ge.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:a,frag:o,part:l,chunkMeta:c,offset:h}=t,u=c.buffering[r],{sn:d,cc:f}=o,p=self.performance.now();u.start=p;const v=o.stats.buffering,m=l?l.stats.buffering:null;v.start===0&&(v.start=p),m&&m.start===0&&(m.start=p);const g=i.audio;let E=!1;r==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const _=i.video,T=_==null?void 0:_.buffer;if(T&&d!=="initSegment"){const A=l||o,C=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(_.ending||_.ended)){const y=A.start+A.duration*.05,w=T.buffered,N=this.currentOp("video");!w.length&&!N?this.blockAudio(A):!N&&!Fe.isBuffered(T,y)&&this.lastVideoAppendEnd<y&&this.blockAudio(A)}else if(r==="video"){const S=A.end;if(C){const y=C.frag.start;(S>y||S<this.lastVideoAppendEnd||Fe.isBuffered(T,y))&&this.unblockAudio()}this.lastVideoAppendEnd=S}}const b=(l||o).start,R={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const C=(A=this.tracks[r])==null?void 0:A.buffer;C&&(E?this.updateTimestampOffset(C,b,.1,r,d,f):h!==void 0&&de(h)&&this.updateTimestampOffset(C,h,1e-6,r,d,f)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,v.first===0&&(v.first=A),m&&m.first===0&&(m.first=A);const C={};this.sourceBuffers.forEach(([S,y])=>{S&&(C[S]=Fe.getBuffered(y))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(x.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:C})},onError:A=>{var C;const S={type:Ee.MEDIA_ERROR,parent:o.type,details:z.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:c,error:A,err:A,fatal:!1},y=(C=this.media)==null?void 0:C.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)S.details=z.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!y)S.errorAction=Wn(!0);else if(A.name===gu&&this.sourceBufferCount===0)S.errorAction=Wn(!0);else{const w=++this.appendErrors[r];this.warn(`Failed ${w}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${y||"no media error"})`),(w>=this.hls.config.appendErrorMaxRetry||y)&&(S.fatal=!0)}this.hls.trigger(x.ERROR,S)}};this.log(`queuing "${r}" append sn: ${d}${l?" p: "+l.index:""} of ${o.type===ge.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(R,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(x.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,n,r),a)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[ot.AUDIOVIDEO]?r.push("audiovideo"):(a[ot.AUDIO]&&r.push("audio"),a[ot.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const c=n?n.stats:i.stats;this.hls.trigger(x.FRAG_BUFFERED,{frag:i,part:n,stats:c,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(x.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(x.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}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(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===z.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;de(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,a=t.levelTargetDuration,o=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(de(o)&&o>=0){const c=Math.max(o,a),h=Math.floor(r/a)*a-c;this.flushBackBuffer(r,a,h)}const l=n.frontBufferFlushThreshold;if(de(l)&&l>0){const c=Math.max(n.maxBufferLength,l),h=Math.max(c,a),u=Math.floor(r/a)*a+h;this.flushFrontBuffer(r,a,u)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=Fe.getBuffered(r);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(x.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger(x.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const a=Fe.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(i>l||e>=l&&e<=c)return;this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),h=Math.max(c,n);return{duration:1/0,start:c,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return de(r)?{duration:r}:null;const a=this.media.duration,o=de(i.duration)?i.duration:0;return n>o&&n>a||!de(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(de(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${lt(i)}`),this.tracksReady){var n;const r=(n=this.transferData)==null?void 0:n.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(x.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(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${lt(o)}`);try{const h=i.addSourceBuffer(c),u=go(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var n;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&fs(i,"video")&&(n=F0(n,i));const r=fr(n,e.levelCodec);return r?t.slice(0,5)==="audio"?dr(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(x.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,a){const o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!n||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=de(n.duration)?n.duration:1/0,c=de(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(i,l,c);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i==null?void 0:i.buffer;if(!n)throw new k_(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const a=i.bind(this,e);n.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function _u(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function B_(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function go(s){return s==="audio"?1:0}class Fr{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(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&de(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,Fr.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&n(l,e[o+1])){r=o;break}}return r}}const Qt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},G_={HLS:"h"};class Ri{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Ri?i:new Ri(i))),this.value=e,this.params=t}}const V_="Dict";function H_(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function $_(s,e,t,i){return new Error(`failed to ${s} "${H_(e)}" as ${t}`,{cause:i})}function Mi(s,e,t){return $_("serialize",s,e,t)}class Eu{constructor(e){this.description=e}}const xu="Bare Item",z_="Boolean";function W_(s){if(typeof s!="boolean")throw Mi(s,z_);return s?"?1":"?0"}function K_(s){return btoa(String.fromCharCode(...s))}const X_="Byte Sequence";function Y_(s){if(ArrayBuffer.isView(s)===!1)throw Mi(s,X_);return`:${K_(s)}:`}const q_="Integer";function j_(s){return s<-999999999999999||999999999999999<s}function Su(s){if(j_(s))throw Mi(s,q_);return s.toString()}function Q_(s){return`@${Su(s.getTime()/1e3)}`}function yu(s,e){if(s<0)return-yu(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const n=Math.floor(s*t);return(n%2===0?n:n+1)/t}else return Math.round(s*t)/t}const Z_="Decimal";function J_(s){const e=yu(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Mi(s,Z_);const t=e.toString();return t.includes(".")?t:`${t}.0`}const eE="String",tE=/[\x00-\x1f\x7f]+/;function iE(s){if(tE.test(s))throw Mi(s,eE);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function nE(s){return s.description||s.toString().slice(7,-1)}const sE="Token";function Tu(s){const e=nE(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Mi(e,sE);return e}function vo(s){switch(typeof s){case"number":if(!de(s))throw Mi(s,xu);return Number.isInteger(s)?Su(s):J_(s);case"string":return iE(s);case"symbol":return Tu(s);case"boolean":return W_(s);case"object":if(s instanceof Date)return Q_(s);if(s instanceof Uint8Array)return Y_(s);if(s instanceof Eu)return Tu(s);default:throw Mi(s,xu)}}const rE="Key";function _o(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Mi(s,rE);return s}function Eo(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${_o(e)}`:`;${_o(e)}=${vo(t)}`).join("")}function Au(s){return s instanceof Ri?`${vo(s.value)}${Eo(s.params)}`:vo(s)}function aE(s){return`(${s.value.map(Au).join(" ")})${Eo(s.params)}`}function oE(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Mi(s,V_);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Ri||(r=new Ri(r));let a=_o(n);return r.value===!0?a+=Eo(r.params):(a+="=",Array.isArray(r.value)?a+=aE(r):a+=Au(r)),a}).join(`,${i}`)}function bu(s,e){return oE(s,e)}const Li="CMCD-Object",gt="CMCD-Request",mn="CMCD-Session",tn="CMCD-Status",lE={br:Li,ab:Li,d:Li,ot:Li,tb:Li,tpb:Li,lb:Li,tab:Li,lab:Li,url:Li,pb:gt,bl:gt,tbl:gt,dl:gt,ltc:gt,mtp:gt,nor:gt,nrr:gt,rc:gt,sn:gt,sta:gt,su:gt,ttfb:gt,ttfbb:gt,ttlb:gt,cmsdd:gt,cmsds:gt,smrt:gt,df:gt,cs:gt,ts:gt,cid:mn,pr:mn,sf:mn,sid:mn,st:mn,v:mn,msd:mn,bs:tn,bsd:tn,cdn:tn,rtp:tn,bg:tn,pt:tn,ec:tn,e:tn},cE={REQUEST:gt};function hE(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(n=>e[n]=t),e},{})}function uE(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?hE(e):{};return i.reduce((r,a)=>{var o;const l=lE[a]||n[a]||cE.REQUEST,c=(o=r[l])!==null&&o!==void 0?o:r[l]={};return c[a]=s[a],r},t)}function dE(s){return["ot","sf","st","e","sta"].includes(s)}function fE(s){return typeof s=="number"?de(s):s!=null&&s!==""&&s!==!1}const Ru="event";function pE(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const n=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const Or=s=>Math.round(s),xo=(s,e)=>Array.isArray(s)?s.map(t=>xo(t,e)):s instanceof Ri&&typeof s.value=="string"?new Ri(xo(s.value,e),s.params):(e.baseUrl&&(s=pE(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Ur=s=>Or(s/100)*100,mE={br:Or,d:Or,bl:Ur,dl:Ur,mtp:Ur,nor:(s,e)=>{let t=s;return e.version>=2&&(s instanceof Ri&&typeof s.value=="string"?t=new Ri([s]):typeof s=="string"&&(t=[s])),xo(t,e)},rtp:Ur,tb:Or},Mu="request",Lu="response",So=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],gE=["e"],vE=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Nr(s){return vE.test(s)}function _E(s){return So.includes(s)||gE.includes(s)||Nr(s)}const Iu=["d","dl","nor","ot","rtp","su"];function EE(s){return So.includes(s)||Iu.includes(s)||Nr(s)}const xE=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function SE(s){return So.includes(s)||Iu.includes(s)||xE.includes(s)||Nr(s)}const yE=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function TE(s){return yE.includes(s)||Nr(s)}const AE={[Lu]:SE,[Ru]:_E,[Mu]:EE};function Cu(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||Mu,r=i===1?TE:AE[n];let a=Object.keys(s).filter(r);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=n===Lu||n===Ru;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const c=at({},mE,e.formatters),h={version:i,reportingMode:n,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let d=s[u];const f=c[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(i===1)return;d=i}u=="pr"&&d===1||(l&&u==="ts"&&!de(d)&&(d=Date.now()),fE(d)&&(dE(u)&&typeof d=="string"&&(d=new Eu(d)),t[u]=d))}),t}function bE(s,e={}){const t={};if(!s)return t;const i=Cu(s,e),n=uE(i,e==null?void 0:e.customHeaderMap);return Object.entries(n).reduce((r,[a,o])=>{const l=bu(o,{whitespace:!1});return l&&(r[a]=l),r},t)}function RE(s,e,t){return at(s,bE(e,t))}const ME="CMCD";function LE(s,e={}){return s?bu(Cu(s,e),{whitespace:!1}):""}function IE(s,e={}){if(!s)return"";const t=LE(s,e);return encodeURIComponent(t)}function CE(s,e={}){if(!s)return"";const t=IE(s,e);return`${ME}=${t}`}const wu=/CMCD=[^&#]+/;function wE(s,e,t){const i=CE(e,t);if(!i)return s;if(wu.test(s))return s.replace(wu,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class Du{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:Qt.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:a}=n,o=this.hls.levels[r.level],l=this.getObjectType(r),c={d:(a||r).duration*1e3,ot:l};(l===Qt.VIDEO||l===Qt.AUDIO||l==Qt.MUXED)&&(c.br=o.bitrate/1e3,c.tb=this.getTopBandwidth(l)/1e3,c.bl=this.getBufferLength(l));const h=a?this.getNextPart(a):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(c.nor=h.url),this.apply(n,c)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHED,this.onMediaDetached,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHED,this.onMediaDetached,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:G_.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){at(t,this.createData());const i=t.ot===Qt.INIT||t.ot===Qt.VIDEO||t.ot===Qt.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((a,o)=>(n.includes(o)&&(a[o]=t[o]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),RE(e.headers,t,r)):e.url=wE(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=n;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===i&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Qt.TIMED_TEXT;if(e.sn==="initSegment")return Qt.INIT;if(t==="audio")return Qt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Qt.VIDEO:Qt.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Qt.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Qt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Fe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const DE=3e5;class Pu extends li{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===It.SendAlternateToPenaltyBox&&i.flags===Yt.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&n?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),t.details===z.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${n&&n.length} priorities: ${lt(r)} penalized: ${lt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>DE&&delete i[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Dh(t),this.hls.trigger(x.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<n.length;r++)if(t===Ye.AUDIO_TRACK&&n[r].hasAudioGroup(e)||t===Ye.SUBTITLE_TRACK&&n[r].hasSubtitleGroup(e))return n[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new ft(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(i[u.AUDIO]=d,u.AUDIO=d),f&&(n[u.SUBTITLES]=f,u.SUBTITLES=f);const p=Ou(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),v=new zn({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:p,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let m=1;m<h.audioGroups.length;m++)v.addGroupId("audio",`${h.audioGroups[m]}_clone_${a}`);if(h.subtitleGroups)for(let m=1;m<h.subtitleGroups.length;m++)v.addGroupId("text",`${h.subtitleGroups[m]}_clone_${a}`);return v});t.push(...c),Fu(this.audioTracks,i,l,a),Fu(this.subtitleTracks,n,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:n.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${n}"`);const p=h.data;if((p==null?void 0:p.VERSION)!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":v,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":g}=p;if(v)try{this.uri=new self.URL(v,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${v}`);return}this.scheduleRefresh(this.uri||d.url),m&&this.clonePathways(m);const E={steeringManifest:p,url:n.toString()};this.hls.trigger(x.STEERING_MANIFEST_LOADED,E),g&&this.updatePathwayPriority(g)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let p=this.timeToLoad*1e3;if(h.code===429){const v=this.loader;if(typeof(v==null?void 0:v.getResponseHeader)=="function"){const m=v.getResponseHeader("Retry-After");m&&(p=parseFloat(m)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,p)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Fu(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const o=at({},a);return o.details=void 0,o.attrs=new ft(o.attrs),o.url=o.attrs.URI=Ou(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[n],o.attrs["PATHWAY-ID"]=i,o});s.push(...r)})}function Ou(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return n&&!o&&(l.host=n),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}class gn extends li{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=gn.CDMCleanupPromise?[gn.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=gs(this.config));const o=a.map(Ya).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Tr(a);if(i!=="sinf"||o!==pt.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{const f=At(new Uint8Array(n)),p=Ka(JSON.parse(f).sinf),v=Lc(p);if(!v)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(v.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const c=Ut(l),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[c];for(let f=0;f<u.length;f++){const p=u[f],v=p.decryptdata;if(!v.keyId)continue;const m=Ut(v.keyId);if(Sr(l,v.keyId)||v.uri.replace(/-/g,"").indexOf(c)!==-1){if(d=h[m],!d)continue;if(v.pssh)break;delete h[m],v.pssh=new Uint8Array(n),v.keyId=l,d=h[c]=d.then(()=>this.generateRequestWithPreferredKeySession(p,i,n,"encrypted-event-key-match")),d.catch(g=>this.handleError(g));break}}d||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(x.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(x.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t==null?void 0:t[e];if(n)return n.licenseUrl;if(e===pt.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t==null?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,n,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof ni?o(u):o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return qa===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){var n;const r=xv(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(n=a)==null?void 0:n.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${lt(r)}`),o=this.requestMediaKeySystemAccess(e,r);const l=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 h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ut(e.keyId||[])} keyUri: ${e.uri}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=kr(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ut(e.decryptdata.keyId||[])}
|
|
3713
|
+
} (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ya(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const r=Ya(n);r?t(r):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}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){const t=gs(this.config),i=e.map(Tr).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const n=PE(e,t[i]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,i=kr(t),n=this.bannedKeyIds[i];if(n||this.getKeyStatus(t)==="internal-error"){const o=Uu(n||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const a=this.keyIdToKeySessionPromise[i];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(l,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:c,decryptdata:t}))))).then(l=>{const c="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,c,h,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof ni){const l=et({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);const c=new ni(l,o.message);this.handleError(c,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof ni){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ut(i.keyId||[])})`:""}`),this.hls.trigger(x.ERROR,e.data)}else this.error(e.message),this.hls.trigger(x.ERROR,{type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=kr(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Tr(e.keyFormat),r=n?[n]:gs(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=gs(this.config)),e.length===0)throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${lt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r;const a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const p=a.call(this.hls,t,i,e);if(!p)throw new Error("Invalid response from configured generateRequest filter");t=p.initDataType,i=p.initData?p.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(p){if(this.warn(p.message),this.hls&&this.hls.config.debug)throw p}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const o=kr(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);const c=new to,h=e._onmessage=p=>{const v=e.mediaKeysSession;if(!v){c.emit("error",new Error("invalid state"));return}const{messageType:m,message:g}=p;this.log(`"${m}" message event for session "${v.sessionId}" message size: ${g.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,g).catch(E=>{c.eventNames().length?c.emit("error",E):this.handleError(E)}):m==="license-release"?e.keySystem===pt.FAIRPLAY&&this.updateKeySession(e,Xa("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${m}"`)},u=(p,v)=>{v.keyStatus=p;let m;p.startsWith("usable")?c.emit("resolved"):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?m=Uu(p,v.decryptdata):p==="expired"?m=new Error(`key expired (keyId: ${o})`):p==="released"?m=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${o})`),m&&(c.eventNames().length?c.emit("error",m):this.handleError(m))},d=e._onkeystatuseschange=p=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const m=this.getKeyStatuses(e);if(!Object.keys(m).some(T=>m[T]!=="status-pending"))return;if(m[o]==="expired"){this.log(`Expired key ${lt(m)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=m[o];if(E)u(E,e);else{var _;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(_=e.keyStatusTimeouts)[o]||(_[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const b=this.getKeyStatus(e.decryptdata);if(b&&b!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${b} from other session.`),u(b,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",u(E,e)},1e3)),this.log(`No status for keyId ${o} (${lt(m)}).`)}};Ht(e.mediaKeysSession,"message",h),Ht(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((p,v)=>{c.on("error",v),c.on("resolved",p)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(p=>{throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>f).catch(p=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw p}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,n)=>{if(typeof n=="string"&&typeof i=="object"){const o=n;n=i,i=o}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===pt.PLAYREADY&&r.length===16){const o=Ut(r);t[o]=i,uh(r)}const a=Ut(r);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{a(d.data)},onError:(d,f,p,v)=>{o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:et({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,p)=>{o(new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,p)=>{o(new Error("aborted"))}};n.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,p=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&p&&e.setRequestHeader(f,p)}}const l=n.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Xa(atob(c))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(h){this.error(h)}n(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new ni({type:Ee.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==pt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Ht(i,"encrypted",this.onMediaEncrypted),Ht(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(qt(e,"encrypted",this.onMediaEncrypted),qt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Bi.clearKeyUriToKeyIdMap();const r=n.length;gn.CDMCleanupPromise=Promise.all(n.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ut((n==null?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(c=>self.clearTimeout(a[c]));const{drmSystemOptions:o}=this.config;return(yv(o)?new Promise((c,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(c).catch(h)}):Promise.resolve()).catch(c=>{this.log(`Could not remove session: ${c}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${c}`)})}).then(()=>t.close()).catch(c=>{this.log(`Could not close session: ${c}`),this.hls&&this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}gn.CDMCleanupPromise=void 0;function kr(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Ut(s.keyId)}function PE(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class ni extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Uu(s,e){const t=s==="output-restricted",i=t?z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ni({type:Ee.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class Nu{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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(x.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(x.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function ku(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function Bu(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){tt.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){tt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Zn(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function yo(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=OE(s.cues,e,t);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&s.removeCue(r[a])}n==="disabled"&&(s.mode=n)}function FE(s,e){if(e<=s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),e<s[r].startTime)n=r-1;else if(e>s[r].startTime&&i<t)i=r+1;else return r;return s[i].startTime-e<e-s[n].startTime?i:n}function OE(s,e,t){const i=[],n=FE(s,e);if(n>-1)for(let r=n,a=s.length;r<a;r++){const o=s[r];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Br(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}class Gu extends Pr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Br(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];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(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(x.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Br(i.textTracks).forEach(a=>{Zn(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||(n==null?void 0:n.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Ai(o,a);if(h>-1)r=a[h];else{const u=Ai(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(x.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const r=t[n];if(!(i&&!r.default||!i&&!e)&&(!e||dn(r,e)))return n}if(e){for(let n=0;n<t.length;n++){const r=t[n];if(Ts(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const r=t[n];if(Ts(e.attrs,r.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const n=t[i];if(mo(n,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Ye.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&dn(e,i))return i;const n=Ai(e,this.tracksInGroup);if(n>-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=Ai(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(x.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Br(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>mo(i,r))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==n&&(r.mode="disabled")}),n){const r=this.subtitleDisplay?"showing":"hidden";n.mode!==r&&(n.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!de(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:h}=n;this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:h});const u=this.switchParams(n.url,i==null?void 0:i.details,n.details);this.loadPlaylist(u)}}function UE(){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 r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?r:r&3|8).toString(16)})}}}function As(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Jn=.025;let Gr=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function NE(s,e,t){return`${s.identifier}-${t+1}-${As(e)}`}class kE{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return To(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=To(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=de(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return To(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)<Jn))}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"?Gr.Range:Gr.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 BE(this)}}function To(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<Jn)?e.start:e.start+e.duration}function Vu(s,e,t){const i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function Ao(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function BE(s){return`["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function es(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class GE{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(x.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const a=()=>{this.hasDetails=!0};r.once(x.LEVEL_LOADED,a),r.once(x.AUDIO_TRACK_LOADED,a),r.once(x.SUBTITLE_TRACK_LOADED,a),r.on(x.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(x.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(x.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Vu(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=Fe.bufferInfo(e,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Fe.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;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>11111111111111112e-21&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,i){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,i){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${es(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Hu=.033;class VE extends li{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;n<i.length;n++){let r=i[n];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return n}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let n=e;n<=t&&i[n];n++){const r=i[n].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var i;if(((i=t[n].event)==null?void 0:i.identifier)===e)return n}return-1}findAssetIndex(e,t){const i=e.assetList,n=i.length;if(n>1)for(let r=0;r<n;r++){const a=i[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===n-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,n=i[i.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:n}=i,r=this.events,a=this.parseDateRanges(n,{url:i.url},t),o=Object.keys(n),l=r?r.filter(c=>!o.includes(c.identifier)):[];a.length&&a.sort((c,h)=>{const u=c.cue.pre,d=c.cue.post,f=h.cue.pre,p=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!p)return 1;if(p&&!d)return-1;if(!u&&!f&&!d&&!p){const v=c.startTime,m=h.startTime;if(v!==m)return v-m}return c.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=a,l.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,a=this.parseSchedule(n,e);(i||t.length||(r==null?void 0:r.length)!==a.length||a.some((l,c)=>Math.abs(l.playout.start-r[c].playout.start)>.005||Math.abs(l.playout.end-r[c].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new kE(l,t),this.eventMap[o]=c,i===!1&&(c.appendInPlace=i)),n.push(c)}}return n}parseSchedule(e,t){const i=[],n=t.main.details,r=n.live?1/0:n.edge;let a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,c=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,p=e[u-1]||null,v=h.appendInPlace,m=f?r:h.startOffset,g=h.duration,E=h.timelineOccupancy===Gr.Range?g:0,_=h.resumptionOffset,T=(p==null?void 0:p.startTime)===m,b=m+h.cumulativeDuration;let R=v?b+g:m+_;if(d||!f&&m<=0){const C=c;c+=E,h.timelineStart=b;const S=a;a+=g,i.push({event:h,start:b,end:R,playout:{start:S,end:a},integrated:{start:C,end:c}})}else if(m<=r){if(!T){const y=m-l;if(y>Hu){const w=l,N=c;c+=y;const Y=a;a+=y;const D={previousEvent:e[u-1]||null,nextEvent:h,start:w,end:w+y,playout:{start:Y,end:a},integrated:{start:N,end:c}};i.push(D)}else y>0&&p&&(p.cumulativeDuration+=y,i[i.length-1].end=m)}f&&(R=b),h.timelineStart=b;const C=c;c+=E;const S=a;a+=g,i.push({event:h,start:b,end:R,playout:{start:S,end:a},integrated:{start:C,end:c}})}else return;const A=h.resumeTime;f||A>r?l=r:l=A}),l<r){var o;const h=l,u=c,d=r-l;c+=d;const f=a;a+=d,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:h+d,playout:{start:f,end:a},integrated:{start:u,end:c}})}this.setDurations(r,a,c)}else i.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,n=i.live?1/0:i.edge;let r=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,h=o.cue.post,u=c?0:h?n:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=pn(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Hu&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=de(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>Jn?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;const c=pn(null,o.fragments,i);if(!c)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(c.start-i)<Jn+h||Math.abs(c.end-i)<Jn+h?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,n=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,n||(n=o.duration===null),r||(r=!!o.error);const c=o.error?0:o.duration||0;i+=c}n&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function vi(s){return`[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}class HE{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let n;try{n=Vu(i,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,d,i);this.hls.trigger(x.ERROR,f);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),l={responseType:"json",url:n.href},c=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{const m=d.data,g=m==null?void 0:m.ASSETS;if(!Array.isArray(g)){const E=this.assignAssetListError(e,z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),p.url,f,v);this.hls.trigger(x.ERROR,E);return}e.assetListResponse=m,this.hls.trigger(x.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:v})},onError:(d,f,p,v)=>{const m=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,v,p);this.hls.trigger(x.ERROR,m)},onTimeout:(d,f,p)=>{const v=this.assignAssetListError(e,z.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,p);this.hls.trigger(x.ERROR,v)}};return o.load(l,h,u),this.hls.trigger(x.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,n,r,a){return e.error=i,{type:Ee.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:a,stats:r}}}function $u(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function ts(s,e){return`[${s}] Advancing timeline position to ${e}`}class $E extends li{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const a=n<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;const f=this.findItemIndex(o);let p=this.schedule.findItemIndexAtTime(i);if(p===-1&&(p=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${p})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&p>f){const v=this.schedule.findJumpRestrictedIndex(f+1,p);if(v>f){this.setSchedulePosition(v);return}}this.setSchedulePosition(p);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}const h=c.timelineStart,u=c.duration||0;if(a&&i<h||i>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,c)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const o=this.findItemIndex(n);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],c=r.durations,h=i.map(v=>v.identifier),u=!!(o.length||h.length);(u||n)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
3714
|
+
Schedule: ${l.map(v=>vi(v))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),i.forEach(v=>{v.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(v=>{if(v.interstitial.appendInPlace){const m=v.assetItem.timelineStart,g=v.timelineOffset-m;if(g)try{v.timelineOffset=m}catch(E){Math.abs(g)>Jn&&this.warn(`${E} ("${v.assetId}" ${v.timelineOffset}->${m})`)}}}),u||n){if(this.hls.trigger(x.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(a)&&h.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),p&&f!==d&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new HE(e),this.schedule=new VE(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(x.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(x.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(x.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(x.MEDIA_ENDED,this.onMediaEnded,this),e.on(x.ERROR,this.onError,this),e.on(x.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(x.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(x.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(x.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(x.MEDIA_ENDED,this.onMediaEnded,this),e.off(x.ERROR,this.onError,this),e.off(x.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){qt(e,"play",this.onPlay),qt(e,"pause",this.onPause),qt(e,"seeking",this.onSeeking),qt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Ht(i,"seeking",this.onSeeking),Ht(i,"timeupdate",this.onTimeupdate),Ht(i,"play",this.onPlay),Ht(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),n=(u,d,f,p,v)=>{if(u){let m=u[d].start;const g=u.event;if(g){if(d==="playout"||g.timelineOccupancy!==Gr.Point){const E=i(f);(E==null?void 0:E.interstitial)===g&&(m+=E.assetItem.startOffset+E[v])}}else{const E=p==="bufferedPos"?a():e[p];m+=E-u.start}return m}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var p;const v=e.schedule.findItemIndexAtTime(u),m=(p=e.schedule.items)==null?void 0:p[v];if(m){const g=m[d].start-m.start;return u+g}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,d)=>{var f,p;const v=e.effectivePlayingItem;if(v!=null&&(f=v.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const m=e.effectivePlayingItem,g=e.schedule.findItemIndexAtTime(u,d),E=(p=e.schedule.items)==null?void 0:p[g],_=e.getBufferingPlayer(),T=_==null?void 0:_.interstitial,b=T==null?void 0:T.appendInPlace,R=m&&e.itemsMatch(m,E);if(m&&(b||R)){const A=i(e.playingAsset),C=(A==null?void 0:A.media)||e.primaryMedia;if(C){const S=d==="primary"?C.currentTime:n(m,d,e.playingAsset,"timelinePos","currentTime"),y=u-S,w=(b?S:C.currentTime)+y;if(w>=0&&(!A||b||w<=A.duration)){C.currentTime=w;return}}}if(E){let A=u;if(d!=="primary"){const S=E[d].start,y=u-S;A=E.start+y}const C=!e.isInterstitial(E);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(C||E.event.appendInPlace)){const S=e.media||(b?_==null?void 0:_.media:null);S&&(S.currentTime=A)}else if(m){const S=e.findItemIndex(m);if(g>S){const w=e.schedule.findJumpRestrictedIndex(S+1,g);if(w>S){e.setSchedulePosition(w);return}}let y=0;if(C)e.timelinePos=A,e.checkBuffer();else{const w=E.event.assetList,N=u-(E[d]||E).start;for(let Y=w.length;Y--;){const D=w[Y];if(D.duration&&N>=D.startOffset&&N<D.startOffset+D.duration){y=Y;break}}}e.setSchedulePosition(g,y)}}},c=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return n(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=c(),d=e.effectivePlayingItem;return d&&d===u?n(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=c(),f=e.effectivePlayingItem;f&&f===d&&l(u+f.playout.start,"playout")},get duration(){const u=c();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=c())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=c())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return c()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.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(u){l(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u==null?void 0:u.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const p=u.playout.start+u.event.duration;l(p+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(t=n)==null?void 0:t.currentTime;if(!(r===void 0||!de(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${lt(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(i=this.detachedData)==null?void 0:i.mediaSource;let h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else if(c){const p=this.getBufferingPlayer();p?(r=p.transferMedia(),h=`${p}`):h="detached MediaSource"}else h="detached media";if(!r){if(c)r=this.detachedData,this.log(`using detachedData: MediaSource ${lt(r)}`);else if(!this.detachedData||a.media===t){const p=this.playerQueue;p.length>1&&p.forEach(v=>{if(o&&v.interstitial.appendInPlace!==l){const m=v.interstitial;this.clearInterstitial(v.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(d===r&&f){const p=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||p,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(ts("checkStart (preroll)",r));const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){this.log(ts("checkStart",r));const a=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(ts("checkStart (playing item)",n.start));const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=Ao(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,i){const n=Ao(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,o=r.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(ts("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const r=e.assetList[n];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const n=t.parentIdentifier,r=i.getEvent(n);if(r){const a=i.findEventIndex(n),o=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var i;const n=(i=this.schedule)==null?void 0:i.items;if(!n||this.playbackDisabled)return;const r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&vi(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const h=a.event,u=this.playingAsset,d=u==null?void 0:u.identifier,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,r)||t!==void 0&&d!==h.assetList[t].identifier)){var l;const p=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${h.assetList.length} ${es(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(x.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:p,event:h,schedule:n.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(d,r),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${vi(a)}`),h.hasPlayed=!0,this.hls.trigger(x.INTERSTITIAL_ENDED,{event:h,schedule:n.slice(0),scheduleIndex:e}),h.cue.once)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(r&&p){const v=this.findItemIndex(r);this.advanceSchedule(v,p,t,a,o)}return}}this.advanceSchedule(e,n,t,a,o)}advanceSchedule(e,t,i,n,r){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(i===void 0){i=a.findAssetIndex(h,this.timelinePos);const p=Ao(h,i-1);if(h.isAssetPastPlayoutLimit(p)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,i);return}i=p}const u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(h,i);if(this.eventItemsMatch(o,u||n)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${vi(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(x.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[i];if(!f){this.advanceAfterAssetEnded(h,e,i||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const p=h.assetList.length;this.warn(`asset ${i+1}/${p} player destroyed ${h}`),d=this.createAssetPlayer(h,f,i),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,i,t,e,l),this.shouldPlay&&$u(d.media)}else o?(this.resumePrimary(o,e,n),this.shouldPlay&&$u(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${vi(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(ts("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${vi(e)}`),this.hls.trigger(x.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(i<n.fragmentStart||i>n.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Fe.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(ts("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(x.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(x.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=et(et({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=et(et({},this.altSelection),{},{audio:i});return}const r=et(et({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=et(et({},this.altSelection),{},{subtitles:i});return}const r=et(et({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=Hc(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Hc(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const r=t[n];if(r.cue.post){var i;const a=this.schedule.findEventIndex(r.identifier),o=(i=this.schedule.items)==null?void 0:i[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const n=(i=this.schedule)==null?void 0:i.items;if(e&&n){const r=this.findItemIndex(e,t);return n[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=Fe.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${vi(e)} (was ${vi(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const n=Fe.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((l===-1&&r&&e>=r.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${vi(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(x.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,a=e.cue.once;if(r){const l=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-l;d>0&&(c=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${c?` live-start: ${h} start-offset: ${c}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const u=this.assetListLoader.loadAssetList(e,c);u&&(e.assetListLoader=u)}else if(!a&&n){for(let c=t;c<n;c++){const h=e.assetList[c],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}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(x.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,n,r,a){const o={parentIdentifier:e.identifier,identifier:NE(e,a,t),duration:r,startOffset:i,timelineStart:n,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){const n=this.hls,r=n.userConfig;let a=r.videoPreference;const o=n.loadLevelObj||n.levels[n.currentLevel];(a||o)&&(a=at({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=n.audioTracks[n.audioTrack],c=n.subtitleTracks[n.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const b=t.duration;b&&T<b&&(h=T)}}const u=t.identifier,d=et(et({},r),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||r.audioPreference,subtitlePreference:c||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=at({},f,{contentId:As(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const p=new GE(this.HlsPlayerClass,d,e,t);this.playerQueue.push(p),e.assetList[i]=t;let v=!0;const m=T=>{if(T.live){var b;const C=new Error(`Interstitials MUST be VOD assets ${e}`),S={fatal:!0,type:Ee.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:C},y=((b=this.schedule)==null?void 0:b.findEventIndex(e.identifier))||-1;this.handleAssetItemError(S,e,y,i,C.message);return}const R=T.edge-T.fragmentStart,A=t.duration;(v||A===null||R>A)&&(v=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${R}`),t.duration=R,this.updateSchedule())};p.on(x.LEVEL_UPDATED,(T,{details:b})=>m(b)),p.on(x.LEVEL_PTS_UPDATED,(T,{details:b})=>m(b)),p.on(x.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const g=(T,b)=>{const R=this.getAssetPlayer(u);if(R&&b.tracks){R.off(x.BUFFER_CODECS,g),R.tracks=b.tracks;const A=this.primaryMedia;this.bufferingAsset===R.assetItem&&A&&!R.media&&this.bufferAssetPlayer(R,A)}};p.on(x.BUFFER_CODECS,g);const E=()=>{var T;const b=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${b}`),!b||!this.schedule)return;const R=this.schedule.findEventIndex(e.identifier),A=(T=this.schedule.items)==null?void 0:T[R];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};p.on(x.BUFFERED_TO_END,E);const _=T=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,T)};return p.once(x.MEDIA_ENDED,_(i)),p.once(x.PLAYOUT_LIMIT_REACHED,_(1/0)),p.on(x.ERROR,(T,b)=>{if(!this.schedule)return;const R=this.getAssetPlayer(u);if(b.details===z.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),p.on(x.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const b=new Error(`Asset player destroyed unexpectedly ${u}`),R={fatal:!0,type:Ee.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${es(t)}`),this.hls.trigger(x.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const n=this.playerQueue[i];this.log(`clear ${n} toSegment: ${t&&vi(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==l)&&(h&&(this.clearAssetPlayer(h.identifier,i[n]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${es(o)}`),this.hls.trigger(x.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:a}=e,o=this.schedule.findEventIndex(r.identifier),l=(i=this.schedule.items)==null?void 0:i[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;const c=this.getBufferingPlayer();if(c===e)return;const h=r.appendInPlace;if(h&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const u=(c==null?void 0:c.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!gc(u,e.tracks)){const d=new Error(`Asset ${es(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:Ee.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},p=r.findAssetIndex(a);this.handleAssetItemError(f,r,o,p,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||n-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${n})`),l&&(c/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,n,r){if(e.details===z.BUFFER_STALLED_ERROR)return;const a=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&es(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,u=at({},e,{fatal:!1,errorAction:Wn(!0),asset:a,assetListIndex:n,event:t,schedule:h,scheduleIndex:i,player:c});if(this.hls.trigger(x.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,p=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(v=>!v.error))t.error=p;else for(let v=n;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,i,n):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;let n=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${vi(i)} error: ${e.error}`),n===-1&&(n=this.hls.startPosition);const a=this.updateItem(i,n);this.itemsMatch(i,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(n===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var i,n;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;const l=r.timelineStart,c=r.duration;let h=0;o.forEach((v,m)=>{const g=parseFloat(v.DURATION);this.createAsset(r,m,h,l+h,g,v.URI),h+=g}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${r}`);const u=this.waitingItem,d=(u==null?void 0:u.event.identifier)===a;this.updateSchedule();const f=(n=this.bufferingItem)==null?void 0:n.event;if(d){var p;const v=this.schedule.findEventIndex(a),m=(p=this.schedule.items)==null?void 0:p[v];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==v){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(m)}this.setSchedulePosition(v)}else if((f==null?void 0:f.identifier)===a){const v=r.assetList[0];if(v){const m=this.getAssetPlayer(v.identifier);if(f.appendInPlace){const g=this.primaryMedia;m&&g&&this.bufferAssetPlayer(m,g)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case z.ASSET_LIST_PARSING_ERROR:case z.ASSET_LIST_LOAD_ERROR:case z.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case z.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const zu=500;class Wu extends br{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",ge.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(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=te.IDLE,this.setInterval(zu),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragContextChanged(i)||(Et(i)&&(this.fragPrevious=i),this.state=te.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=i.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,r,ge.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===ge.SUBTITLE&&(t.details===z.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==te.STOPPED&&(this.state=te.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&fu(this.levels,t)){this.levels=t.map(i=>new zn(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new zn(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ge.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==te.STOPPED&&this.setInterval(zu)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Ar(a,u),c=a.fragmentStart):d&&(c=d.start,Ja(a,c));else{var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&d&&(c=d.start,Ja(a,c))}u&&!this.startFragRequested&&this.setStartPosition(u,c)}l.details=a,this.levelLastLoaded=l,o===n&&(this.hls.trigger(x.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===te.IDLE&&(pn(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Xn(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Wa(n.method)).catch(o=>{throw r.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(x.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=te.IDLE})}}doTick(){if(!this.media){this.state=te.IDLE;return}if(this.state===te.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),a=Fe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:o,len:l}=a,c=i.details,h=this.hls.maxBufferLength+c.levelTargetDuration;if(l>h)return;const u=c.fragments,d=u.length,f=c.edge;let p=null;const v=this.fragPrevious;if(o<f){const E=n.maxFragLookUpTolerance,_=o>f-E?0:E;p=pn(v,u,Math.max(u[0].start,o),_),!p&&v&&v.start<u[0].start&&(p=u[0])}else p=u[d-1];if(p=this.filterReplacedPrimary(p,i.details),!p)return;const m=p.sn-c.startSN,g=u[m-1];if(g&&g.cc===p.cc&&this.fragmentTracker.getState(g)===bt.NOT_LOADED&&(p=g),this.fragmentTracker.getState(p)===bt.NOT_LOADED){const E=this.mapToInitFragWhenRequired(p);E&&this.loadFragment(E,i,o)}}}loadFragment(e,t,i){Et(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new zE(this.tracksBuffered[this.currentTrackId]||[])}}class zE{constructor(e){this.buffered=void 0;const t=(i,n,r)=>{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const WE={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},Ku=s=>String.fromCharCode(WE[s]||s),_i=15,Hi=100,KE={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},XE={17:2,18:4,21:6,22:8,23:10,19:13,20:15},YE={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},qE={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jE=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class QE{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;tt.log(`${this.time} [${e}] ${i}`)}}}const vn=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Xu{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const n=t[i];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ZE{constructor(){this.uchar=" ",this.penState=new Xu}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 JE{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Xu,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Hi;t++)this.chars.push(new ZE);this.logger=e}equals(e){for(let t=0;t<Hi;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Hi;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Hi;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>Hi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Hi)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ku(e);if(this.pos>=Hi){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<Hi;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Hi;i++){const n=this.chars[i].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class bo{constructor(e){this.rows=[],this.currRow=_i-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<_i;t++)this.rows.push(new JE(e));this.logger=e}reset(){for(let e=0;e<_i;e++)this.rows[e].clear();this.currRow=_i-1}equals(e){let t=!0;for(let i=0;i<_i;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<_i;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<_i;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 = "+lt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<_i;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[a].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 = "+lt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let r=0;r<_i;r++){const a=this.rows[r].getTextString();a&&(n=r+1,e?t.push("Row "+n+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
3715
3715
|
`)),i}getTextAndFormat(){return this.rows}}class Yu{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new bo(i),this.nonDisplayedMemory=new bo(i),this.lastOutputScreen=new bo(i),this.currRollUpRow=this.displayedMemory.rows[_i-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[_i-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+lt(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 qu{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=tx(),this.logger=void 0;const n=this.logger=new QE;this.channels=[null,new Yu(e,t,n),new Yu(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const n=t[i]&127,r=t[i+1]&127;let a=!1,o=null;if(n===0&&r===0)continue;this.logger.log(3,()=>"["+vn([t[i],t[i+1]])+"] -> ("+vn([n,r])+")");const l=this.cmdHistory;if(n>=16&&n<=31){if(ex(n,r,l)){Vr(null,null,l),this.logger.log(3,()=>"Repeated command ("+vn([n,r])+") is dropped");continue}Vr(n,r,this.cmdHistory),a=this.parseCmd(n,r),a||(a=this.parseMidrow(n,r)),a||(a=this.parsePAC(n,r)),a||(a=this.parseBackgroundAttributes(n,r))}else Vr(null,null,l);if(!a&&(o=this.parseChars(n,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+vn([n,r])+" orig: "+vn([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const r=e===20||e===21||e===23?1:2,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+vn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(n||r))return!1;const a=e<=23?1:2;t>=64&&t<=95?i=a===1?KE[e]:YE[e]:i=a===1?XE[e]:qE[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Ku(a)+"' in channel "+i),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+vn(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=jE[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Vr(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Vr(s,e,t){t.a=s,t.b=e}function ex(s,e,t){return t.a===s&&t.b===e}function tx(){return{a:null,b:null}}var Ro=function(){if(yr!=null&&yr.VTTCue)return self.VTTCue;const s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(s,o)}function n(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,p=o,v=l,m=c,g=null,E="",_=!0,T="auto",b="start",R=50,A="middle",C=50,S="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(y){d=""+y}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(y){f=!!y}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return p},set:function(y){if(typeof y!="number")throw new TypeError("Start time must be set to a number.");p=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return v},set:function(y){if(typeof y!="number")throw new TypeError("End time must be set to a number.");v=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return m},set:function(y){m=""+y,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return g},set:function(y){g=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return E},set:function(y){const w=i(y);if(w===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return _},set:function(y){_=!!y,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return T},set:function(y){if(typeof y!="number"&&y!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return b},set:function(y){const w=n(y);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");b=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return R},set:function(y){if(y<0||y>100)throw new Error("Position must be between 0 and 100.");R=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(y){const w=n(y);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");A=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return C},set:function(y){if(y<0||y>100)throw new Error("Size must be between 0 and 100.");C=y,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return S},set:function(y){const w=n(y);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");S=w,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class ix{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ju(s){function e(i,n,r,a){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(a||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class nx{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n<i.length;++n)if(t===i[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Qu(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const a=n[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Mo=new Ro(0,0,""),Hr=Mo.align==="middle"?"middle":"center";function sx(s,e,t){const i=s;function n(){const o=ju(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new nx;Qu(o,function(d,f){let p;switch(d){case"region":for(let v=t.length-1;v>=0;v--)if(t[v].id===f){c.set(d,t[v].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":p=f.split(","),c.integer(d,p[0]),c.percent(d,p[0])&&c.set("snapToLines",!1),c.alt(d,p[0],["auto"]),p.length===2&&c.alt("lineAlign",p[1],["start",Hr,"end"]);break;case"position":p=f.split(","),c.percent(d,p[0]),p.length===2&&c.alt("positionAlign",p[1],["start",Hr,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",Hr,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&Mo.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Hr);let u=c.get("position","auto");u==="auto"&&Mo.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=n(),a(),r(s,e)}function Zu(s){return s.replace(/<br(?: \/)?>/gi,`
|
|
3716
3716
|
`)}class rx{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ix,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,a=0;for(r=Zu(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
3717
3717
|
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
@@ -3722,5 +3722,5 @@ Schedule: ${l.map(v=>vi(v))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
3722
3722
|
`).split(`
|
|
3723
3723
|
`),c=[],h=e?R_(e.baseTime,e.timescale):0;let u="00:00.000",d=0,f=0,p,v=!0;o.oncue=function(m){const g=t[i];let E=t.ccOffset;const _=(d-h)/9e4;if(g!=null&&g.new&&(f!==void 0?E=t.ccOffset=g.start:lx(t,i,_)),_){if(!e){p=new Error("Missing initPTS for VTT MPEGTS");return}E=_-t.presentationOffset}const T=m.endTime-m.startTime,b=ii((m.startTime+E-f)*9e4,n*9e4)/9e4;m.startTime=Math.max(b,0),m.endTime=Math.max(b+T,0);const R=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(R)),m.id||(m.id=Io(m.startTime,m.endTime,R)),m.endTime>0&&c.push(m)},o.onparsingerror=function(m){p=m},o.onflush=function(){if(p){a(p);return}r(c)},l.forEach(m=>{if(v)if(Lo(m,"X-TIMESTAMP-MAP=")){v=!1,m.slice(16).split(",").forEach(g=>{Lo(g,"LOCAL:")?u=g.slice(6):Lo(g,"MPEGTS:")&&(d=parseInt(g.slice(7)))});try{f=ox(u)/1e3}catch(g){p=g}return}else m===""&&(v=!1);o.parse(m+`
|
|
3724
3724
|
`)}),o.flush()}const Co="stpp.ttml.im1t",Ju=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ed=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,hx={left:"start",center:"center",right:"end",start:"start",end:"end"};function td(s,e,t,i){const n=We(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(o=>ti(o)),a=b_(e.baseTime,1,e.timescale);try{r.forEach(o=>t(ux(o,a)))}catch(o){i(o)}}function ux(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=n.getAttribute(`ttp:${d}`)||r[d],u),{}),o=n.getAttribute("xml:space")!=="preserve",l=id(wo(n,"styling","style")),c=id(wo(n,"layout","region")),h=wo(n,"body","[begin]");return[].map.call(h,u=>{const d=nd(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=Po(u.getAttribute("begin"),a),p=Po(u.getAttribute("dur"),a);let v=Po(u.getAttribute("end"),a);if(f===null)throw sd(u);if(v===null){if(p===null)throw sd(u);v=f+p}const m=new Ro(f-e,v-e,d);m.id=Io(m.startTime,m.endTime,m.text);const g=c[u.getAttribute("region")],E=l[u.getAttribute("style")],_=dx(g,E,l),{textAlign:T}=_;if(T){const b=hx[T];b&&(m.lineAlign=b),m.align=T}return at(m,_),m}).filter(u=>u!==null)}function wo(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function id(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function nd(s,e){return[].slice.call(s.childNodes).reduce((t,i,n)=>{var r;return i.nodeName==="br"&&n?t+`
|
|
3725
|
-
`:(r=i.childNodes)!=null&&r.length?nd(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function dx(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((o,l)=>{const c=Do(e,i,l)||Do(s,i,l)||Do(n,i,l);return c&&(o[l]=c),o},{})}function Do(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function sd(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Po(s,e){if(!s)return null;let t=ju(s);return t===null&&(Ju.test(s)?t=fx(s,e):ed.test(s)&&(t=px(s,e))),t}function fx(s,e){const t=Ju.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function px(s,e){const t=ed.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class $r{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class rd{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=ld(),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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(x.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(x.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new $r(this,"textTrack1"),t=new $r(this,"textTrack2"),i=new $r(this,"textTrack3"),n=new $r(this,"textTrack4");this.cea608Parser1=new qu(1,e,t),this.cea608Parser2=new qu(3,i,n)}addCues(e,t,i,n,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=mx(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,n)}else{const o=this.Cues.newCue(null,t,i,n);this.hls.trigger(x.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){const{unparsedVttFrags:o}=this;i===ge.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(x.FRAG_LOADED,l):this.hls.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n<i.textTracks.length;n++){const r=i.textTracks[n];if(od(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:n}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)i[e]=o,Zn(i[e]),ku(i[e],n);else{const l=this.createTextTrack("captions",r,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,n={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,i){const n=this.media;if(n)return n.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:n}=this;Object.keys(n).forEach(r=>{Zn(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ld(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Zn(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],n=i.some(r=>r.textCodec===Co);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(fu(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Br(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&od(o[d],l)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)Zn(h);else{const u=ad(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ge.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===ge.SUBTITLE)if(n.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Co?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;td(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?ci(i.initSegment.data,new Uint8Array(n)).buffer:n;cx(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,h=>{this._appendCues(h,i.level),l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(i,n),l.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>i.cc)&&l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:h})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||td(t,this.initPTS[e.cc],()=>{i.textCodec=Co,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>Bu(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(x.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===ge.SUBTITLE&&this.onFragLoaded(x.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=t;if(!(i.type===ge.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;r<n.length;r++){const a=n[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(n[r].pts,o[0]),this.cea608Parser2.addData(n[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:n,type:r}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r<i;r++){const a=e[n++],o=127&e[n++],l=127&e[n++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function ad(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function od(s,e){return!!s&&s.kind===ad(e)&&mo(e,s)}function mx(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function ld(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const gx=/\s/,cd={newCue(s,e,t,i){const n=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(r=i.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let v=0;v<r.chars.length;v++)gx.test(r.chars[v].uchar)&&o?l++:(c+=r.chars[v].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Zu(c.trim()),p=Io(e,t,f);s!=null&&(u=s.cues)!=null&&u.getCueById(p)||(a=new h(e,t,f),a.id=p,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),n.forEach(d=>Bu(s,d))),n}};function hd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const vx=/(\d+)-(\d+)\/(\d+)/;class Fo{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||Sx,this.controller=new self.AbortController,this.stats=new ar}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=_x(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=l&&de(l)?l:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(ys(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const f=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},c-(f-n.loading.start)),!u.ok){const{status:v,statusText:m}=u;throw new yx(m||"fetch, bad network response",v,u)}n.loading.first=f,n.total=xx(u.headers)||n.total;const p=(d=this.callbacks)==null?void 0:d.onProgress;return p&&de(t.highWaterMark)?this.loadProgressively(u,n,e,t.highWaterMark,p):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,f;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const v=u[o];v&&(n.loaded=n.total=v);const m={url:p.url,data:u,code:p.status},g=(d=this.callbacks)==null?void 0:d.onProgress;g&&!de(t.highWaterMark)&&g(n,e,u,p),(f=this.callbacks)==null||f.onSuccess(m,n,e,p)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const f=u&&u.code||0,p=u?u.message:null;(d=this.callbacks)==null||d.onError({code:f,text:p},e,u?u.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const a=new kh,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<n||a.dataLength?(a.push(h),a.dataLength>=n&&r(t,i,a.flush().buffer,e)):r(t,i,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function _x(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(at({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function Ex(s){const e=vx.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function xx(s){const e=s.get("Content-Range");if(e){const i=Ex(e);if(de(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function Sx(s,e){return new self.Request(s.url,e)}class yx extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Tx=/^age:\s*[\d.]+\s*$/im;class Oo{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 ar,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,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(n)for(const o in n)e.setRequestHeader(o,n[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&de(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const p=h??t.response;if(p!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const v=t.responseType==="arraybuffer"?p.byteLength:p.length;i.loaded=i.total=v,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(i,e,p,t);const g={url:t.responseURL,data:p,code:c};(o=this.callbacks)==null||o.onSuccess(g,i,e,t);return}}const u=r.loadPolicy.errorRetry,d=i.retry,f={url:e.url,data:void 0,code:c};if(vr(u,d,!1,f))this.retry(u);else{var l;tt.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(vr(e,t,!0))this.retry(e);else{var i;tt.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ga(e,i.retry),i.retry++,tt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Tx.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 Ax={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},bx=et(et({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Oo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:zc,bufferController:vu,capLevelController:Fr,errorController:Zc,fpsController:Nu,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:qa,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Ax},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},Rx()),{},{subtitleStreamController:Wu,subtitleTrackController:Gu,timelineController:rd,audioStreamController:du,audioTrackController:pu,emeController:gn,cmcdController:Du,contentSteeringController:Pu,interstitialsController:$E});function Rx(){return{cueHandler:cd,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 Mx(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Uo(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&l){c.push(u);const f=i[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${lt(e[o])}`)}),et(et({},i),e)}function Uo(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Uo):Object.keys(s).reduce((e,t)=>(e[t]=Uo(s[t]),e),{}):s}function Lx(s,e){const t=s.loader;t!==Fo&&t!==Oo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):hd()&&(s.loader=Fo,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const zr=2,Ix=.1,Cx=.05,wx=100;class Dx extends nh{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.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(wx),this.mediaSource=t.mediaSource;const i=this.media=t.media;Ht(i,"playing",this.onMediaPlaying),Ht(i,"waiting",this.onMediaWaiting),Ht(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(qt(i,"playing",this.onMediaPlaying),qt(i,"waiting",this.onMediaWaiting),qt(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!1}));return}if(!Fe.getBuffered(a).length){this.nudgeRetry=0;return}const u=Fe.bufferInfo(a,e,0),d=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const R=ud(this.hls.inFlightFragments,e),A=u.len>zr,C=!d||R||d-e>zr&&!f.getPartialFragment(e);if(A||C)return;this.moved=!1}const p=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,S=!!(p!=null&&p.live)?p.targetduration*2:zr,y=Wr(e,f);if(A>0&&(A<=S||y)){a.paused||this._trySkipBufferHole(y);return}}const v=r.detectStallWithCurrentTimeMs,m=self.performance.now(),g=this.waiting;let E=this.stalled;if(E===null)if(g>0&&m-g<v)E=this.stalled=g;else{this.stalled=m;return}const _=m-E;if(!o&&(_>=v||g)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-((p==null?void 0:p.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const b=Fe.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(b,_,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(x.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&n&&n.length>1&&e>n.end(0)){const r=Fe.bufferedInfo(Fe.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=Fe.timeRangesToArray(n),o=Fe.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=Fe.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Wr(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=Fe.bufferInfo(this.media,e,0);this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:a,media:o}=this,l=(n=this.hls)==null?void 0:n.config;if(!o||!a||!l)return;const c=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Wr(i,a);if((h||c!=null&&c.live&&i<c.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,ge.MAIN),a=i.getFragAtPos(n,ge.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${lt(e)})`);this.warn(a.message),t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const a=n.currentTime,o=Fe.bufferInfo(n,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&n.readyState<3,d=l-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let p=!1;if(a===0){const v=i.getAppendedFrag(0,ge.MAIN);v&&l<v.end&&(p=!0)}if(!p&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||ud(this.hls.inFlightFragments,l))return 0;let m=!1,g=e.end;for(;g<l;){const E=Wr(g,i);if(E)g+=E.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(l+Cx,a+Ix);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,n.currentTime=f,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),v={type:Ee.MEDIA_ERROR,details:H.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?v.part=e:v.frag=e),this.hls.trigger(x.ERROR,v)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:n}=this,r=t==null?void 0:t.config;if(!i||!r)return 0;const a=i.currentTime;if(this.nudgeRetry++,n<r.nudgeMaxRetry){const o=a+(n+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function ud(s,e){const t=dd(s.main);if(t&&t.start<=e)return t;const i=dd(s.audio);return i&&i.start<=e?i:null}function dd(s){if(!s)return null;switch(s.state){case te.IDLE:case te.STOPPED:case te.ENDED:case te.ERROR:return null}return s.frag}function Wr(s,e){return e.getAppendedFrag(s,ge.MAIN)||e.getPartialFragment(s)}const Px=.25;function No(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ko(s,e,t,i,n){let r=new s(e,t,"");try{r.value=i,n&&(r.type=n)}catch{r=new s(e,t,lt(n?et({type:n},i):i))}return r}const Kr=(()=>{const s=No();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Fx{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(x.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&&(e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zn(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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return ku(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:n}=this.hls.config;if(!i&&!n)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=No();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===jt.emsg&&!i||!n)continue;const c=Kh(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Kr&&(u=Kr),u-h<=0&&(u=h+Px);for(let f=0;f<c.length;f++){const p=c[f];if(!Xh(p)){this.updateId3CueEnds(h,l);const v=ko(a,h,u,p,l);v&&this.id3Track.addCue(v)}}}}updateId3CueEnds(e,t){var i;const n=(i=this.id3Track)==null?void 0:i.cues;if(n)for(let r=n.length;r--;){const a=n[r];a.type===t&&a.startTime<e&&a.endTime===Kr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:n}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;n==="audio"?c=h=>h.type===jt.audioId3&&l:n==="video"?c=h=>h.type===jt.emsg&&o:c=h=>h.type===jt.audioId3&&l||h.type===jt.emsg&&o,yo(r,t,i,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=No();if(i&&n&&!a){const{fragmentStart:v,fragmentEnd:m}=e;let g=this.assetCue;g?(g.startTime=v,g.endTime=m):o&&(g=this.assetCue=ko(o,v,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),g&&(g.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(g),g.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c);let u=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.cues)!=null&&d.length){const v=Object.keys(u).filter(m=>!h.includes(m));for(let m=v.length;m--;){var f;const g=v[m],E=(f=u[g])==null?void 0:f.cues;delete u[g],E&&Object.keys(E).forEach(_=>{const T=E[_];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(T)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(h.length===0||!de(p==null?void 0:p.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let v=0;v<h.length;v++){const m=h[v],g=c[m],E=g.startTime,_=u[m],T=(_==null?void 0:_.cues)||{};let b=(_==null?void 0:_.durationKnown)||!1,R=Kr;const{duration:A,endDate:C}=g;if(C&&A!==null)R=E+A,b=!0;else if(g.endOnNext&&!b){const y=h.reduce((w,U)=>{if(U!==g.id){const X=c[U];if(X.class===g.class&&X.startDate>g.startDate&&(!w||g.startDate<w.startDate))return X}return w},null);y&&(R=y.startTime,b=!0)}const S=Object.keys(g.attr);for(let y=0;y<S.length;y++){const w=S[y];if(!gv(w))continue;const U=T[w];if(U)b&&!(_!=null&&_.durationKnown)?U.endTime=R:Math.abs(U.startTime-E)>.01&&(U.startTime=E,U.endTime=R);else if(o){let X=g.attr[w];vv(w)&&(X=vc(X));const F=ko(o,E,R,{key:w,data:X},jt.dateRange);F&&(F.id=m,this.id3Track.addCue(F),T[w]=F,a&&(w==="X-ASSET-LIST"||w==="X-ASSET-URL")&&F.addEventListener("enter",this.onEventCueEnter))}}u[m]={cues:T,dateRange:g,durationKnown:b}}}}}class Ox{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,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const l=n-o,c=Math.min(this.maxLatency,o+i.targetduration);if(l<c&&l>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){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:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*n);const h=n;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 i=this.levelDetails;if(i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,a=n-i.totalduration,o=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const 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 i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===H.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,n;e.playbackRate!==t&&((i=this.hls)==null||i.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 Ux extends Pr{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.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 i=this.hls.config.preferManagedMediaSource,n=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:f}=h;d&&(h.audioCodec=d=dr(d,i)||void 0),f&&(f=h.videoCodec=O0(f));const{width:p,height:v,unknownCodecs:m}=h,g=(m==null?void 0:m.length)||0;if(o||(o=!!(p&&v)),l||(l=!!f),c||(c=!!d),g||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":_,"HDCP-LEVEL":T,"PATHWAY-ID":b,RESOLUTION:R,"VIDEO-RANGE":A}=u,S=`${`${b||"."}-`}${h.bitrate}-${R}-${_}-${E}-${A}-${T}`;if(r[S])if(r[S].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const y=a[S]+=1;h.attrs["PATHWAY-ID"]=new Array(y+1).join(".");const w=this.createLevel(h);r[S]=w,n.push(w)}else r[S].addGroupId("audio",u.AUDIO),r[S].addGroupId("text",u.SUBTITLES);else{const y=this.createLevel(h);r[S]=y,a[S]=1,n.push(y)}}),this.filterAndSortMediaOptions(n,t,o,l,c)}createLevel(e){const t=new zn(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=Uc(n,[])}return t}isAudioSupported(e){return fs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return fs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var a;let o=[],l=[],c=e;const h=((a=t.stats)==null?void 0:a.parsing)||{};if((i||n)&&r&&(c=c.filter(({videoCodec:E,videoRange:_,width:T,height:b})=>(!!E||!!(T&&b))&&W0(_))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",_=E;t.levels.length&&(_=`one or more CODECS in variant not supported: ${lt(t.levels.map(b=>b.attrs.CODECS).filter((b,R,A)=>A.indexOf(b)===R))}`,this.warn(_),E+=` (${_})`);const T=new Error(E);this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:H.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:_})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),fd(o)),t.subtitles&&(l=t.subtitles,fd(l));const u=c.slice(0);c.sort((E,_)=>{if(E.attrs["HDCP-LEVEL"]!==_.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(_.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&E.height!==_.height)return E.height-_.height;if(E.frameRate!==_.frameRate)return E.frameRate-_.frameRate;if(E.videoRange!==_.videoRange)return pr.indexOf(E.videoRange)-pr.indexOf(_.videoRange);if(E.videoCodec!==_.videoCodec){const T=Dc(E.videoCodec),b=Dc(_.videoCodec);if(T!==b)return b-T}if(E.uri===_.uri&&E.codecSet!==_.codecSet){const T=ur(E.codecSet),b=ur(_.codecSet);if(T!==b)return b-T}return E.averageBitrate!==_.averageBitrate?E.averageBitrate-_.averageBitrate:0});let d=u[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==u.length)){for(let E=0;E<u.length;E++)if(u[E].pathwayId===c[0].pathwayId){d=u[E];break}}this._levels=c;for(let E=0;E<c.length;E++)if(c[E]===d){var f;this._firstLevel=E;const _=d.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${_}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const b=Math.min(_,this.hls.config.abrEwmaDefaultEstimateMax);b>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const p=r&&!n,v=this.hls.config,m=!!(v.audioStreamController&&v.audioTrackController),g={levels:c,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:m&&!p&&o.some(E=>!!E.url)};h.end=performance.now(),this.hls.trigger(x.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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&n&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(x.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,n==null?void 0:n.details,c);this.loadPlaylist(h)}}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(),i=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=i}}onError(e,t){t.fatal||!t.context||t.context.type===Ye.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===ge.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))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 i;const{level:n,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${n}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(n,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(x.LEVEL_LOADING,{url:i,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 i=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Dh(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(x.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(x.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function fd(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function pd(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bo(){if(!Ni())return!1;const e=pd();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function md(){if(!Bo())return!1;const s=Ni();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(ps(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(ps(e,"audio"))))}function Nx(){var s;const e=pd();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const kx=100;class Bx extends br{constructor(e,t,i){super(e,t,i,"stream-controller",ge.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,r=n?n.currentTime:null;if(r===null||!de(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(n,r,ge.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(kx),this.level=-1,!this.startFragRequested){let r=n.startLevel;r===-1&&(n.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=n.firstAutoLevel),n.nextLoadLevel=r,this.level=n.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=te.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=te.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case te.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e==null?void 0:e[t],n=i==null?void 0:i.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=te.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=te.IDLE;break}break}case te.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===te.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:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const v={};this.altAudio===2&&(v.type="video"),this.hls.trigger(x.BUFFER_EOS,v),this.state=te.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===te.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=te.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==bt.OK){var p;const m=((p=this.backtrackFragment)!=null?p:f).sn-c.startSN,g=c.fragments[m-1];g&&f.cc===g.cc&&(f=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?ot.AUDIO:ot.VIDEO,g=(m===ot.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,m,ge.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,ge.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d)))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===bt.NOT_LOADED||n===bt.PARTIAL?Et(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ge.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,h=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,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 te.KEY_LOADING:case te.FRAG_LOADING:case te.FRAG_LOADING_WAITING_RETRY:case te.PARSING:case te.PARSED:this.state=te.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 i=t.media;Ht(i,"playing",this.onMediaPlaying),Ht(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(qt(i,"playing",this.onMediaPlaying),qt(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(x.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,n=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,n=n||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&n&&!Nx(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==te.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=te.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:n,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!n){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=t.levelInfo,h=this.fragCurrent;h&&(this.state===te.FRAG_LOADING||this.state===te.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=c.details)!=null&&i.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,r||this.setStartPosition(o,u),this.hls.trigger(x.LEVEL_UPDATED,{details:o,level:a}),this.state===te.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=te.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const n=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(n!==null&&i.duration>n&&(r<n||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const u=Fe.bufferInfo(i,n,0);if(!((c=u.buffered)!=null&&c.length)){i.currentTime=n;return}if(u.start<=r){i.currentTime=n;return}const{nextStart:f}=Fe.bufferedInfo(u.buffered,r,0);f&&(i.currentTime=f)}else i.currentTime=n}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new hu(this.hls,ge.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=n?n.index:-1,v=p!==-1,m=new Er(i.level,i.sn,i.stats.chunkCount,r.byteLength,p,v),g=this.initPTS[i.cc];f.push(r,u,d,c,i,n,l.totalduration,h,m,g)}onAudioTrackSwitching(e,t){const i=this.hls,n=this.altAudio!==0;if(mr(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(x.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(x.AUDIO_TRACK_SWITCHED,t)}),i.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(x.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=mr(t.url,this.hls);if(i){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=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,n=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t,r=i.type===ge.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===te.PARSED&&(this.state=te.IDLE);return}const o=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Et(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const a=this.media;a&&(!this._hasEnoughToStart&&Fe.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case H.FRAG_GAP:case H.FRAG_PARSING_ERROR:case H.FRAG_DECRYPT_ERROR:case H.FRAG_LOAD_ERROR:case H.FRAG_LOAD_TIMEOUT:case H.KEY_LOAD_ERROR:case H.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.MAIN,t);break;case H.LEVEL_LOAD_ERROR:case H.LEVEL_LOAD_TIMEOUT:case H.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Ye.LEVEL&&(this.state=te.IDLE);break;case H.BUFFER_ADD_CODEC_ERROR:case H.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case H.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case H.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=te.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ot.AUDIO||!this.altAudio){const i=(t===ot.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,ge.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 i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&i&&(i+=n);const r=this.getLevelDetails(),a=Fe.getBuffered(e),o=a.length?a.start(0):0,l=o-i,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:n}=this,r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=te.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(x.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=n,{details:p}=c,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=te.PARSING,f){const m=f.tracks;if(m){const T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,m,T,r),i.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:m})}const g=f.initPTS,E=f.timescale,_=this.initPTS[o.cc];if(de(g)&&(!_||_.baseTime!==g||_.timescale!==E)){const T=f.trackId;this.initPTS[o.cc]={baseTime:g,timescale:E,trackId:T},i.trigger(x.INIT_PTS_FOUND,{frag:o,id:t,initPTS:g,timescale:E,trackId:T})}}if(h&&p){v&&h.type==="audiovideo"&&this.logMuxedErr(o);const m=p.fragments[o.sn-1-p.startSN],g=o.sn===p.startSN,E=!m||o.cc>m.cc;if(n.independent!==!1){const{startPTS:_,endPTS:T,startDTS:b,endDTS:R}=h;if(l)l.elementaryStreams[h.type]={startPTS:_,endPTS:T,startDTS:b,endDTS:R};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!E&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),C=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,S=h.firstKeyFramePTS?h.firstKeyFramePTS:_;if(!g&&C<S-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,T,o.start,R,!0)}else g&&_-(p.appliedTimelineOffset||0)>zr&&(o.gap=!0);o.setElementaryStreamInfo(h.type,_,T,b,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,g||E)}else if(g||E)o.gap=!0;else{this.backtrack(o);return}}if(v){const{startPTS:m,endPTS:g,startDTS:E,endDTS:_}=v;l&&(l.elementaryStreams[ot.AUDIO]={startPTS:m,endPTS:g,startDTS:E,endDTS:_}),o.setElementaryStreamInfo(ot.AUDIO,m,g,E,_),this.bufferFragmentData(v,o,l,r)}if(p&&d!=null&&d.samples.length){const m={id:t,frag:o,details:p,samples:d.samples};i.trigger(x.FRAG_PARSING_METADATA,m)}if(p&&u){const m={id:t,frag:o,details:p,samples:u.samples};i.trigger(x.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${Et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==te.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:o}=t;if(r){const c=e.audioCodec;let h=fr(r.codec,c);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),c&&c!==h&&this.log(`Swapping manifest audio codec "${c}" for "${h}"`),r.levelCodec=h,r.id=ge.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=ge.MAIN;const c=a.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(x.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const u=t[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger(x.BUFFER_APPENDING,{type:c,data:u,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ge.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=te.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Fe.isBuffered(e,i)?t=this.getAppendedFrag(i):Fe.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r)&&(this.fragPlaying=t,this.hls.trigger(x.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(x.LEVEL_SWITCHED,{level:r}))}}}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 i=this.getLevelDetails(),n=this.currentFrag||(i?pn(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const a=r+(t-n.start)*1e3;return new Date(a)}}}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 Gx extends li{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[i].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.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=H.KEY_LOAD_ERROR,i,n,r){return new ki({type:Ee.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n<r;n++){const a=t[n];if(e.cc<=a.cc&&(!Et(e)||!Et(a)||e.sn<a.sn)||!i&&n==r-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=Tr(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const n=gs(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,H.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,H.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Go(r);let l=this.keyIdToKeyInfo[o];if((i=l)!=null&&i.decryptdata.key)return r.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(n=l)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Ut(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,H.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const a=T0(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Ut(o)}`),Bi.setKeyIdForUri(e.decryptdata.uri,o)):(o=Bi.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Ut(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Et(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{const{frag:m,keyInfo:g}=p,E=Go(g.decryptdata);if(!m.decryptdata||g!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(m,H.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),v));g.decryptdata.key=m.decryptdata.key=new Uint8Array(d.data),m.keyLoader=null,g.loader=null,a({frag:m,keyInfo:g})},onError:(d,f,p,v)=>{this.resetLoader(f),o(this.createKeyLoadError(t,H.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),p,et({url:l.url,data:void 0},d)))},onTimeout:(d,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,H.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(d,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,H.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};r.load(l,h,u)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const a=Go(i.decryptdata)||n;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function Go(s){if(s.keyFormat!==Ct.FAIRPLAY){const e=s.keyId;if(e)return Ut(e)}return s.uri}function gd(s){const{type:e}=s;switch(e){case Ye.AUDIO_TRACK:return ge.AUDIO;case Ye.SUBTITLE_TRACK:return ge.SUBTITLE;default:return ge.MAIN}}function Vo(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Vx{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ye.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:Ye.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ye.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ye.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[Ye.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[Ye.LEVEL])}}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const c=this.hls.logger,h=n.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===Ye.MANIFEST?r=i.manifestLoadPolicy.default:r=at({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),de((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===Ye.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===Ye.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===Ye.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=at({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const p=c.data;h.parsing.start=performance.now(),gi.isMediaPlaylist(p)||u.type!==Ye.MANIFEST?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};n.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,a=e.data,o=Vo(e,i),l=gi.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,n,t);return}const{contentSteering:c,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p}=l;this.variableList=p,h.forEach(E=>{const{unknownCodecs:_}=E;if(_){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:b,videoCodec:R}=E;for(let A=_.length;A--;){const C=_[A];fs(C,"audio",T)?(E.audioCodec=b=b?`${b},${C}`:C,$n.audio[b.substring(0,4)]=2,_.splice(A,1)):fs(C,"video",T)&&(E.videoCodec=R=R?`${R},${C}`:C,$n.video[R.substring(0,4)]=2,_.splice(A,1))}}});const{AUDIO:v=[],SUBTITLES:m,"CLOSED-CAPTIONS":g}=gi.parseMasterPlaylistMedia(a,o,l);v.length&&!v.some(_=>!_.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ft({}),bitrate:0,url:""})),r.trigger(x.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:m,captions:g,contentSteering:c,url:o,stats:t,networkDetails:n,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:o,level:l,type:c}=i,h=Vo(e,i),u=de(l)?l:de(o)?o:0,d=gd(i),f=gi.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(c===Ye.MANIFEST){const p={attrs:new ft({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+Lh(f,0),a.trigger(x.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:h,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:H.MANIFEST_PARSING_ERROR,fatal:t.type===Ye.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Ye.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ye.AUDIO_TRACK||e.type===Ye.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=H.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case Ye.MANIFEST:l=i?H.MANIFEST_LOAD_TIMEOUT:H.MANIFEST_LOAD_ERROR,c=!0;break;case Ye.LEVEL:l=i?H.LEVEL_LOAD_TIMEOUT:H.LEVEL_LOAD_ERROR,c=!1;break;case Ye.AUDIO_TRACK:l=i?H.AUDIO_TRACK_LOAD_TIMEOUT:H.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Ye.SUBTITLE_TRACK:l=i?H.SUBTITLE_TRACK_LOAD_TIMEOUT:H.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:Ee.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(n){const d=(t==null?void 0:t.url)||e.url;u.response=et({url:d,data:void 0},n)}this.hls.trigger(x.ERROR,u)}handlePlaylistLoaded(e,t,i,n,r,a){const o=this.hls,{type:l,level:c,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=n,p=Vo(t,n),v=gd(n);let m=typeof n.level=="number"&&v===ge.MAIN?c:void 0;const g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:H.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:n,level:m,parent:v,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:H.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:E,reason:E.message,response:t,context:n,level:m,parent:v,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Ye.MANIFEST:case Ye.LEVEL:if(m){if(!h)m=0;else if(h!==o.levels[m]){const E=o.levels.indexOf(h);E>-1&&(m=E)}}o.trigger(x.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:m||0,id:u||0,stats:i,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===Ye.MANIFEST});break;case Ye.AUDIO_TRACK:o.trigger(x.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:f});break;case Ye.SUBTITLE_TRACK:o.trigger(x.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:f});break}}}class $i{static get version(){return _s}static isMSESupported(){return Bo()}static isSupported(){return md()}static getMediaSource(){return Ni()}static get Events(){return x}static get MetadataSchema(){return jt}static get ErrorTypes(){return Ee}static get ErrorDetails(){return H}static get DefaultConfig(){return $i.defaultConfig?$i.defaultConfig:bx}static set DefaultConfig(e){$i.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 to,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=d0(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=Mx($i.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Lx(i,t);const{abrController:n,bufferController:r,capLevelController:a,errorController:o,fpsController:l}=i,c=new o(this),h=this.abrController=new n(this),u=new sv(this),d=i.interstitialsController,f=d?this.interstitialsController=new d(this,$i):null,p=this.bufferController=new r(this,u),v=this.capLevelController=new a(this),m=new l(this),g=new Vx(this),E=i.contentSteeringController,_=E?new E(this):null,T=this.levelController=new Ux(this,_),b=new Fx(this),R=new Gx(this.config,this.logger),A=this.streamController=new Bx(this,u,R),C=this.gapController=new Dx(this,u);v.setStreamController(A),m.setStreamController(A);const S=[g,T,A];f&&S.splice(1,0,f),_&&S.splice(1,0,_),this.networkControllers=S;const y=[h,p,C,v,m,b,u];this.audioTrackController=this.createController(i.audioTrackController,S);const w=i.audioStreamController;w&&S.push(this.audioStreamController=new w(this,u,R)),this.subtitleTrackController=this.createController(i.subtitleTrackController,S);const U=i.subtitleStreamController;U&&S.push(this.subtititleStreamController=new U(this,u,R)),this.createController(i.timelineController,y),R.emeController=this.emeController=this.createController(i.emeController,y),this.cmcdController=this.createController(i.cmcdController,y),this.latencyController=this.createController(Ox,y),this.coreComponents=y,S.push(c);const X=c.onErrorOut;typeof X=="function"&&this.on(x.ERROR,X,c),this.on(x.MANIFEST_LOADED,g.onManifestLoaded,g)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const n=e===x.ERROR;this.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(x.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 r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:H.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,n=t?e:{media:i};this._media=i,this.trigger(x.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(x.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(x.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Ca.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(x.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ge.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ge.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ge.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=UE()),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){z0(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 i=e.length;for(let n=0;n<i;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return n}get 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 i=Vc(t);return Nc(e,i,navigator.mediaCapabilities)}}$i.defaultConfig=void 0;const Hx=Object.freeze(Object.defineProperty({__proto__:null,AbrController:zc,AttrList:ft,AudioStreamController:du,AudioTrackController:pu,BasePlaylistController:Pr,BaseSegment:wa,BaseStreamController:br,BufferController:vu,CMCDController:Du,CapLevelController:Fr,ChunkMetadata:Er,ContentSteeringController:Pu,Cues:cd,DateRange:za,EMEController:gn,ErrorActionFlags:Yt,ErrorController:Zc,ErrorDetails:H,ErrorTypes:Ee,Events:x,FPSController:Nu,FetchLoader:Fo,Fragment:or,Hls:$i,HlsSkip:ms,HlsUrlParameters:Ba,KeySystemFormats:Ct,KeySystems:pt,Level:zn,LevelDetails:ch,LevelKey:Bi,LoadStats:ar,M3U8Parser:gi,MetadataSchema:jt,NetworkErrorAction:It,Part:Ec,PlaylistLevelType:ge,SubtitleStreamController:Wu,SubtitleTrackController:Gu,TimelineController:rd,XhrLoader:Oo,default:$i,fetchSupported:hd,getMediaSource:Ni,isMSESupported:Bo,isSupported:md,requestMediaKeySystemAccess:qa},Symbol.toStringTag,{value:"Module"}));return Gt.LookControls=nc,Gt.MODES=Ui,Gt.PROJECTIONS=Zl,Gt.Player=uc,Gt.StereoScene=ec,Gt.ThreeVideoElement=dc,Gt.VideoSource=sc,Gt.buildProxyUrl=ac,Gt.clampAngles=ic,Gt.detectFormat=rc,Gt.detectProjection=Jl,Gt.isFlatMode=t0,Gt.registerWebComponent=fc,Object.defineProperty(Gt,Symbol.toStringTag,{value:"Module"}),Gt}({});
|
|
3725
|
+
`:(r=i.childNodes)!=null&&r.length?nd(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function dx(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((o,l)=>{const c=Do(e,i,l)||Do(s,i,l)||Do(n,i,l);return c&&(o[l]=c),o},{})}function Do(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function sd(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Po(s,e){if(!s)return null;let t=ju(s);return t===null&&(Ju.test(s)?t=fx(s,e):ed.test(s)&&(t=px(s,e))),t}function fx(s,e){const t=Ju.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function px(s,e){const t=ed.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class $r{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class rd{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=ld(),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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(x.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(x.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new $r(this,"textTrack1"),t=new $r(this,"textTrack2"),i=new $r(this,"textTrack3"),n=new $r(this,"textTrack4");this.cea608Parser1=new qu(1,e,t),this.cea608Parser2=new qu(3,i,n)}addCues(e,t,i,n,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=mx(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,n)}else{const o=this.Cues.newCue(null,t,i,n);this.hls.trigger(x.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){const{unparsedVttFrags:o}=this;i===ge.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(x.FRAG_LOADED,l):this.hls.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n<i.textTracks.length;n++){const r=i.textTracks[n];if(od(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:n}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)i[e]=o,Zn(i[e]),ku(i[e],n);else{const l=this.createTextTrack("captions",r,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,n={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,i){const n=this.media;if(n)return n.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:n}=this;Object.keys(n).forEach(r=>{Zn(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ld(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Zn(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],n=i.some(r=>r.textCodec===Co);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(fu(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Br(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&od(o[d],l)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)Zn(h);else{const u=ad(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ge.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===ge.SUBTITLE)if(n.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Co?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;td(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?ci(i.initSegment.data,new Uint8Array(n)).buffer:n;cx(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,h=>{this._appendCues(h,i.level),l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(i,n),l.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>i.cc)&&l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:h})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||td(t,this.initPTS[e.cc],()=>{i.textCodec=Co,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>Bu(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(x.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===ge.SUBTITLE&&this.onFragLoaded(x.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=t;if(!(i.type===ge.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;r<n.length;r++){const a=n[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(n[r].pts,o[0]),this.cea608Parser2.addData(n[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:n,type:r}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>yo(o[l],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r<i;r++){const a=e[n++],o=127&e[n++],l=127&e[n++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function ad(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function od(s,e){return!!s&&s.kind===ad(e)&&mo(e,s)}function mx(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function ld(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const gx=/\s/,cd={newCue(s,e,t,i){const n=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(r=i.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let v=0;v<r.chars.length;v++)gx.test(r.chars[v].uchar)&&o?l++:(c+=r.chars[v].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Zu(c.trim()),p=Io(e,t,f);s!=null&&(u=s.cues)!=null&&u.getCueById(p)||(a=new h(e,t,f),a.id=p,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),n.forEach(d=>Bu(s,d))),n}};function hd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const vx=/(\d+)-(\d+)\/(\d+)/;class Fo{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||Sx,this.controller=new self.AbortController,this.stats=new ar}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=_x(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=l&&de(l)?l:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(ys(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const f=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},c-(f-n.loading.start)),!u.ok){const{status:v,statusText:m}=u;throw new yx(m||"fetch, bad network response",v,u)}n.loading.first=f,n.total=xx(u.headers)||n.total;const p=(d=this.callbacks)==null?void 0:d.onProgress;return p&&de(t.highWaterMark)?this.loadProgressively(u,n,e,t.highWaterMark,p):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,f;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const v=u[o];v&&(n.loaded=n.total=v);const m={url:p.url,data:u,code:p.status},g=(d=this.callbacks)==null?void 0:d.onProgress;g&&!de(t.highWaterMark)&&g(n,e,u,p),(f=this.callbacks)==null||f.onSuccess(m,n,e,p)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const f=u&&u.code||0,p=u?u.message:null;(d=this.callbacks)==null||d.onError({code:f,text:p},e,u?u.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const a=new kh,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<n||a.dataLength?(a.push(h),a.dataLength>=n&&r(t,i,a.flush().buffer,e)):r(t,i,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function _x(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(at({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function Ex(s){const e=vx.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function xx(s){const e=s.get("Content-Range");if(e){const i=Ex(e);if(de(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function Sx(s,e){return new self.Request(s.url,e)}class yx extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Tx=/^age:\s*[\d.]+\s*$/im;class Oo{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 ar,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,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(n)for(const o in n)e.setRequestHeader(o,n[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&de(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const p=h??t.response;if(p!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const v=t.responseType==="arraybuffer"?p.byteLength:p.length;i.loaded=i.total=v,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(i,e,p,t);const g={url:t.responseURL,data:p,code:c};(o=this.callbacks)==null||o.onSuccess(g,i,e,t);return}}const u=r.loadPolicy.errorRetry,d=i.retry,f={url:e.url,data:void 0,code:c};if(vr(u,d,!1,f))this.retry(u);else{var l;tt.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(vr(e,t,!0))this.retry(e);else{var i;tt.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ga(e,i.retry),i.retry++,tt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Tx.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 Ax={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},bx=et(et({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Oo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:zc,bufferController:vu,capLevelController:Fr,errorController:Zc,fpsController:Nu,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:qa,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Ax},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},Rx()),{},{subtitleStreamController:Wu,subtitleTrackController:Gu,timelineController:rd,audioStreamController:du,audioTrackController:pu,emeController:gn,cmcdController:Du,contentSteeringController:Pu,interstitialsController:$E});function Rx(){return{cueHandler:cd,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 Mx(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Uo(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&l){c.push(u);const f=i[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${lt(e[o])}`)}),et(et({},i),e)}function Uo(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Uo):Object.keys(s).reduce((e,t)=>(e[t]=Uo(s[t]),e),{}):s}function Lx(s,e){const t=s.loader;t!==Fo&&t!==Oo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):hd()&&(s.loader=Fo,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const zr=2,Ix=.1,Cx=.05,wx=100;class Dx extends nh{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.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(wx),this.mediaSource=t.mediaSource;const i=this.media=t.media;Ht(i,"playing",this.onMediaPlaying),Ht(i,"waiting",this.onMediaWaiting),Ht(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(qt(i,"playing",this.onMediaPlaying),qt(i,"waiting",this.onMediaWaiting),qt(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!1}));return}if(!Fe.getBuffered(a).length){this.nudgeRetry=0;return}const u=Fe.bufferInfo(a,e,0),d=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const R=ud(this.hls.inFlightFragments,e),A=u.len>zr,C=!d||R||d-e>zr&&!f.getPartialFragment(e);if(A||C)return;this.moved=!1}const p=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,S=!!(p!=null&&p.live)?p.targetduration*2:zr,y=Wr(e,f);if(A>0&&(A<=S||y)){a.paused||this._trySkipBufferHole(y);return}}const v=r.detectStallWithCurrentTimeMs,m=self.performance.now(),g=this.waiting;let E=this.stalled;if(E===null)if(g>0&&m-g<v)E=this.stalled=g;else{this.stalled=m;return}const _=m-E;if(!o&&(_>=v||g)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-((p==null?void 0:p.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(x.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const b=Fe.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(b,_,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(x.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&n&&n.length>1&&e>n.end(0)){const r=Fe.bufferedInfo(Fe.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=Fe.timeRangesToArray(n),o=Fe.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=Fe.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Wr(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=Fe.bufferInfo(this.media,e,0);this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:a,media:o}=this,l=(n=this.hls)==null?void 0:n.config;if(!o||!a||!l)return;const c=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Wr(i,a);if((h||c!=null&&c.live&&i<c.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,ge.MAIN),a=i.getFragAtPos(n,ge.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${lt(e)})`);this.warn(a.message),t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const a=n.currentTime,o=Fe.bufferInfo(n,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&n.readyState<3,d=l-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let p=!1;if(a===0){const v=i.getAppendedFrag(0,ge.MAIN);v&&l<v.end&&(p=!0)}if(!p&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||ud(this.hls.inFlightFragments,l))return 0;let m=!1,g=e.end;for(;g<l;){const E=Wr(g,i);if(E)g+=E.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(l+Cx,a+Ix);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,n.currentTime=f,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),v={type:Ee.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?v.part=e:v.frag=e),this.hls.trigger(x.ERROR,v)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:n}=this,r=t==null?void 0:t.config;if(!i||!r)return 0;const a=i.currentTime;if(this.nudgeRetry++,n<r.nudgeMaxRetry){const o=a+(n+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function ud(s,e){const t=dd(s.main);if(t&&t.start<=e)return t;const i=dd(s.audio);return i&&i.start<=e?i:null}function dd(s){if(!s)return null;switch(s.state){case te.IDLE:case te.STOPPED:case te.ENDED:case te.ERROR:return null}return s.frag}function Wr(s,e){return e.getAppendedFrag(s,ge.MAIN)||e.getPartialFragment(s)}const Px=.25;function No(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ko(s,e,t,i,n){let r=new s(e,t,"");try{r.value=i,n&&(r.type=n)}catch{r=new s(e,t,lt(n?et({type:n},i):i))}return r}const Kr=(()=>{const s=No();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Fx{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(x.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&&(e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zn(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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return ku(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:n}=this.hls.config;if(!i&&!n)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=No();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===jt.emsg&&!i||!n)continue;const c=Kh(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Kr&&(u=Kr),u-h<=0&&(u=h+Px);for(let f=0;f<c.length;f++){const p=c[f];if(!Xh(p)){this.updateId3CueEnds(h,l);const v=ko(a,h,u,p,l);v&&this.id3Track.addCue(v)}}}}updateId3CueEnds(e,t){var i;const n=(i=this.id3Track)==null?void 0:i.cues;if(n)for(let r=n.length;r--;){const a=n[r];a.type===t&&a.startTime<e&&a.endTime===Kr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:n}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;n==="audio"?c=h=>h.type===jt.audioId3&&l:n==="video"?c=h=>h.type===jt.emsg&&o:c=h=>h.type===jt.audioId3&&l||h.type===jt.emsg&&o,yo(r,t,i,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=No();if(i&&n&&!a){const{fragmentStart:v,fragmentEnd:m}=e;let g=this.assetCue;g?(g.startTime=v,g.endTime=m):o&&(g=this.assetCue=ko(o,v,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),g&&(g.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(g),g.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c);let u=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.cues)!=null&&d.length){const v=Object.keys(u).filter(m=>!h.includes(m));for(let m=v.length;m--;){var f;const g=v[m],E=(f=u[g])==null?void 0:f.cues;delete u[g],E&&Object.keys(E).forEach(_=>{const T=E[_];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(T)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(h.length===0||!de(p==null?void 0:p.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let v=0;v<h.length;v++){const m=h[v],g=c[m],E=g.startTime,_=u[m],T=(_==null?void 0:_.cues)||{};let b=(_==null?void 0:_.durationKnown)||!1,R=Kr;const{duration:A,endDate:C}=g;if(C&&A!==null)R=E+A,b=!0;else if(g.endOnNext&&!b){const y=h.reduce((w,N)=>{if(N!==g.id){const Y=c[N];if(Y.class===g.class&&Y.startDate>g.startDate&&(!w||g.startDate<w.startDate))return Y}return w},null);y&&(R=y.startTime,b=!0)}const S=Object.keys(g.attr);for(let y=0;y<S.length;y++){const w=S[y];if(!gv(w))continue;const N=T[w];if(N)b&&!(_!=null&&_.durationKnown)?N.endTime=R:Math.abs(N.startTime-E)>.01&&(N.startTime=E,N.endTime=R);else if(o){let Y=g.attr[w];vv(w)&&(Y=vc(Y));const F=ko(o,E,R,{key:w,data:Y},jt.dateRange);F&&(F.id=m,this.id3Track.addCue(F),T[w]=F,a&&(w==="X-ASSET-LIST"||w==="X-ASSET-URL")&&F.addEventListener("enter",this.onEventCueEnter))}}u[m]={cues:T,dateRange:g,durationKnown:b}}}}}class Ox{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,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const l=n-o,c=Math.min(this.maxLatency,o+i.targetduration);if(l<c&&l>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){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:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*n);const h=n;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 i=this.levelDetails;if(i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,a=n-i.totalduration,o=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const 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 i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,n;e.playbackRate!==t&&((i=this.hls)==null||i.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 Ux extends Pr{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.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 i=this.hls.config.preferManagedMediaSource,n=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:f}=h;d&&(h.audioCodec=d=dr(d,i)||void 0),f&&(f=h.videoCodec=O0(f));const{width:p,height:v,unknownCodecs:m}=h,g=(m==null?void 0:m.length)||0;if(o||(o=!!(p&&v)),l||(l=!!f),c||(c=!!d),g||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":_,"HDCP-LEVEL":T,"PATHWAY-ID":b,RESOLUTION:R,"VIDEO-RANGE":A}=u,S=`${`${b||"."}-`}${h.bitrate}-${R}-${_}-${E}-${A}-${T}`;if(r[S])if(r[S].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const y=a[S]+=1;h.attrs["PATHWAY-ID"]=new Array(y+1).join(".");const w=this.createLevel(h);r[S]=w,n.push(w)}else r[S].addGroupId("audio",u.AUDIO),r[S].addGroupId("text",u.SUBTITLES);else{const y=this.createLevel(h);r[S]=y,a[S]=1,n.push(y)}}),this.filterAndSortMediaOptions(n,t,o,l,c)}createLevel(e){const t=new zn(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=Uc(n,[])}return t}isAudioSupported(e){return fs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return fs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var a;let o=[],l=[],c=e;const h=((a=t.stats)==null?void 0:a.parsing)||{};if((i||n)&&r&&(c=c.filter(({videoCodec:E,videoRange:_,width:T,height:b})=>(!!E||!!(T&&b))&&W0(_))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",_=E;t.levels.length&&(_=`one or more CODECS in variant not supported: ${lt(t.levels.map(b=>b.attrs.CODECS).filter((b,R,A)=>A.indexOf(b)===R))}`,this.warn(_),E+=` (${_})`);const T=new Error(E);this.hls.trigger(x.ERROR,{type:Ee.MEDIA_ERROR,details:z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:_})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),fd(o)),t.subtitles&&(l=t.subtitles,fd(l));const u=c.slice(0);c.sort((E,_)=>{if(E.attrs["HDCP-LEVEL"]!==_.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(_.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&E.height!==_.height)return E.height-_.height;if(E.frameRate!==_.frameRate)return E.frameRate-_.frameRate;if(E.videoRange!==_.videoRange)return pr.indexOf(E.videoRange)-pr.indexOf(_.videoRange);if(E.videoCodec!==_.videoCodec){const T=Dc(E.videoCodec),b=Dc(_.videoCodec);if(T!==b)return b-T}if(E.uri===_.uri&&E.codecSet!==_.codecSet){const T=ur(E.codecSet),b=ur(_.codecSet);if(T!==b)return b-T}return E.averageBitrate!==_.averageBitrate?E.averageBitrate-_.averageBitrate:0});let d=u[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==u.length)){for(let E=0;E<u.length;E++)if(u[E].pathwayId===c[0].pathwayId){d=u[E];break}}this._levels=c;for(let E=0;E<c.length;E++)if(c[E]===d){var f;this._firstLevel=E;const _=d.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${_}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const b=Math.min(_,this.hls.config.abrEwmaDefaultEstimateMax);b>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const p=r&&!n,v=this.hls.config,m=!!(v.audioStreamController&&v.audioTrackController),g={levels:c,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:m&&!p&&o.some(E=>!!E.url)};h.end=performance.now(),this.hls.trigger(x.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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&n&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(x.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,n==null?void 0:n.details,c);this.loadPlaylist(h)}}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(),i=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=i}}onError(e,t){t.fatal||!t.context||t.context.type===Ye.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===ge.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))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 i;const{level:n,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${n}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(n,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(x.LEVEL_LOADING,{url:i,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 i=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Dh(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(x.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(x.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function fd(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function pd(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bo(){if(!Ni())return!1;const e=pd();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function md(){if(!Bo())return!1;const s=Ni();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(ps(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(ps(e,"audio"))))}function Nx(){var s;const e=pd();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const kx=100;class Bx extends br{constructor(e,t,i){super(e,t,i,"stream-controller",ge.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,r=n?n.currentTime:null;if(r===null||!de(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(n,r,ge.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(kx),this.level=-1,!this.startFragRequested){let r=n.startLevel;r===-1&&(n.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=n.firstAutoLevel),n.nextLoadLevel=r,this.level=n.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=te.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=te.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case te.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e==null?void 0:e[t],n=i==null?void 0:i.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=te.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=te.IDLE;break}break}case te.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===te.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:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const v={};this.altAudio===2&&(v.type="video"),this.hls.trigger(x.BUFFER_EOS,v),this.state=te.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===te.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=te.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==bt.OK){var p;const m=((p=this.backtrackFragment)!=null?p:f).sn-c.startSN,g=c.fragments[m-1];g&&f.cc===g.cc&&(f=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?ot.AUDIO:ot.VIDEO,g=(m===ot.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,m,ge.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,ge.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d)))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===bt.NOT_LOADED||n===bt.PARTIAL?Et(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ge.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,h=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,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 te.KEY_LOADING:case te.FRAG_LOADING:case te.FRAG_LOADING_WAITING_RETRY:case te.PARSING:case te.PARSED:this.state=te.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 i=t.media;Ht(i,"playing",this.onMediaPlaying),Ht(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(qt(i,"playing",this.onMediaPlaying),qt(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(x.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,n=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,n=n||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&n&&!Nx(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==te.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=te.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:n,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!n){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=t.levelInfo,h=this.fragCurrent;h&&(this.state===te.FRAG_LOADING||this.state===te.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=c.details)!=null&&i.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,r||this.setStartPosition(o,u),this.hls.trigger(x.LEVEL_UPDATED,{details:o,level:a}),this.state===te.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=te.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const n=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(n!==null&&i.duration>n&&(r<n||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const u=Fe.bufferInfo(i,n,0);if(!((c=u.buffered)!=null&&c.length)){i.currentTime=n;return}if(u.start<=r){i.currentTime=n;return}const{nextStart:f}=Fe.bufferedInfo(u.buffered,r,0);f&&(i.currentTime=f)}else i.currentTime=n}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new hu(this.hls,ge.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=n?n.index:-1,v=p!==-1,m=new Er(i.level,i.sn,i.stats.chunkCount,r.byteLength,p,v),g=this.initPTS[i.cc];f.push(r,u,d,c,i,n,l.totalduration,h,m,g)}onAudioTrackSwitching(e,t){const i=this.hls,n=this.altAudio!==0;if(mr(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(x.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(x.AUDIO_TRACK_SWITCHED,t)}),i.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(x.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=mr(t.url,this.hls);if(i){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=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,n=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t,r=i.type===ge.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===te.PARSED&&(this.state=te.IDLE);return}const o=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Et(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const a=this.media;a&&(!this._hasEnoughToStart&&Fe.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.MAIN,t);break;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Ye.LEVEL&&(this.state=te.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=te.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ot.AUDIO||!this.altAudio){const i=(t===ot.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,ge.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 i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&i&&(i+=n);const r=this.getLevelDetails(),a=Fe.getBuffered(e),o=a.length?a.start(0):0,l=o-i,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:n}=this,r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=te.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(x.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=n,{details:p}=c,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=te.PARSING,f){const m=f.tracks;if(m){const T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,m,T,r),i.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:m})}const g=f.initPTS,E=f.timescale,_=this.initPTS[o.cc];if(de(g)&&(!_||_.baseTime!==g||_.timescale!==E)){const T=f.trackId;this.initPTS[o.cc]={baseTime:g,timescale:E,trackId:T},i.trigger(x.INIT_PTS_FOUND,{frag:o,id:t,initPTS:g,timescale:E,trackId:T})}}if(h&&p){v&&h.type==="audiovideo"&&this.logMuxedErr(o);const m=p.fragments[o.sn-1-p.startSN],g=o.sn===p.startSN,E=!m||o.cc>m.cc;if(n.independent!==!1){const{startPTS:_,endPTS:T,startDTS:b,endDTS:R}=h;if(l)l.elementaryStreams[h.type]={startPTS:_,endPTS:T,startDTS:b,endDTS:R};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!E&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),C=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,S=h.firstKeyFramePTS?h.firstKeyFramePTS:_;if(!g&&C<S-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,T,o.start,R,!0)}else g&&_-(p.appliedTimelineOffset||0)>zr&&(o.gap=!0);o.setElementaryStreamInfo(h.type,_,T,b,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,g||E)}else if(g||E)o.gap=!0;else{this.backtrack(o);return}}if(v){const{startPTS:m,endPTS:g,startDTS:E,endDTS:_}=v;l&&(l.elementaryStreams[ot.AUDIO]={startPTS:m,endPTS:g,startDTS:E,endDTS:_}),o.setElementaryStreamInfo(ot.AUDIO,m,g,E,_),this.bufferFragmentData(v,o,l,r)}if(p&&d!=null&&d.samples.length){const m={id:t,frag:o,details:p,samples:d.samples};i.trigger(x.FRAG_PARSING_METADATA,m)}if(p&&u){const m={id:t,frag:o,details:p,samples:u.samples};i.trigger(x.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${Et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==te.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:o}=t;if(r){const c=e.audioCodec;let h=fr(r.codec,c);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),c&&c!==h&&this.log(`Swapping manifest audio codec "${c}" for "${h}"`),r.levelCodec=h,r.id=ge.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=ge.MAIN;const c=a.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(x.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const u=t[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger(x.BUFFER_APPENDING,{type:c,data:u,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ge.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=te.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Fe.isBuffered(e,i)?t=this.getAppendedFrag(i):Fe.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r)&&(this.fragPlaying=t,this.hls.trigger(x.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(x.LEVEL_SWITCHED,{level:r}))}}}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 i=this.getLevelDetails(),n=this.currentFrag||(i?pn(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const a=r+(t-n.start)*1e3;return new Date(a)}}}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 Gx extends li{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[i].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.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=z.KEY_LOAD_ERROR,i,n,r){return new ki({type:Ee.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n<r;n++){const a=t[n];if(e.cc<=a.cc&&(!Et(e)||!Et(a)||e.sn<a.sn)||!i&&n==r-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=Tr(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const n=gs(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Go(r);let l=this.keyIdToKeyInfo[o];if((i=l)!=null&&i.decryptdata.key)return r.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(n=l)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Ut(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const a=T0(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Ut(o)}`),Bi.setKeyIdForUri(e.decryptdata.uri,o)):(o=Bi.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Ut(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Et(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,p,v)=>{const{frag:m,keyInfo:g}=p,E=Go(g.decryptdata);if(!m.decryptdata||g!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(m,z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),v));g.decryptdata.key=m.decryptdata.key=new Uint8Array(d.data),m.keyLoader=null,g.loader=null,a({frag:m,keyInfo:g})},onError:(d,f,p,v)=>{this.resetLoader(f),o(this.createKeyLoadError(t,z.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),p,et({url:l.url,data:void 0},d)))},onTimeout:(d,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(d,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,z.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};r.load(l,h,u)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const a=Go(i.decryptdata)||n;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function Go(s){if(s.keyFormat!==Ct.FAIRPLAY){const e=s.keyId;if(e)return Ut(e)}return s.uri}function gd(s){const{type:e}=s;switch(e){case Ye.AUDIO_TRACK:return ge.AUDIO;case Ye.SUBTITLE_TRACK:return ge.SUBTITLE;default:return ge.MAIN}}function Vo(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Vx{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ye.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:Ye.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ye.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ye.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[Ye.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[Ye.LEVEL])}}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const c=this.hls.logger,h=n.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===Ye.MANIFEST?r=i.manifestLoadPolicy.default:r=at({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),de((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===Ye.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===Ye.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===Ye.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=at({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const p=c.data;h.parsing.start=performance.now(),gi.isMediaPlaylist(p)||u.type!==Ye.MANIFEST?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};n.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,a=e.data,o=Vo(e,i),l=gi.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,n,t);return}const{contentSteering:c,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p}=l;this.variableList=p,h.forEach(E=>{const{unknownCodecs:_}=E;if(_){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:b,videoCodec:R}=E;for(let A=_.length;A--;){const C=_[A];fs(C,"audio",T)?(E.audioCodec=b=b?`${b},${C}`:C,$n.audio[b.substring(0,4)]=2,_.splice(A,1)):fs(C,"video",T)&&(E.videoCodec=R=R?`${R},${C}`:C,$n.video[R.substring(0,4)]=2,_.splice(A,1))}}});const{AUDIO:v=[],SUBTITLES:m,"CLOSED-CAPTIONS":g}=gi.parseMasterPlaylistMedia(a,o,l);v.length&&!v.some(_=>!_.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ft({}),bitrate:0,url:""})),r.trigger(x.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:m,captions:g,contentSteering:c,url:o,stats:t,networkDetails:n,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:o,level:l,type:c}=i,h=Vo(e,i),u=de(l)?l:de(o)?o:0,d=gd(i),f=gi.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(c===Ye.MANIFEST){const p={attrs:new ft({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+Lh(f,0),a.trigger(x.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:h,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:z.MANIFEST_PARSING_ERROR,fatal:t.type===Ye.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Ye.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ye.AUDIO_TRACK||e.type===Ye.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=z.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case Ye.MANIFEST:l=i?z.MANIFEST_LOAD_TIMEOUT:z.MANIFEST_LOAD_ERROR,c=!0;break;case Ye.LEVEL:l=i?z.LEVEL_LOAD_TIMEOUT:z.LEVEL_LOAD_ERROR,c=!1;break;case Ye.AUDIO_TRACK:l=i?z.AUDIO_TRACK_LOAD_TIMEOUT:z.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Ye.SUBTITLE_TRACK:l=i?z.SUBTITLE_TRACK_LOAD_TIMEOUT:z.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:Ee.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(n){const d=(t==null?void 0:t.url)||e.url;u.response=et({url:d,data:void 0},n)}this.hls.trigger(x.ERROR,u)}handlePlaylistLoaded(e,t,i,n,r,a){const o=this.hls,{type:l,level:c,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=n,p=Vo(t,n),v=gd(n);let m=typeof n.level=="number"&&v===ge.MAIN?c:void 0;const g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:n,level:m,parent:v,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(x.ERROR,{type:Ee.NETWORK_ERROR,details:z.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:E,reason:E.message,response:t,context:n,level:m,parent:v,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Ye.MANIFEST:case Ye.LEVEL:if(m){if(!h)m=0;else if(h!==o.levels[m]){const E=o.levels.indexOf(h);E>-1&&(m=E)}}o.trigger(x.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:m||0,id:u||0,stats:i,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===Ye.MANIFEST});break;case Ye.AUDIO_TRACK:o.trigger(x.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:f});break;case Ye.SUBTITLE_TRACK:o.trigger(x.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:f});break}}}class $i{static get version(){return _s}static isMSESupported(){return Bo()}static isSupported(){return md()}static getMediaSource(){return Ni()}static get Events(){return x}static get MetadataSchema(){return jt}static get ErrorTypes(){return Ee}static get ErrorDetails(){return z}static get DefaultConfig(){return $i.defaultConfig?$i.defaultConfig:bx}static set DefaultConfig(e){$i.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 to,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=d0(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=Mx($i.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Lx(i,t);const{abrController:n,bufferController:r,capLevelController:a,errorController:o,fpsController:l}=i,c=new o(this),h=this.abrController=new n(this),u=new sv(this),d=i.interstitialsController,f=d?this.interstitialsController=new d(this,$i):null,p=this.bufferController=new r(this,u),v=this.capLevelController=new a(this),m=new l(this),g=new Vx(this),E=i.contentSteeringController,_=E?new E(this):null,T=this.levelController=new Ux(this,_),b=new Fx(this),R=new Gx(this.config,this.logger),A=this.streamController=new Bx(this,u,R),C=this.gapController=new Dx(this,u);v.setStreamController(A),m.setStreamController(A);const S=[g,T,A];f&&S.splice(1,0,f),_&&S.splice(1,0,_),this.networkControllers=S;const y=[h,p,C,v,m,b,u];this.audioTrackController=this.createController(i.audioTrackController,S);const w=i.audioStreamController;w&&S.push(this.audioStreamController=new w(this,u,R)),this.subtitleTrackController=this.createController(i.subtitleTrackController,S);const N=i.subtitleStreamController;N&&S.push(this.subtititleStreamController=new N(this,u,R)),this.createController(i.timelineController,y),R.emeController=this.emeController=this.createController(i.emeController,y),this.cmcdController=this.createController(i.cmcdController,y),this.latencyController=this.createController(Ox,y),this.coreComponents=y,S.push(c);const Y=c.onErrorOut;typeof Y=="function"&&this.on(x.ERROR,Y,c),this.on(x.MANIFEST_LOADED,g.onManifestLoaded,g)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const n=e===x.ERROR;this.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(x.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 r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(x.ERROR,{type:Ee.OTHER_ERROR,details:z.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,n=t?e:{media:i};this._media=i,this.trigger(x.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(x.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(x.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Ca.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(x.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ge.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ge.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ge.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=UE()),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){z0(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 i=e.length;for(let n=0;n<i;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return n}get 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 i=Vc(t);return Nc(e,i,navigator.mediaCapabilities)}}$i.defaultConfig=void 0;const Hx=Object.freeze(Object.defineProperty({__proto__:null,AbrController:zc,AttrList:ft,AudioStreamController:du,AudioTrackController:pu,BasePlaylistController:Pr,BaseSegment:wa,BaseStreamController:br,BufferController:vu,CMCDController:Du,CapLevelController:Fr,ChunkMetadata:Er,ContentSteeringController:Pu,Cues:cd,DateRange:za,EMEController:gn,ErrorActionFlags:Yt,ErrorController:Zc,ErrorDetails:z,ErrorTypes:Ee,Events:x,FPSController:Nu,FetchLoader:Fo,Fragment:or,Hls:$i,HlsSkip:ms,HlsUrlParameters:Ba,KeySystemFormats:Ct,KeySystems:pt,Level:zn,LevelDetails:ch,LevelKey:Bi,LoadStats:ar,M3U8Parser:gi,MetadataSchema:jt,NetworkErrorAction:It,Part:Ec,PlaylistLevelType:ge,SubtitleStreamController:Wu,SubtitleTrackController:Gu,TimelineController:rd,XhrLoader:Oo,default:$i,fetchSupported:hd,getMediaSource:Ni,isMSESupported:Bo,isSupported:md,requestMediaKeySystemAccess:qa},Symbol.toStringTag,{value:"Module"}));return Gt.LookControls=nc,Gt.MODES=Ui,Gt.PROJECTIONS=Zl,Gt.Player=uc,Gt.StereoScene=ec,Gt.ThreeVideoElement=dc,Gt.VideoSource=sc,Gt.buildProxyUrl=ac,Gt.clampAngles=ic,Gt.detectFormat=rc,Gt.detectProjection=Jl,Gt.isFlatMode=t0,Gt.registerWebComponent=fc,Object.defineProperty(Gt,Symbol.toStringTag,{value:"Module"}),Gt}({});
|
|
3726
3726
|
//# sourceMappingURL=three-vr-player.standalone.js.map
|