@xmov/avatar 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},_extends.apply(null,arguments)}var EErrorCode;!function(t){t[t.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",t[t.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",t[t.START_SESSION_ERROR=10003]="START_SESSION_ERROR",t[t.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",t[t.INIT_ERROR=10005]="INIT_ERROR",t[t.SOCKET_QUIT=10006]="SOCKET_QUIT",t[t.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",t[t.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",t[t.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",t[t.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",t[t.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",t[t.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",t[t.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",t[t.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",t[t.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",t[t.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",t[t.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",t[t.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",t[t.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",t[t.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",t[t.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",t[t.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",t[t.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",t[t.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",t[t.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",t[t.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",t[t.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",t[t.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",t[t.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",t[t.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",t[t.TTSA_ERROR=40006]="TTSA_ERROR",t[t.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",t[t.NETWORK_DOWN=50001]="NETWORK_DOWN",t[t.NETWORK_UP=50002]="NETWORK_UP",t[t.NETWORK_RETRY=50003]="NETWORK_RETRY",t[t.NETWORK_BREAK=50004]="NETWORK_BREAK",t[t.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",t[t.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",t[t.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",t[t.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",t[t.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",t[t.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",t[t.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",t[t.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(EErrorCode||(EErrorCode={}));const ERROR_CODE_MAP={10001:3101,10002:3102,10003:3103,10004:3104,10005:3105,10006:3106,10007:3107,20001:3201,20002:3202,20003:3203,20004:3204,20005:3205,20006:3206,20007:3207,20008:3208,20009:3209,20010:3210,20011:3211,30001:3301,30002:3302,30003:3303,30004:3304,30005:3305,30006:3306,30007:3307,40001:3401,40002:3402,40003:3403,40004:3404,40005:3405,40006:3406,40007:3407,50001:3501,50002:3502,50003:3503,50004:3504,60001:3601,60002:3602,60003:3603,60004:3604,60005:3605,60006:3606,60007:3607,60008:3608},ERROR_NAME_MAP={10001:"CONTAINER_NOT_FOUND",10002:"CONNECT_SOCKET_ERROR",10003:"START_SESSION_ERROR",10004:"STOP_SESSION_ERROR",10005:"INIT_ERROR",10006:"SOCKET_QUIT",10007:"SOCKET_DISCONNECT",20001:"VIDEO_FRAME_EXTRACT_ERROR",20002:"INIT_WORKER_ERROR",20003:"PROCESS_VIDEO_STREAM_ERROR",20004:"FACE_PROCESSING_ERROR",20005:"RENDER_BODY_ERROR",20006:"RENDER_FACE_ERROR",20007:"WebGL_RENDER_ERROR",20008:"RENDER_DATA_MISSING",20009:"RENDER_FACE_DATA_MISSING",20010:"EVENT_WITHOUT_SPEECH_ID",20011:"EVENT_TRIGGERED",30001:"BACKGROUND_IMAGE_LOAD_ERROR",30002:"FACE_BIN_LOAD_ERROR",30003:"INVALID_BODY_NAME",30004:"VIDEO_DOWNLOAD_ERROR",30005:"BODY_DATA_EXPIRED",30006:"EVENT_SPEAK_START_EXPIRED",30007:"EVENT_VOICE_START_EXPIRED",40001:"AUDIO_DECODE_ERROR",40002:"FACE_DECODE_ERROR",40003:"VIDEO_DECODE_ERROR",40004:"EVENT_DECODE_ERROR",40005:"INVALID_DATA_STRUCTURE",40006:"TTSA_ERROR",40007:"AUDIO_DATA_EXPIRED",50001:"NETWORK_DOWN",50002:"NETWORK_UP",50003:"NETWORK_RETRY",50004:"NETWORK_BREAK",60001:"WEBGL_CONTEXT_LOST",60002:"WEBGL_CONTEXT_RESTORED",60003:"WEBGL_CONTEXT_RESTORE_TIMEOUT",60004:"WEBGL_CONTEXT_RECOVERED",60005:"WEBGL_CONTEXT_RECOVERY_FAILED",60006:"WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",60007:"WEBGL_RESOLUTION_RESTORED",60008:"WEBGL_CONTEXT_MANUAL_RESTARTED"};var AvatarStatus,RenderState,InitModel,EFrameDataType;!function(t){t[t.online=0]="online",t[t.offline=1]="offline",t[t.network_on=2]="network_on",t[t.network_off=3]="network_off",t[t.close=4]="close",t[t.visible=5]="visible",t[t.invisible=6]="invisible",t[t.stopped=7]="stopped"}(AvatarStatus||(AvatarStatus={})),function(t){t.init="init",t.rendering="rendering",t.pausing="pausing",t.paused="paused",t.resumed="resumed",t.stopped="stopped"}(RenderState||(RenderState={})),function(t){t.normal="normal",t.invisible="invisible"}(InitModel||(InitModel={})),function(t){t.AUDIO="tts_audio",t.BODY="body_data",t.FACE="face_data",t.EVENT="event_data",t.AA_FRAME="aa_frame",t.SYNC_FRAME="sync_frame"}(EFrameDataType||(EFrameDataType={}));const FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk";class DataCacheQueue{constructor(){this.TAG="[DataCacheQueue]",this._bodyQueue=new Map,this._facialQueue=[],this._realFacialQueue=[],this.audioQueue=[],this.eventQueue=[],this.videoIdList=[],this._currentPlayState="idle",this._currentTtsaState=null,window.__dev_event_queue__=this.eventQueue}set currentPlayState(t){this._currentPlayState=t}get currentPlayState(){return this._currentPlayState}set currentTtsaState(t){this._currentTtsaState=t}get currentTtsaState(){return this._currentTtsaState}get bodyQueue(){return Array.from(this._bodyQueue.values())}_updateBodyImageBitmap(t){const e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(const[e,n]of this._bodyQueue.entries())n.body_id<t.body_id&&n.frameIndex>=t.frameIndex&&(n.frame.close(),this._bodyQueue.delete(e));this._bodyQueue.set(t.frameIndex,t)}clearOldFrames(t){for(const[e,n]of this._bodyQueue.entries())e>=t&&(n.frame.close(),this._bodyQueue.delete(e))}clearOldFaceData(t){this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),this._realFacialQueue=this._realFacialQueue.filter(e=>e.frameIndex>=t)}setVideoIdList(t){this.videoIdList.includes(t)||this.videoIdList.push(t)}getVideoIdList(){return this.videoIdList}_getBodyImageBitmap(t){const e=this._bodyQueue.get(t);for(const[e,n]of this._bodyQueue.entries())e<t&&(n.frame.close(),this._bodyQueue.delete(e));if(e)return e}getBodyVideoNameListLength(){const t=[];return this.bodyQueue.forEach(e=>{t.includes(e.name)||t.push(e.name)}),t.length}_getFaceImageBitmap(t,e){let n=null;for(let i=this._facialQueue.length-1;i>=0;i--){const r=this._facialQueue[i];if(r.frameIndex===t&&r.body_id===e){n=r;break}}return this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),n}_updateFacial(t){this._facialQueue.push(...t)}get facialQueue(){return this._facialQueue}_getRealFaceImageBitmap(t,e){let n=null;for(let i=this._realFacialQueue.length-1;i>=0;i--){const r=this._realFacialQueue[i];if((null==r?void 0:r.frameIndex)===t&&(null==r?void 0:r.body_id)===e){n=r;break}}return this._realFacialQueue=this._realFacialQueue.filter(e=>(null==e?void 0:e.frameIndex)>=t),n}_updateRealFacial(t){this._realFacialQueue.push(...t)}get realFacialQueue(){return this._realFacialQueue}clearAllFaceData(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")}_updateAudio(t){this.audioQueue.push(...t)}_clearAudio(t){this.audioQueue=-1!==t?this.audioQueue.filter(e=>e.sid!==t):[]}_getAudio(t){const e=this.audioQueue.findIndex(e=>e.sf===t);if(-1===e)return;const[n]=this.audioQueue.splice(e,1);return n}_getAudioInterval(t,e){const n=this.audioQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0===n.length)return;const i=n[n.length-1],r=this.audioQueue.findIndex(t=>t.id===i.id);return this.audioQueue.splice(r,1),i}_updateUiEvent(t){this.eventQueue.push(...t)}clearOldEvent(t){this.eventQueue=this.eventQueue.filter(e=>e.sf>=t)}clearSubtitleOn(t){this.eventQueue=this.eventQueue.map(e=>{var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(e=>e.speech_id>t||"subtitle_on"!==e.type)})})}_clearEvent(){this.eventQueue=[]}_getEvent(t){const e=this.eventQueue.filter(e=>e.sf===t);if(0!==e.length)return this.eventQueue=this.eventQueue.filter(e=>e.sf!==t),this._mergeEventsBySf(e)}_getEventInterval(t,e){const n=this.eventQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0!==n.length)return this.eventQueue=this.eventQueue.filter(n=>!(n.sf>=t&&n.sf<=e)),this._mergeEventsBySf(n)}_mergeEventsBySf(t){const e={};for(const n of t){const t=n.sf;e[t]||(e[t]=_extends({},n,{e:[]})),e[t].e.push(...n.e)}const n=Object.values(e);if(0===n.length)return null;if(n.length>1){const t=[];return n.forEach(e=>t.push(...e.e)),_extends({},n[0],{mergeFrameFlag:1,e:t})}return n[0]}checkValidData(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,i;if(0===this.audioQueue.length||0===t.length)return;if((null==(n=this.audioQueue[this.audioQueue.length-1])?void 0:n.ef)<t[0].sf||t[0].sf<(null==(i=this.audioQueue[0])?void 0:i.sf)){const e=this.audioQueue.findIndex(e=>e.sf>=t[0].sf);-1!==e&&(this.audioQueue.length=e)}}}destroy(){this._bodyQueue.forEach(t=>{t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]}}class GLDevice{constructor(t){this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;const e=()=>{const t=this.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");this.gl=t,this._lost_context_sim=this.gl.getExtension("WEBGL_lose_context"),this.shaderStage={vertex:this.gl.VERTEX_SHADER,fragment:this.gl.FRAGMENT_SHADER},this._ElementTypeMap_JS2GL={Uint8Array:this.gl.UNSIGNED_BYTE,Uint8ClampedArray:this.gl.UNSIGNED_BYTE,Int8Array:this.gl.BYTE,Uint16Array:this.gl.UNSIGNED_SHORT,Int16Array:this.gl.SHORT,Uint32Array:this.gl.UNSIGNED_INT,Int32Array:this.gl.INT,Float16Array:this.gl.HALF_FLOAT,Float32Array:this.gl.FLOAT};const e=[[this.gl.UNSIGNED_BYTE,[[this.gl.RED,this.gl.R8],[this.gl.RED_INTEGER,this.gl.R8UI],[this.gl.RG,this.gl.RG8],[this.gl.RG_INTEGER,this.gl.RG8UI],[this.gl.RGB,this.gl.RGB8],[this.gl.RGB_INTEGER,this.gl.RGB8UI],[this.gl.RGBA,this.gl.RGBA8],[this.gl.RGBA_INTEGER,this.gl.RGBA8UI]]],[this.gl.BYTE,[[this.gl.RED,this.gl.R8_SNORM],[this.gl.RED_INTEGER,this.gl.R8I],[this.gl.RG,this.gl.RG8_SNORM],[this.gl.RG_INTEGER,this.gl.RG8I],[this.gl.RGB,this.gl.RGB8_SNORM],[this.gl.RGB_INTEGER,this.gl.RGB8I],[this.gl.RGBA,this.gl.RGBA8_SNORM],[this.gl.RGBA_INTEGER,this.gl.RGBA8I]]],[this.gl.UNSIGNED_SHORT,[[this.gl.RED_INTEGER,this.gl.R16UI],[this.gl.RG_INTEGER,this.gl.RG16UI],[this.gl.RGB_INTEGER,this.gl.RGB16UI],[this.gl.RGBA_INTEGER,this.gl.RGBA16UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT16]]],[this.gl.SHORT,[[this.gl.RED_INTEGER,this.gl.R16I],[this.gl.RG_INTEGER,this.gl.RG16I],[this.gl.RGB_INTEGER,this.gl.RGB16I],[this.gl.RGBA_INTEGER,this.gl.RGBA16I]]],[this.gl.UNSIGNED_INT,[[this.gl.RED_INTEGER,this.gl.R32UI],[this.gl.RG_INTEGER,this.gl.RG32UI],[this.gl.RGB_INTEGER,this.gl.RGB32UI],[this.gl.RGBA_INTEGER,this.gl.RGBA32UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT24]]],[this.gl.INT,[[this.gl.RED_INTEGER,this.gl.R32I],[this.gl.RG_INTEGER,this.gl.RG32I],[this.gl.RGB_INTEGER,this.gl.RGB32I],[this.gl.RGBA_INTEGER,this.gl.RGBA32I]]],[this.gl.HALF_FLOAT,[[this.gl.RED,this.gl.R16F],[this.gl.RG,this.gl.RG16F],[this.gl.RGB,this.gl.RGB16F],[this.gl.RGBA,this.gl.RGBA16F]]],[this.gl.FLOAT,[[this.gl.RED,this.gl.R32F],[this.gl.RG,this.gl.RG32F],[this.gl.RGB,this.gl.RGB32F],[this.gl.RGBA,this.gl.RGBA32F],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT32F]]],[this.gl.UNSIGNED_SHORT_5_6_5,[[this.gl.RGB,this.gl.RGB565]]],[this.gl.UNSIGNED_SHORT_4_4_4_4,[[this.gl.RGBA,this.gl.RGBA4]]],[this.gl.UNSIGNED_SHORT_5_5_5_1,[[this.gl.RGBA,this.gl.RGB5_A1]]],[this.gl.UNSIGNED_INT_2_10_10_10_REV,[[this.gl.RGBA,this.gl.RGB10_A2]]],[this.gl.UNSIGNED_INT_10F_11F_11F_REV,[[this.gl.RGB,this.gl.R11F_G11F_B10F]]],[this.gl.UNSIGNED_INT_5_9_9_9_REV,[[this.gl.RGB,this.gl.RGB9_E5]]],[this.gl.UNSIGNED_INT_24_8,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH24_STENCIL8]]],[this.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH32F_STENCIL8]]]];this._FormatTypeMap_Ext2Int=new Map;for(const[t,n]of e){const e=new Map;for(const[t,i]of n)e.set(t,i);this._FormatTypeMap_Ext2Int.set(t,e)}const n={GL_RED:this.gl.RED,GL_RED_INTEGER:this.gl.RED_INTEGER,GL_RG:this.gl.RG,GL_RG_INTEGER:this.gl.RG_INTEGER,GL_RGB:this.gl.RGB,GL_RGB_INTEGER:this.gl.RGB_INTEGER,GL_RGBA:this.gl.RGBA,GL_RGBA_INTEGER:this.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:this.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:this.gl.DEPTH_STENCIL};this._FormatTypeMap_Ext2Str=new Map;for(const[t,e]of Object.entries(n))this._FormatTypeMap_Ext2Str.set(e,t)};this.frameID=null,this.cbRender=()=>{},this._onContextLost=t=>{t.preventDefault(),this.stop()},this._onContextRestored=e,this._onContextCreationError=t=>{console.error(t.statusMessage||"WebGL context creation error: unknown error.")},this.canvas.addEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.addEventListener("webglcontextcreationerror",this._onContextCreationError,!1),e()}compileShaderProgram(t){let e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(const[n,i]of Object.entries(t)){const t=this.gl.createShader(this.shaderStage[n]);if(!t)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(t,i),this.gl.compileShader(t),!this.gl.getShaderParameter(t,this.gl.COMPILE_STATUS)){const e=this.gl.getShaderInfoLog(t);throw this.gl.deleteShader(t),new Error("WebGL shader compile failed:"+e)}this.gl.attachShader(e,t)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const t=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+t)}return e}getShaderProgramUniformLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getUniformLocation(t,i);return n}getShaderProgramUniformBlockLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getUniformBlockIndex(t,i);return n}getShaderProgramAttribLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getAttribLocation(t,i);return n}getGLArrayElementType(t){const e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null}getGLTexInternalFormat(t,e){const n=this._FormatTypeMap_Ext2Int.get(e);if(n){const e=n.get(t);if(e)return e}return null}texImage2D(t,e,n,i,r,s){var a;const o=this.getGLArrayElementType(s);if(!o)throw new Error(`Unsupported data format: ${s[Symbol.toStringTag]}`);const l=this.getGLTexInternalFormat(r,o);if(!l)throw new Error(`No available internal format for ${s[Symbol.toStringTag]} and ${null!=(a=this._FormatTypeMap_Ext2Str.get(r))?a:"unknown"}.`);this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,i,0,r,o,s)}texImage3D(t,e,n,i,r,s,a){var o;const l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);const h=this.getGLTexInternalFormat(s,l);if(!h)throw new Error(`No available internal format for ${a[Symbol.toStringTag]} and ${null!=(o=this._FormatTypeMap_Ext2Str.get(s))?o:"unknown"}.`);this.gl.HALF_FLOAT==l&&(a=new Uint16Array(a.buffer)),this.gl.texImage3D(t,e,h,n,i,r,0,s,l,a)}run(t,e){if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;const t=(n,i)=>{this.running&&(this.syncMediaTime=i.mediaTime,this.cbRender(this),this.frameID=e.requestVideoFrameCallback(t))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(t)}else{const t=()=>{this.running&&(this.cbRender(this),this.frameID=requestAnimationFrame(t))};t()}}refresh(){this.cbRender(this)}getSyncMediaTime(){return this.syncMediaTime}stop(){null!==this.frameID&&(this.syncMedia?(this.syncMedia.cancelVideoFrameCallback(this.frameID),this.syncMedia=null,this.syncMediaTime=null):cancelAnimationFrame(this.frameID),this.frameID=null),this.running=!1}simulateContextFault(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())}captureFrame(){const t=this.canvas.width,e=this.canvas.height,n=new Uint8ClampedArray(t*e*4);return this.gl.readPixels(0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),{width:t,height:e,data:n}}destroy(){if(this._isDestroyed||!this.gl)return;const t=this.gl;try{const e=t.getExtension("WEBGL_lose_context");if(e&&e.loseContext(),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),t.flush(),this.canvas){const t=this.canvas.getContext("2d");t&&t.clearRect(0,0,this.canvas.width,this.canvas.height)}this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.removeEventListener("webglcontextcreationerror",this._onContextCreationError,!1)),this.gl=null,this._isDestroyed=!0}catch(t){this._isDestroyed=!0}}}function length(t){return Math.sqrt(t.reduce((t,e)=>t+e*e,0))}function normalize(t){let e=length(t);return t.map(t=>t/e)}function mvmul(t,e){const n=t.length,i=e.length;let r=Array(n);for(let s=0;s<n;s++){r[s]=0;for(let n=0;n<i;n++)r[s]+=t[s][n]*e[n]}return r}function mmul(t,e){const n=t.length,i=e.length,r=e[0].length;let s=Array(n);for(let a=0;a<n;a++){let n=Array(r);for(let s=0;s<r;s++){n[s]=0;for(let r=0;r<i;r++)n[s]+=t[a][r]*e[r][s]}s[a]=n}return s}function transpose(t){const e=t.length,n=t[0].length;let i=Array(n);for(let r=0;r<n;r++){let n=Array(e);for(let i=0;i<e;i++)n[i]=t[i][r];i[r]=n}return i}function identity(t){let e=Array(t);for(let n=0;n<t;n++){let i=Array(t);for(let e=0;e<t;e++)i[e]=n==e?1:0;e[n]=i}return e}function det3(t){let e=0;return e+=t[0][0]*t[1][1]*t[2][2],e+=t[0][1]*t[1][2]*t[2][0],e+=t[0][2]*t[1][0]*t[2][1],e-=t[0][2]*t[1][1]*t[2][0],e-=t[0][1]*t[1][0]*t[2][2],e-=t[0][0]*t[1][2]*t[2][1],e}function inv3(t){const e=1/det3(t);return[[(t[1][1]*t[2][2]-t[2][1]*t[1][2])*e,(t[0][2]*t[2][1]-t[0][1]*t[2][2])*e,(t[0][1]*t[1][2]-t[0][2]*t[1][1])*e],[(t[1][2]*t[2][0]-t[1][0]*t[2][2])*e,(t[0][0]*t[2][2]-t[0][2]*t[2][0])*e,(t[1][0]*t[0][2]-t[0][0]*t[1][2])*e],[(t[1][0]*t[2][1]-t[2][0]*t[1][1])*e,(t[2][0]*t[0][1]-t[0][0]*t[2][1])*e,(t[0][0]*t[1][1]-t[1][0]*t[0][1])*e]]}function inv4(t){let e=[[...t[0]],[...t[1]],[...t[2]],[...t[3]]],n=[0,0,0,0],i=[0,0,0,0],r=0;for(let t=0;t<4;t++){let s=0;for(let r=t;r<4;r++)for(let a=t;a<4;a++)Math.abs(e[r][a])>s&&(s=Math.abs(e[r][a]),n[t]=r,i[t]=a);if(s<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[t]!=t)for(let i=0;i<4;i++)r=e[t][i],e[t][i]=e[n[t]][i],e[n[t]][i]=r;if(i[t]!=t)for(let n=0;n<4;n++)r=e[n][t],e[n][t]=e[n][i[t]],e[n][i[t]]=r;e[t][t]=1/e[t][t];for(let n=0;n<4;n++)n!=t&&(e[t][n]*=e[t][t]);for(let n=0;n<4;n++)if(n!=t)for(let i=0;i<4;i++)i!=t&&(e[n][i]-=e[n][t]*e[t][i]);for(let n=0;n<4;n++)n!=t&&(e[n][t]*=-e[t][t])}for(let t=3;t>=0;t--){if(i[t]!=t)for(let n=0;n<4;n++)r=e[t][n],e[t][n]=e[i[t]][n],e[i[t]][n]=r;if(n[t]!=t)for(let i=0;i<4;i++)r=e[i][t],e[i][t]=e[i][n[t]],e[i][n[t]]=r}return e}function quaternion_conj(t){return[t[0],-t[1],-t[2],-t[3]]}function quaternion_mul(t,e){return[t[0]*e[0]-t[1]*e[1]-t[2]*e[2]-t[3]*e[3],t[0]*e[1]+t[1]*e[0]+t[2]*e[3]-t[3]*e[2],t[0]*e[2]-t[1]*e[3]+t[2]*e[0]+t[3]*e[1],t[0]*e[3]+t[1]*e[2]-t[2]*e[1]+t[3]*e[0]]}function quaternion_to_mat(t){const[e,n,i,r]=t;return[[e*e+n*n-i*i-r*r,2*(n*i-r*e),2*(n*r+i*e)],[2*(n*i+r*e),e*e-n*n+i*i-r*r,2*(i*r-n*e)],[2*(n*r-i*e),2*(i*r+n*e),e*e-n*n-i*i+r*r]]}function GivensTransform(t,e,n,i){const r=Math.sin(i),s=Math.cos(i),a=t[0].length;for(let i=0;i<a;i++){const a=r*t[e][i]+s*t[n][i];t[e][i]=s*t[e][i]-r*t[n][i],t[n][i]=a}}function Euler_to_mat(t,e="xyz"){let n=identity(3);switch(e){case"xyz":case"zxy":GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]),GivensTransform(n,0,1,t[2]);break;case"yzx":GivensTransform(n,0,1,t[2]),GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]);break;case"xzy":GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]);break;case"yxz":GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]);break;case"zyx":GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]);break;default:throw Error("Unrecognizable rotation order.")}return n}function make_homogeneous(t,e){return[[t[0][0],t[0][1],t[0][2],e[0]],[t[1][0],t[1][1],t[1][2],e[1]],[t[2][0],t[2][1],t[2][2],e[2]],[0,0,0,1]]}function flatten(t){const e=t.length,n=t[0].length;let i=Array(e*n);for(let r=0;r<e;r++)for(let e=0;e<n;e++)i[r*n+e]=t[r][e];return i}const performanceConstant={load_resource:"load_resource",ttsa_connect:"ttsa_connect",ttsa_ready:"ttsa_ready",first_avatar_render:"first_avatar_render",first_webgl_render:"first_webgl_render",ttsa_body_res:"ttsa_body_res",start_action_res:"start_action_res",start_action_render:"start_action_render",load_video:"load_video",decode_video:"decode_video",voice_response_play:"voice_response_play",first_decode_video:"first_decode_video",first_render:"first_render"};class PerformanceTracker{constructor(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=()=>{},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}getFirstInfo(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}}markStart(t,e){this.marks.set(t,{state:e,time:performance.now()})}markEnd(t,e){const n=this.marks.get(t);if(!n)return;if(e&&"string"==typeof e&&e!==(null==n?void 0:n.state))return;const i=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:i}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,i),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=i),t===performanceConstant.first_render&&(this.firstRenderTime=i),i}getAllMetrics(){return Object.fromEntries(this.measures.entries())}getVideoMetrics(){const t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(([t])=>[performanceConstant.decode_video,performanceConstant.load_video].includes(t)))}setReportFunc(t){this.reportFunc=t}reportMetric(){var t;const e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){const t=Object.fromEntries(Object.entries(e).filter(([t])=>![performanceConstant.load_video,performanceConstant.decode_video].includes(t)));var n;Object.keys(t).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(t));for(const e in t)e!==performanceConstant.decode_video&&e!==performanceConstant.load_video&&this.measures.delete(e)}}setOnStateRenderChange(t){this.onStateRenderChange=t}}window.performanceTracker=new PerformanceTracker;const shadow_sample_count=4,shader_common="\n float randFloat(vec2 p) {\n // generate a uniformely distributed float in [0, 1).\n return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);\n }\n bool isMaskedBitSet(uint value, uint mask){\n return bool(value & mask);\n }\n vec4 RGB2sRGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.0031308)color[i] *= 12.92;\n else color[i] = 1.055 * pow(color[i], 1.0 / 2.4) - 0.055;\n }\n return color;\n }\n vec4 sRGB2RGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.04045)color[i] /= 12.92;\n else color[i] = pow((color[i] + 0.055) / 1.055, 2.4);\n }\n return color;\n }\n",vs_background="#version 300 es\n layout(location = 0) in vec2 pos;\n layout(location = 1) in vec2 texCoord;\n out vec2 v_texCoord;\n void main() {\n gl_Position = vec4(pos, 0, 1);\n v_texCoord = texCoord;\n }\n",fs_background=`#version 300 es\n precision mediump float;\n uniform sampler2D u_image_bg, u_image_char_body, u_image_mesh_color, u_image_mesh_alpha;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint flags; // 1 - has background, 2 - with multisample coverage, 4 - shadow fx\n\n layout (std140) uniform ub_shadow_fx_info {\n mat3 transform[2];\n vec4 color;\n vec4 sampleParams; // sample radius, unused, unused, unused \n } ub_shadow_fx;\n\n in vec2 v_texCoord;\n out vec4 fragColor;\n\n ${shader_common}\n\n vec2 tex2scr(vec2 coord){\n return vec2(coord.x * 2.0 - 1.0, 1.0 - coord.y * 2.0);\n }\n vec2 scr2tex(vec2 coord){\n return vec2(coord.x * 0.5 + 0.5, 0.5 - coord.y * 0.5);\n }\n vec2 randomUnitVec2D(float seed) {\n float theta = seed * 2.0 * 3.14159265359;\n return vec2(cos(theta), sin(theta));\n }\n float sampleOpacity(vec2 texCoord, mat2 u_transform_2d){\n float result = texture(u_image_mesh_color, vec2(texCoord.x, 1.0 - texCoord.y)).a;\n texCoord = texCoord * u_transform_2d[0] + u_transform_2d[1];\n texCoord.x = texCoord.x * 0.5 + 0.5;\n result += (1.0 - result) * texture(u_image_char_body, texCoord).r;\n return result;\n }\n float PI = 3.14159265359;\n\n void main() {\n float randSeed = randFloat(vec2(gl_FragCoord.xy));\n\n vec2 texcoord_transformed = v_texCoord * u_transform_2d[0] + u_transform_2d[1];\n texcoord_transformed = clamp(texcoord_transformed, 0.0, 1.0);\n vec2 texCoord_char_color = vec2(texcoord_transformed.x * 0.5, texcoord_transformed.y);\n vec2 texCoord_char_alpha = vec2(texcoord_transformed.x * 0.5 + 0.5, texcoord_transformed.y);\n vec2 texCoord_mesh = vec2(v_texCoord.x, 1.0 - v_texCoord.y);\n\n vec4 char_color = texture(u_image_char_body, texCoord_char_color);\n vec4 char_alpha = texture(u_image_char_body, texCoord_char_alpha);\n char_color = sRGB2RGB(char_color);\n char_alpha = sRGB2RGB(char_alpha);\n float char_alpha_back = char_alpha.r;\n float char_alpha_front = max(char_alpha.r - char_alpha.b, 0.0);\n\n vec4 mesh_color_srgb = texture(u_image_mesh_color, texCoord_mesh);\n float mesh_alpha = mesh_color_srgb.a;\n if(isMaskedBitSet(flags, 2u)){\n float mesh_coverage = texture(u_image_mesh_alpha, texCoord_mesh).r;\n mesh_color_srgb.rgb /= max(mesh_coverage, 9e-5); // epsilon for float16\n }\n\n vec3 final_rgb = char_alpha_back * char_color.rgb;\n float final_alpha = char_alpha_back;\n\n if(isMaskedBitSet(flags, 4u)){ // fake shadow\n vec3 pos_shadow = vec3(tex2scr(v_texCoord), 1.0);\n pos_shadow = ub_shadow_fx.transform[1] * pos_shadow;\n if(pos_shadow.z > 0.0 && pos_shadow.y > 0.0){\n // simple and noisy blur\n pos_shadow /= pos_shadow.z;\n float radius = ub_shadow_fx.sampleParams.x * pos_shadow.y;\n vec2 randVec = randomUnitVec2D(randSeed);\n mat2 randMat = mat2(randVec.x, randVec.y, -randVec.y, randVec.x);\n float shadow_opacity = 0.0;\n\n int sampleCount = radius > 0.0 ? ${shadow_sample_count} : 1;\n for(int i=0;i<sampleCount;i++){\n float sampleDist = (float(i) + 0.5) / float(sampleCount);\n float angle = 26.0 * PI * sampleDist; // prime number * 2pi\n sampleDist = radius * sqrt(sampleDist);\n vec2 sampleVec = sampleDist * randMat * vec2(cos(angle), sin(angle));\n\n vec3 pos_shadow_proj = ub_shadow_fx.transform[0] * (pos_shadow + vec3(sampleVec, 0.0));\n vec2 texCoord_shadow = clamp(pos_shadow_proj.xy / pos_shadow_proj.z, -1.0, 1.0);\n texCoord_shadow = scr2tex(texCoord_shadow);\n shadow_opacity += sampleOpacity(texCoord_shadow, u_transform_2d);\n }\n shadow_opacity /= float(sampleCount);\n float shadow_alpha = shadow_opacity * ub_shadow_fx.color.a;\n\n final_rgb = final_rgb + (1.0 - final_alpha) * shadow_alpha * ub_shadow_fx.color.rgb;\n final_alpha = final_alpha + (1.0 - final_alpha) * shadow_alpha;\n }\n }\n final_rgb = mesh_alpha * mesh_color_srgb.rgb + (1.0 - mesh_alpha) * final_rgb;\n final_alpha = mesh_alpha + (1.0 - mesh_alpha) * final_alpha;\n final_rgb = char_alpha_front * char_color.rgb + (1.0 - char_alpha_front) * final_rgb;\n final_alpha = char_alpha_front + (1.0 - char_alpha_front) * final_alpha;\n\n if(isMaskedBitSet(flags, 1u)){\n vec4 bg_color = sRGB2RGB(texture(u_image_bg, v_texCoord));\n final_rgb += bg_color.rgb * (1.0 - final_alpha);\n final_alpha = 1.0;\n }\n final_rgb = RGB2sRGB(vec4(final_rgb, 1.0)).rgb;\n fragColor = vec4(final_rgb, final_alpha);\n }\n`,uniform_var_list_bg=["u_image_bg","u_image_char_body","u_image_mesh_color","u_image_mesh_alpha","u_transform_2d","flags"],uniform_block_list_bg=["ub_shadow_fx_info"];function generateMeshPipelineShader(t){return{vertex:`#version 300 es\n precision highp float;\n\n layout (std140) uniform ub_rig_info {\n mat4 joint_matrices[${t.max_bones}];\n vec4 bs_weights[${t.max_bs_count/4}];\n } ub_rig;\n \n uniform sampler2D u_image_bs; // used for blendshape deformation\n uniform mat4 u_proj_mat;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint u_bs_count; // number of bs weight vectors (divided by 4)\n uniform uint flags; // 1 - has opacity\n\n layout(location = 0) in vec3 pos;\n layout(location = 1) in vec2 tex_coord;\n layout(location = 2) in float opacity;\n layout(location = 3) in uvec4 bone_index_0_4;\n layout(location = 4) in uvec4 bone_index_4_8;\n layout(location = 5) in vec4 bone_weight_0_4;\n layout(location = 6) in vec4 bone_weight_4_8;\n\n out vec4 v_pos;\n out vec2 v_tex_coord;\n out float v_opacity;\n\n ${shader_common}\n\n vec4 lbs_transform(vec3 pos){\n float total_weight = 0.0;\n vec4 aug_pos = vec4(pos, 1.0);\n vec4 result = vec4(0.0);\n uint index;\n for(index = 0u;index < 8u;index++){\n uint joint_index;\n float joint_weight;\n if(index < 4u) {\n joint_index = bone_index_0_4[index];\n joint_weight = bone_weight_0_4[index];\n }\n else {\n joint_index = bone_index_4_8[index - 4u];\n joint_weight = bone_weight_4_8[index - 4u];\n }\n if(255u == joint_index)break;\n else result += joint_weight * (ub_rig.joint_matrices[joint_index] * aug_pos);\n }\n result /= result.w;\n return vec4(result.xyz, 1.0);\n }\n\n vec3 bs_accumulate(uint vertex_id){\n uint texWidth = uint(textureSize(u_image_bs, 0).x);\n vec3 pos = vec3(0.0);\n\n uint vertex_offset = vertex_id * u_bs_count * 3u;\n for(uint i = 0u; i < u_bs_count; i++){\n vec4 bs_weight_vec = ub_rig.bs_weights[i];\n for (uint j = 0u; j < 3u; j++){\n uint texel_offset = j * u_bs_count + vertex_offset + i;\n uint texel_x = texel_offset % texWidth;\n uint texel_y = texel_offset / texWidth;\n vec4 data = texelFetch(u_image_bs, ivec2(texel_x, texel_y), 0);\n pos[j] += dot(data, bs_weight_vec);\n }\n }\n return pos;\n }\n \n void main() {\n if(isMaskedBitSet(flags, 1u))v_opacity = opacity; else v_opacity = 1.0;\n \n vec3 bs_pos = vec3(0.0);\n if(u_bs_count > 0u)bs_pos = bs_accumulate(uint(gl_VertexID)) * v_opacity;\n v_pos = u_proj_mat * lbs_transform(pos + bs_pos);\n v_pos /= v_pos.w;\n v_pos.xy = u_transform_2d[0] * v_pos.xy + u_transform_2d[1];\n v_tex_coord = tex_coord;\n gl_Position = v_pos;\n }\n`,fragment_mask:"#version 300 es\n precision highp float;\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing)fragColor = vec4(1.0);\n else fragColor = vec4(0.0);\n }\n",fragment:`#version 300 es\n precision highp int;\n precision highp float;\n precision highp sampler2DArray;\n precision highp sampler3D;\n layout (std140) uniform ub_pca_info {\n vec4 weights[${t.max_pca_component_count/4}];\n } ub_pca;\n uniform sampler2DArray u_image_pca;\n uniform sampler3D u_image_lut;\n uniform uint flags; // 2 - has LUT, 4 - unsigned PCA component\n uniform vec3 u_gamma;\n uniform vec3 u_color_balance; // r/c, g/m, b/y\n\n ${shader_common}\n \n vec4 pca_accumulate(vec2 tex_coord, bool _unsigned){\n ivec3 texSize = textureSize(u_image_pca, 0);\n vec4 result = vec4(0.0);\n for(int i = 0; i < texSize.z; i++){\n int vec_index = i / 4;\n int elem_index = i % 4;\n vec4 pca_sample = texture(u_image_pca, vec3(tex_coord, float(i)));\n if(_unsigned)pca_sample = 2.0 * pca_sample - 1.0;\n result += ub_pca.weights[vec_index][elem_index] * pca_sample;\n }\n return result;\n }\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing){\n vec2 fragTexCoord = v_tex_coord;\n vec4 sample_color = pca_accumulate(v_tex_coord, isMaskedBitSet(flags, 4u));\n if(isMaskedBitSet(flags, 2u))sample_color = texture(u_image_lut, sample_color.rgb);\n // Apply gamma correction\n vec3 final_color = pow(sample_color.rgb, u_gamma);\n\n // Apply color balance\n // Convert -100 to 100 range to -0.5 to 0.5 range\n vec3 balance_adjusted = u_color_balance / 200.0; // Map -100..100 to -0.5..0.5\n\n // Red/Cyan adjustment\n final_color.r += balance_adjusted.x;\n final_color.g -= balance_adjusted.x; // Cyan is opposite of Red\n\n // Green/Magenta adjustment\n final_color.g += balance_adjusted.y;\n final_color.b -= balance_adjusted.y; // Magenta is opposite of Green\n\n // Blue/Yellow adjustment\n final_color.b += balance_adjusted.z;\n final_color.r -= balance_adjusted.z; // Yellow is opposite of Blue\n\n // Clamp values to [0, 1]\n final_color = clamp(final_color, 0.0, 1.0);\n fragColor = sRGB2RGB(vec4(final_color.bgr, v_opacity));\n }\n else fragColor = vec4(0.0);\n }\n`}}const uniform_var_list_mesh=["u_proj_mat","u_transform_2d","u_image","u_image_bs","u_image_pca","u_image_lut","u_bs_count","flags","u_gamma","u_color_balance"],uniform_block_list_mesh=["ub_pca_info","ub_rig_info"];class GLPipeline{assembleBackgroundPipeline(){this._ub_shadow_fx_data=new Float32Array(32);const t=this.device.compileShaderProgram({vertex:vs_background,fragment:fs_background}),e=this.device.getShaderProgramUniformLocation(t,uniform_var_list_bg),n=this.device.getShaderProgramUniformBlockLocation(t,uniform_block_list_bg);this.backgroundPipelineInfo={program:t,progUniforms:e,progUniformBlocks:n},this.device.gl.uniformBlockBinding(this.backgroundPipelineInfo.program,this.backgroundPipelineInfo.progUniformBlocks.ub_shadow_fx_info,0),this.backgroundVAO=this.device.gl.createVertexArray(),this.device.gl.bindVertexArray(this.backgroundVAO);const i=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,2,this.device.gl.FLOAT,!1,16,0),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.gl.FLOAT,!1,16,8),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null);let r={};r.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW),this.backgroundBuffers=r,this.device.gl.bindVertexArray(null);let s={};if(s.u_image_bg=this.device.gl.createTexture(),!s.u_image_bg)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_bg),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),s.u_image_char_body=this.device.gl.createTexture(),!s.u_image_char_body)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_char_body),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.backgroundTextures=s}assembleMeshPipelines(t){if(t.char){const e=t.char;let n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)};for(let t=0;t<e.mesh.length;t++){const i=e.mesh[t].textureModels;let r=0;for(let t of i){let e=t.data.size[0]+3;e-=e%4,r=Math.max(r,e)}n.max_pca_component_count=Math.max(n.max_pca_component_count,r);let s=e.mesh[t].blendshapes.size[2]+3;s-=s%4,n.max_bs_count=Math.max(n.max_bs_count,s)}this.meshStatistics=n,this._ub_rig_info_data=new Float32Array(16*this.meshStatistics.max_bones+this.meshStatistics.max_bs_count),this._ub_pca_info_data=new Float32Array(this.meshStatistics.max_pca_component_count);const i=generateMeshPipelineShader(this.meshStatistics);let r=this.device.compileShaderProgram({vertex:i.vertex,fragment:i.fragment}),s=this.device.getShaderProgramUniformLocation(r,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(r,uniform_block_list_mesh);this.meshPipelineInfo={program:r,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_rig_info,0),this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_pca_info,1),r=this.device.compileShaderProgram({vertex:i.vertex,fragment:i.fragment_mask}),s=this.device.getShaderProgramUniformLocation(r,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(r,uniform_block_list_mesh),this.maskPipelineInfo={program:r,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(let t=0;t<e.mesh.length;t++){let i={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(i.VAO),null===this.device.getGLArrayElementType(e.mesh[t].blendshapes.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].blendshapes.data}`);if(i.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[t].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[t].UVCoord.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].UVCoord.data}`);if(i.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[t].UVCoord.data),!0,0,0),e.mesh[t].opacity){if(null===this.device.getGLArrayElementType(e.mesh[t].opacity.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].opacity.data}`);i.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[t].opacity.data),!0,0,0)}if(i.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointIndex,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(3),this.device.gl.vertexAttribIPointer(3,4,this.device.gl.UNSIGNED_BYTE,8,0),this.device.gl.enableVertexAttribArray(4),this.device.gl.vertexAttribIPointer(4,4,this.device.gl.UNSIGNED_BYTE,8,4),i.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointWeight,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(5),this.device.gl.vertexAttribPointer(5,4,this.device.gl.FLOAT,!1,32,0),this.device.gl.enableVertexAttribArray(6),this.device.gl.vertexAttribPointer(6,4,this.device.gl.FLOAT,!1,32,16),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null),null===this.device.getGLArrayElementType(e.mesh[t].triangles.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].triangles.data}`);if(i.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[t].triangles.data,this.device.gl.STATIC_DRAW),i.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(n.max_pca_component_count),this.device.gl.DYNAMIC_DRAW),i.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(16*n.max_bones+n.max_bs_count),this.device.gl.DYNAMIC_DRAW),this.device.gl.bindVertexArray(null),e.mesh[t].blendshapes.size[2]>0){let n=[Math.ceil(e.mesh[t].blendshapes.size[2]/4),e.mesh[t].blendshapes.size[0]*e.mesh[t].blendshapes.size[1]],r=Math.ceil(Math.sqrt(n[0]*n[1])),s=4*n[0],a=new Float32Array(r*r*4);for(let i=0;i<n[1];i++){for(let n=0;n<e.mesh[t].blendshapes.size[2];n++)a[i*s+n]=e.mesh[t].blendshapes.data[i*e.mesh[t].blendshapes.size[2]+n];for(let n=e.mesh[t].blendshapes.size[2];n<s;n++)a[i*s+n]=0}if(i.textures.u_image_bs=this.device.gl.createTexture(),!i.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.texImage2D(this.device.gl.TEXTURE_2D,0,r,r,this.device.gl.RGBA,a),i.uniformUInts.u_bs_count=n[0]}else i.uniformUInts.u_bs_count=0;for(let n of e.mesh[t].textureModels){let t=this.device.gl.createTexture();if(!t)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,t),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR);let e=this.device.getGLArrayElementType(n.data.data),r={texture:t,unsigned:this.device.gl.UNSIGNED_BYTE===e||this.device.gl.UNSIGNED_SHORT===e||this.device.gl.UNSIGNED_INT===e},s=n.data.data;if("Float64Array"===n.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===e&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===e&&!this.compat_features.OES_texture_half_float_linear){const t=n.data.size[1]*n.data.size[2]*3,e=new Uint8Array(n.data.size[0]*t);let i=new Float32Array(n.data.size[0]);for(let r=0;r<n.data.size[0];r++){let s=1e-6;for(let e=0;e<t;e++)s=Math.max(s,Math.abs(n.data.data[r*t+e]));let a=1/s;for(let i=0;i<t;i++)e[r*t+i]=Math.round(255*(n.data.data[r*t+i]*a*.5+.5));i[r]=s}s=e,r.unsigned=!0,r.scalingFactor=i}n.scalingFactor&&(r.scalingFactor=n.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,n.data.size[1],n.data.size[2],n.data.size[0],this.device.gl.RGB,s),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),i.texturePCAModels.push(r)}this.meshInfos.push(i)}this.initSkeletonStatus=e.evalSkeleton()}if(this.FrameTexture_meshColor=this.device.gl.createTexture(),!this.FrameTexture_meshColor)throw Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),t.multisample){if(this.FrameTexture_meshAlpha=this.device.gl.createTexture(),!this.FrameTexture_meshAlpha)throw Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),this.FrameBuffer_meshColor=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.FrameBuffer_meshAlpha=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha,0);const e=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,e),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);const n=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,n),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);const i=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,i),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.R8,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.RENDERBUFFER,n),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,i),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,e)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;const t=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,t),this.device.gl.renderbufferStorage(this.device.gl.RENDERBUFFER,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,t)}if(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),null===t.LUT)this.LUTTexture=null;else{if(this.LUTTexture=this.device.gl.createTexture(),!this.LUTTexture)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR),this.compat_features.OES_texture_float_linear)this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,t.LUT.data);else{const e=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3);for(let n=0;n<e.length;n++)e[n]=Math.round(255*t.LUT.data[n]);this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,e)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null}getProjMat(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())}initFrame(){this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight),this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData&&(this.charData.multisample?(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT)):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT))),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT)}renderBackground(t){this.device.gl.disable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);let e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);let n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){const n=t.fx.shadow,i=this.getBillboardShadowGeometryInfo(n.refPos,n.light,"point"===n.lightType);e+=4;for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e]=i.Mat_World2ObjImage[e][t];for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e+12]=i.Mat_ShadowImage2World[e][t];for(let t=0;t<3;t++)this._ub_shadow_fx_data[24+t]=n.tint[t];this._ub_shadow_fx_data[27]=n.intensity,this._ub_shadow_fx_data[28]=n.blurRadius,this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW)}this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.uniformMatrix2fv(this.backgroundPipelineInfo.progUniforms.u_transform_2d,!1,n?new Float32Array([1/n.scaleX,1/n.scaleY,-n.offsetX/n.scaleX,-n.offsetY/n.scaleY]):new Float32Array([1,1,0,0])),this.device.gl.uniform1ui(this.backgroundPipelineInfo.progUniforms.flags,e),this.device.gl.bindVertexArray(this.backgroundVAO),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_bg,0),null!==t.backgroundTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_bg),this.backgroundTextureSrc!==t.backgroundTexture&&(this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.backgroundTexture),this.backgroundTextureSrc=t.backgroundTexture)),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_char_body,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_char_body),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.charBodyTexture),this.charData&&(this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_color,2),this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_alpha,3),this.charData.multisample&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+3),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha))),this.device.gl.drawArrays(this.device.gl.TRIANGLES,0,6)}renderMesh(t,e){this.device.gl.enable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);const n=t.char;let i,r=new Float32Array(flatten(this.getProjMat(n.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),i=s?new Float32Array([s.scaleX,s.scaleY,s.scaleX-1+2*s.offsetX,1-s.scaleY-2*s.offsetY]):new Float32Array([1,1,0,0]);let a=n.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=a[t].apply(this.initSkeletonStatus[t].inv());o[t]=e.homogeneous_matrix()}let l=0;for(let t=0;t<Math.min(this.meshStatistics.max_bones,n.skeleton.length);t++){for(let e=0;e<4;e++)for(let n=0;n<4;n++)this._ub_rig_info_data[l+4*e+n]=o[t][n][e];l+=16}if(this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData.multisample){this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.maskPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.maskPipelineInfo.progUniforms.u_proj_mat,!0,r),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,i);for(let t=0;t<n.mesh.length;t++)if(n.mesh[t].genMask){const i=this.meshInfos[t];if(n.mesh[t].blendshapes.size[2]>0){l=16*this.meshStatistics.max_bones;let i=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let r=0;r<i;r++)this._ub_rig_info_data[l+r]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[r]];for(let t=i;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let r=0;n.mesh[t].opacity&&(r+=1);for(const t in i.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[t],i.uniformUInts[t]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,r),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,i.buffers.ub_rig_info),this.device.gl.bindVertexArray(i.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.uniform1i(this.maskPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)}this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.meshPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.meshPipelineInfo.progUniforms.u_proj_mat,!0,r),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,i);let h=!0;for(let t=0;t<n.mesh.length;t++){const i=this.meshInfos[t];let r=i.texturePCAModels[e.data.mesh[t].textureModelIndex];if(n.mesh[t].blendshapes.size[0]>0){l=16*this.meshStatistics.max_bones;let i=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let r=0;r<i;r++)this._ub_rig_info_data[l+r]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[r]];for(let t=i;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let s=0;n.mesh[t].opacity&&(s+=1),null!==this.LUTTexture&&(s+=2),r.unsigned&&(s+=4),h!=n.mesh[t].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!n.mesh[t].genMask),h=n.mesh[t].genMask);for(const t in i.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[t],i.uniformUInts[t]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,s),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_gamma,this.currentGamma.r,this.currentGamma.g,this.currentGamma.b),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_color_balance,this.currentColorBalance.rc,this.currentColorBalance.gm,this.currentColorBalance.by),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,i.buffers.ub_rig_info);let a=Math.min(e.data.mesh[t].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(let n=1;n<a;n++)this._ub_pca_info_data[n]=e.data.mesh[t].texturePCAWeights[n-1];if(r.scalingFactor)for(let t=0;t<a;t++)this._ub_pca_info_data[t]*=r.scalingFactor[t];for(let t=a;t<this.meshStatistics.max_pca_component_count;t++)this._ub_pca_info_data[t]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_pca_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,1,i.buffers.ub_pca_info),this.device.gl.bindVertexArray(i.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),r.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,r.texture),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_lut,2),this.LUTTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture)),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}h||this.device.gl.colorMask(!0,!0,!0,!0),this.charData.multisample&&(this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)}constructor(t,e){this.compat_features={},this.charData=null,this.backgroundBuffers={},this.backgroundTextures={},this.backgroundTextureSrc=null,this.meshPipelineInfo=null,this.maskPipelineInfo=null,this.meshInfos=[],this.meshStatistics={max_pca_component_count:4,max_bs_count:4,max_bones:1},this.FrameTexture_meshColor=null,this.FrameTexture_meshAlpha=null,this.LUTTexture=null,this.FrameBuffer_mesh=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null,this.initSkeletonStatus=[],this.frameDataCallback=()=>null,this.currentGamma={r:1,g:1,b:1},this.currentColorBalance={rc:0,gm:0,by:0},this._ub_shadow_fx_data=null,this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,this.sendSdkPoint=()=>{},this.device=t,this.sendSdkPoint=e,this.reinitialize()}reinitialize(){this.compat_features={},this.compat_features.OES_texture_float_linear=this.device.gl.getExtension("OES_texture_float_linear"),this.compat_features.OES_texture_half_float_linear=this.device.gl.getExtension("OES_texture_half_float_linear"),this.assembleBackgroundPipeline(),this.charData&&this.assembleMeshPipelines(this.charData)}setSyncMedia(t){this.device.run(t=>this.render(),t)}setCharData(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null}setFrameDataCallback(t){this.frameDataCallback=t}setGamma(t,e,n){this.currentGamma={r:t,g:e,b:n}}setColorBalance(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}}getBillboardTransform2D(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};{const n=this.getProjMat(this.charData.char.cameraConfig),i=inv4(n),r=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=r[3][0]/r[3][1],a=[i[0][0]-e[0]*i[3][0],i[1][0]-e[1]*i[3][0],i[2][0]-e[2]*i[3][0]],o=[i[0][1]-t[0]*i[3][1],i[1][1]-t[1]*i[3][1],i[2][1]-t[2]*i[3][1]],l=[i[0][1]-e[0]*i[3][1],i[1][1]-e[1]*i[3][1],i[2][1]-e[2]*i[3][1]],h=s*Math.sqrt([i[0][0]-t[0]*i[3][0],i[1][0]-t[1]*i[3][0],i[2][0]-t[2]*i[3][0]].reduce((t,e)=>t+e*e,0)/a.reduce((t,e)=>t+e*e,0)),d=s*Math.sqrt(o.reduce((t,e)=>t+e*e,0)/l.reduce((t,e)=>t+e*e,0));return{offsetX:.5*(r[0][1]/r[3][1]-r[0][0]/r[3][0]-(h-1)),offsetY:.5*(1-d-(r[1][1]/r[3][1]-r[1][0]/r[3][0])),scaleX:h,scaleY:d}}}getBillboardShadowGeometryInfo(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};{const i=this.getProjMat(this.charData.char.cameraConfig),r=inv4(i),s=[[1,0,0],[0,t[1],1],[0,0,0]],a=[[1,0,0],[0,t[2],1],[0,0,0]];n?(s[2]=[e[0],e[1],1],a[2]=[t[0],-e[2],0]):(s[2]=[e[0],e[1],0],a[2]=[0,-e[2],0]);const o=transpose(mmul(inv3(a),s)),l=mvmul(i,[t[0],t[1],t[2],1]),h=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[i[0][0],i[0][2],i[0][1]*t[1]+i[0][3]],[i[1][0],i[1][2],i[1][1]*t[1]+i[1][3]],[i[3][0],i[3][2],i[3][1]*t[1]+i[3][3]]])),Mat_World2ObjImage:inv3([[r[0][0],r[0][1],r[0][2]*h+r[0][3]],[r[1][0],r[1][1],r[1][2]*h+r[1][3]],[r[3][0],r[3][1],r[3][2]*h+r[3][3]]])}}}render(){var t;const e=this.frameDataCallback();null!==e&&(this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==e.data?this.renderMesh(this.charData,e):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)),this.renderBackground(e),null!==e.onPostRender&&e.onPostRender(this)),null==(t=this.device.gl)||t.flush()}renderFrame(t){this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==t.data&&this.renderMesh(this.charData,t),this.renderBackground(t),this.first_webgl_render&&(window.performanceTracker.markEnd(performanceConstant.first_render),window.performanceTracker.markEnd(performanceConstant.first_webgl_render),this.first_webgl_render=!1,this.sendSdkPoint("render_success_time",{timestamp:Date.now()})),this.device.gl.flush()}destroy(){var t,e,n,i;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(t=>{t.VAO&&this.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(t=>{t&&this.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(t=>{t&&this.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(t=>{t.texture&&this.device.gl.deleteTexture(t.texture)})}),this.meshInfos=[]),this.FrameBuffer_MSAA&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_MSAA),this.FrameBuffer_MSAA=null),this.FrameBuffer_meshColor&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshColor),this.FrameBuffer_meshColor=null),this.FrameBuffer_meshAlpha&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshAlpha),this.FrameBuffer_meshAlpha=null),this.FrameTexture_meshColor&&(this.device.gl.deleteTexture(this.FrameTexture_meshColor),this.FrameTexture_meshColor=null),this.FrameTexture_meshAlpha&&(this.device.gl.deleteTexture(this.FrameTexture_meshAlpha),this.FrameTexture_meshAlpha=null),this.LUTTexture&&(this.device.gl.deleteTexture(this.LUTTexture),this.LUTTexture=null),null!=(n=this.meshPipelineInfo)&&n.program&&(this.device.gl.deleteProgram(this.meshPipelineInfo.program),this.meshPipelineInfo.program=null),null!=(i=this.maskPipelineInfo)&&i.program&&(this.device.gl.deleteProgram(this.maskPipelineInfo.program),this.maskPipelineInfo.program=null)),this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,null==(t=(e=this.device).destroy)||t.call(e)}}const containerWidgetMaps=new Map;let containerIdCounter=0;function getContainerElement(t){return t&&t.el&&t.el instanceof HTMLElement?t.el:null}function getContainerId(t){if(t.id)return t.id;const e=t.getAttribute("data-widget-container-id");if(e)return e;const n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){const e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}const subtitleStyle="bottom: 50px;\nleft: 50%;\ntransform: translateX(-50%);\nbackground: rgba(0, 0, 0, 0.8);\ncolor: white;\npadding: 12px 20px;\nborder-radius: 8px;\nfont-size: 16px;\nfont-weight: 500;\nz-index: 1000;\nmax-width: 80%;\nmin-width: 200px;\nword-break: break-word;\nbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\ntext-align: center;",WidgetDefaultRenderer={_el(t){const{axis_id:e,x_location:n,y_location:i,width:r,height:s}=t,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");let o="position:absolute;";return o+=void 0!==e?`z-index:${e};`:"z-index:1;",void 0!==n&&void 0!==i&&(o+=`top:${100*i}%;left:${100*n}%;`),void 0!==r&&void 0!==s&&(o+=`width:${100*r}%;height:${100*s}%;`),a.setAttribute("style",o),a},_getWidgetKey:(t,e)=>`${t}-${null!=e?e:"default"}`,_replaceWidget(t,e,n,i){const r=this._getWidgetKey(t,e),s=getContainerElement(i||this._currentInstance);if(!s)return;const a=getContainerWidgetMap(s);if(a.has(r)){const t=a.get(r);t&&t.parentNode&&t.remove()}a.set(r,n)},WIDGET_PIC(t,e){const n=this._el(t),i=document.createElement("img");return i.crossOrigin="anonymous",i.setAttribute("style","width:100%;height:100%;"),i.src=t.image,n.appendChild(i),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE(t,e){const{type:n,text:i,axis_id:r}=t,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){const t=getContainerWidgetMap(s),e=this._getWidgetKey("WIDGET_SUBTITLE",r);if(t.has(e)){const n=t.get(e);n&&n.parentNode&&n.remove(),t.delete(e)}}return null}const a=this._el(t);return a.innerHTML=i,a.setAttribute("style",a.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",r,a,e),a},destroy(t){const e=getContainerElement(t||this._currentInstance);if(e){const t=getContainerId(e);if(containerWidgetMaps.has(t)){const e=containerWidgetMaps.get(t);e.forEach((t,e)=>{(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),e.clear(),containerWidgetMaps.delete(t)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(t=>{t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=[0,0,0];for(let e=0;e<3;e++)n[e]=t.dataview.getUint8(t.offset),t.offset+=1;const i=e.split(".").map(t=>parseInt(t));if(i[0]<n[0])throw new Error(`Data version (${n[0]}.${n[1]}.${n[2]}) is incompatible with the version of current data interface (${i[0]}.${i[1]}.${i[2]}).`);return n}function decodeStr(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset);let n=0;for(;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;const i=e.slice(0,n);return new TextDecoder("utf-8").decode(i)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=0,n=0;for(;;){let i=t.dataview.getUint8(t.offset);t.offset++;let r=e|(127&i)<<n;if(r<e)throw new Error("Integer too large to decode.");if(e=r,!(128&i))break;n+=7}return e}const TensorDataTypeMap={B:Uint8Array,b:Int8Array,H:Uint16Array,h:Int16Array,I:Uint32Array,i:Int32Array,L:BigUint64Array,l:BigInt64Array,f:Float32Array,d:Float64Array};"undefined"!=typeof Float16Array&&(TensorDataTypeMap.e=Float16Array);class Tensor{constructor(t,e){this.size=t,this.data=e}itemSize(){let t=1;for(let e of this.size)t*=e;return t}byteSize(){return this.itemSize()*this.data.BYTES_PER_ELEMENT}static zeros(t,e=Float32Array){let n=1;for(let e=0;e<t.length;e++)n*=t[e];const i=new e(n);for(let t=0;t<n;t++)i[t]=0;return new Tensor(t,i)}part(...t){if(t.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");let e=[],n=1;for(let i=t.length;i<this.size.length;i++)e.push(this.size[i]),n*=this.size[i];let i=0;t.length>0&&(i+=t[0]);for(let e=1;e<t.length;e++)i*=this.size[e],i+=t[e];return i*=n,new Tensor(e,this.data.slice(i,i+n))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=t.dataview.getUint8(t.offset);t.offset++;const n=new Array(e);let i=1;for(let r=0;r<e;r++)n[r]=decodeLongInt(t),i*=n[r];const r=String.fromCodePoint(t.dataview.getUint8(t.offset));t.offset++;const s=TensorDataTypeMap[r];if(void 0===s)throw new Error(`Unsupported tensor element type "${r}".`);const a=i*s.BYTES_PER_ELEMENT,o=new s(t.dataview.buffer.slice(t.offset,t.offset+a));return t.offset+=a,new Tensor(n,o)}}function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[null];for(;;){const n=decodeStr(t);if(""==n)break;{let i=null;if("text/plain;charset=UTF-8"===n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e,i=new TextDecoder("utf-8").decode(n)}else if("application/json;charset=UTF-8"==n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e;const r=new TextDecoder("utf-8");i=JSON.parse(r.decode(n))}else if("application/octet-stream"===n)i=Tensor.deserialize(t);else{const e=decodeLongInt(t),r=t.dataview.buffer.slice(t.offset,t.offset+e);t.offset+=e,i=new Blob([r],{type:n})}e.push(i)}}return e}class CameraConfig{constructor(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}getIntrinsicMatrix(t){const[e,n]=t;let i=25.4*this.filmAperture[0];return[[this.focalLength/(i/e),0,t[0]/2],[0,this.focalLength/(i*t[1]/t[0]/n),t[1]/2],[0,0,1]]}getProjMatrix(t,e=.01,n=Infinity){const[i,r]=t,s=this.getIntrinsicMatrix(t);let a,o;return Infinity===n?(a=-1,o=-2*e):(a=-(n+e)/(n-e),o=-2*n*e/(n-e)),[[2*s[0][0]/i,0,(i-2*s[0][2])/i,0],[0,2*s[1][1]/r,(r-2*s[1][2])/r,0],[0,0,a,o],[0,0,-1,0]]}getExtrinsicMatrix(){const t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(e=>e*t),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(t=>-t)))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=new CameraConfig;e.focalLength=t.dataview.getFloat32(t.offset,!0);for(let n=0;n<2;n++)e.filmAperture[n]=t.dataview.getFloat32(t.offset+4*(n+1),!0);for(let n=0;n<3;n++)e.translation[n]=t.dataview.getFloat32(t.offset+4*(n+3),!0);for(let n=0;n<3;n++)e.rotation[n]=t.dataview.getFloat32(t.offset+4*(n+6),!0);return t.offset+=36,e}}class RigidTransform{constructor(t=[0,0,0],e=[1,0,0,0]){this.translation=t,this.rotQuaternion=e}apply(t){if(t instanceof RigidTransform){let e=quaternion_mul(this.rotQuaternion,t.rotQuaternion);e=normalize(e);let n=mvmul(quaternion_to_mat(this.rotQuaternion),t.translation);for(let t=0;t<3;t++)n[t]+=this.translation[t];return new RigidTransform(n,e)}{let e=mvmul(this.matrix(),t);for(let t=0;t<3;t++)e[t]+=this.translation[t];return e}}inv(){let t=quaternion_conj(this.rotQuaternion),e=mvmul(quaternion_to_mat(t),this.translation.map(t=>-t));return new RigidTransform(e,t)}matrix(){return quaternion_to_mat(this.rotQuaternion)}homogeneous_matrix(){return make_homogeneous(this.matrix(),this.translation)}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[0,0,0],n=[1,0,0,0];for(let n=0;n<3;n++)e[n]=t.dataview.getFloat32(t.offset+4*n,!0);let i=0;for(let e=0;e<3;e++)n[e+1]=t.dataview.getFloat32(t.offset+4*(e+3),!0),i+=n[e+1]*n[e+1];return n[0]=Math.sqrt(Math.max(1-i,0)),t.offset+=24,new RigidTransform(e,n)}}class IBRMeshInfo{constructor(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){let n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;let i=[],r=[],s=!0;for(;;){let e=decodeLongInt(t);if(0===e){if(!s)break}else i.push(e-1);s=!1;let n=[],a=!0,o=0;for(;;){let e=decodeLongInt(t);if(a)for(let t=0;t<e;t++)n.push(o+t);if(a=!a,o+=e,0===e&&o>0)break}r.push(n)}let a=r[0].length;this.blendshapeIndices=i;let o=e.archivedItems[decodeLongInt(t)],l=Tensor.zeros([a,o.size[1]],o.data.constructor),h=Tensor.zeros([a,o.size[1],this.blendshapeIndices.length],o.data.constructor),d=0;const c=r[0];for(let t of c){for(let e=0;e<o.size[1];e++)l.data[t*o.size[1]+e]=o.data[d*o.size[1]+e];d++}const u=this.blendshapeIndices.length;for(let t=1;t<r.length;t++){const e=r[t];for(let n of e){for(let e=0;e<o.size[1];e++)h.data[(n*o.size[1]+e)*u+t-1]=o.data[d*o.size[1]+e];d++}}this.vertices=l,this.blendshapes=h,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(a*e.maxJointsPerVertex),this.jointWeight=new Float32Array(a*e.maxJointsPerVertex);for(let n=0;n<a;n++){for(let i=0;i<e.maxJointsPerVertex;i++)this.jointIndex[n*e.maxJointsPerVertex+i]=t.dataview.getUint8(t.offset),t.offset+=1;for(let i=0;i<e.maxJointsPerVertex;i++)this.jointWeight[n*e.maxJointsPerVertex+i]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const f=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(f);for(let n=0;n<f;n++)this.textureModels[n]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;let n=t.dataview.getUint16(t.offset,!0);t.offset+=2;const i=new Float32Array(n);for(let e=0;e<n;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([n],i);let r=t.dataview.getUint16(t.offset,!0);t.offset+=2;const s=new Uint16Array(3*r);for(let e=0;e<r;e++)for(let n=0;n<3;n++)s[3*e+n]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([r,3],s);const a=new Float32Array(2*n);for(let e=0;e<n;e++)for(let n=0;n<2;n++)a[2*e+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([n,2],a);const o=t.dataview.getUint16(t.offset,!0);t.offset+=2;const l=new Float32Array(3*n);for(let e=0;e<3*n;e++)l[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;const h=new Float32Array((o-1)*n*3);for(let e=0;e<o-1;e++)for(let i=0;i<3*n;i++)h[i*(o-1)+e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([n,3],l),this.blendshapes=new Tensor([n,3,o-1],h),this.blendshapeIndices=[];for(let t of e.blendshapeIndices)this.blendshapeIndices.push(t);this.jointIndex=new Uint8Array(n*e.maxJointsPerVertex),this.jointWeight=new Float32Array(n*e.maxJointsPerVertex);for(let i=0;i<n;i++){for(let n=0;n<e.maxJointsPerVertex;n++)this.jointIndex[i*e.maxJointsPerVertex+n]=t.dataview.getUint8(t.offset),t.offset+=1;for(let n=0;n<e.maxJointsPerVertex;n++)this.jointWeight[i*e.maxJointsPerVertex+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const d=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(d);for(let e=0;e<d;e++){const n=[0,0,0,3];for(let e=0;e<3;e++)n[e]=t.dataview.getUint16(t.offset,!0),t.offset+=2;const i=new Float32Array(n[0]*n[1]*n[2]*3);for(let e=0;e<i.length;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[e]={data:new Tensor(n,i)}}}}}class IBRMeshFrameInfo{constructor(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}static deserialize(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let n=t.dataview.getUint8(t.offset);t.offset+=1;let i=new Float32Array(e.textureModels[n].data.size[0]-1);for(let e=0;e<i.length;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;return new IBRMeshFrameInfo(n,i)}}class IBRAnimationGeneratorCharInfo_NN{constructor(t,e={}){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__);let i=[];if(n[0]>2&&(i=loadArchives(t)),this.cameraConfig=CameraConfig.deserialize(t),n[0]>2)this.blendshapeCount=decodeLongInt(t);else{if(!e.blendshapeMap)throw new Error("A blendshape map is required to load the character information of v2.0 format.");let t=new Set;for(const n of e.blendshapeMap)for(const e of n)t.add(e);this.blendshapeCount=t.size}let r=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Array(s);for(let e=0;e<s;e++)a[e]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=a,this.skeleton=new Array(r);for(let e=0;e<r;e++){let n=t.dataview.getUint8(t.offset);n>=this.skeleton.length&&(n=null),t.offset+=1;let i=RigidTransform.deserialize(t);this.skeleton[e]={parent:n,local_transform:i}}this.jointEvalOrder=new Array(r);for(let e=0;e<r;e++)this.jointEvalOrder[e]=t.dataview.getUint8(t.offset),t.offset+=1;let o={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(o.archivedItems=i);let l=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(l);for(let i=0;i<l;i++)n[0]<=2&&(o.blendshapeIndices=e.blendshapeMap[i]),this.mesh[i]=new IBRMeshInfo(t,o)}evalSkeleton(){let t=Array(this.skeleton.length);for(let e of this.jointEvalOrder)t[e]=null==this.skeleton[e].parent?this.skeleton[e].local_transform:t[this.skeleton[e].parent].apply(this.skeleton[e].local_transform);return t}evalSkeletonFromMovable(t){let e=Array(this.skeleton.length);for(let n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(let t of this.jointEvalOrder)null!=this.skeleton[t].parent&&(e[t]=e[this.skeleton[t].parent].apply(this.skeleton[t].local_transform));return e}}class IBRAnimationFrameData_NN{constructor(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}static deserialize(t,e,n){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let i=new IBRAnimationFrameData_NN;const r=e.mesh.length;if(i.mesh=new Array(r),i.blendshapeWeights=new Float32Array(e.blendshapeCount),n[0]>2){for(let n=0;n<r;n++)i.mesh[n]=IBRMeshFrameInfo.deserialize(t,e.mesh[n]);for(let e=0;e<i.blendshapeWeights.length;e++)i.blendshapeWeights[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}else for(let n=0;n<r;n++){const r=e.mesh[n].blendshapeIndices;for(let e=0;e+1<r.length;e++)i.blendshapeWeights[r[e+1]-1]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Float32Array(e.mesh[n].textureModels[s].data.size[0]-1);for(let e=0;e<a.length;e++)a[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;i.mesh[n]=new IBRMeshFrameInfo(s,a)}i.movableJointTransforms=new Array(e.movableJoints.length);for(let n=0;n<e.movableJoints.length;n++)i.movableJointTransforms[n]=RigidTransform.deserialize(t);return i}static interp(t,e,n,i,r){let s=new IBRAnimationFrameData_NN;s.blendshapeWeights=new Float32Array(t.blendshapeWeights.length);for(let n=0;n<s.blendshapeWeights.length;n++)s.blendshapeWeights[n]=i*e.blendshapeWeights[n]+(1-i)*t.blendshapeWeights[n];s.mesh=[];for(let n=0;n<t.mesh.length;n++){let r=new IBRMeshFrameInfo(t.mesh[n].textureModelIndex,new Float32Array(t.mesh[n].texturePCAWeights.length));for(let s=0;s<t.mesh[n].texturePCAWeights.length;s++)r.texturePCAWeights[s]=i*e.mesh[n].texturePCAWeights[s]+(1-i)*t.mesh[n].texturePCAWeights[s];s.mesh.push(r)}s.movableJointTransforms=new Array(n.movableJointTransforms.length);for(let t=0;t<n.movableJointTransforms.length;t++){let e=!0;for(let[n,i]of r)if(n===t){e=!1;break}e&&(s.movableJointTransforms[t]=n.movableJointTransforms[t])}for(let[a,o]of r){let r=t.movableJointTransforms[o].inv().apply(t.movableJointTransforms[a]),l=e.movableJointTransforms[o].inv().apply(e.movableJointTransforms[a]),h=[],d=[];for(let t=0;t<3;t++)h.push(i*l.translation[t]+(1-i)*r.translation[t]);for(let t=0;t<4;t++)d.push(i*l.rotQuaternion[t]+(1-i)*r.rotQuaternion[t]);d=normalize(d);let c=new RigidTransform(h,d);c=n.movableJointTransforms[o].apply(c),s.movableJointTransforms[a]=c}return s}}function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__),i=t.dataview.getUint32(t.offset,!0);t.offset+=4;let r=Array(i);for(let s=0;s<i;s++)r[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return r}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){const t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),i=/Google Inc/.test(e),r=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(i||r)&&s}function getStyleStr(t){return Object.entries(t).map(([t,e])=>{const n="number"==typeof e?e.toString():e;return`${t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}:${n};`}).join("")}function updateCanvasXOffset(t,e){const n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+` translateX(${e}px)`;t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){const t=`${screen.width}x${screen.height}`,e=navigator.userAgent,n=navigator.language,i=Intl.DateTimeFormat().resolvedOptions().timeZone,r=encodeURIComponent(`${t}|${e}|${n}|${i}`);return btoa(r)}function getDeviceInfo(){const t=navigator.userAgent;let e="Unknown Brand",n="Unknown Model",i="Unknown Version",r="Unknown Browser",s="Unknown Version";const a=t.match(/Windows NT (\d+\.\d+)/),o=t.match(/Android (\d+\.\d+(\.\d+)?)/),l=t.match(/OS (\d+_\d+(\._\d+)?) like Mac OS X/);a?i=`Windows NT ${a[1]}`:o?i=`Android ${o[1]}`:l?i=`iOS ${l[1].replace(/_/g,".")}`:t.includes("Macintosh")?i="Macintosh":t.includes("Linux")&&(i="Linux"),t.includes("iPhone")||t.includes("iPad")||t.includes("iPod")?(e="Apple",t.includes("iPhone")?n="iPhone":t.includes("iPad")?n="iPad":t.includes("iPod")&&(n="iPod")):t.includes("Android")?(e="Android",n="Android"):t.includes("Windows")?(e="Windows",n=t.includes("Windows Phone")?"Windows Phone":"Windows Desktop"):t.includes("Linux")&&(e="Linux",n="Linux");const h=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),d=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),c=t.match(/Firefox\/(\d+\.\d+(\.\d+)?)\b/),u=t.match(/Edg\/(\d+\.\d+\.\d+\.\d+)/),f=t.match(/Opera\/(\d+\.\d+)/),p=t.match(/MSIE (\d+\.\d+)/);return h?(r="Chrome",s=h[1]):d?(r="Safari",s=d[1]):c?(r="Firefox",s=c[1]):u?(r="Edge",s=u[1]):f?(r="Opera",s=f[1]):p&&(r="IE",s=p[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:i,browser:r,browser_version:s,browser_ua:t}}function validateScaleWithDecimal(t,e){var n;return"number"==typeof t||"string"==typeof t&&(/^\d+(\.\d+)?vh$/.test(t)||/^\d+(\.\d+)?$/.test(t))?t:(null==(n=window.avatarSDKLogger)||n.warn(e,'scale 必须是数字、带小数的数字字符串或者"xxxvh"格式(xxx为数字/小数)'),1)}function isharmony(){const t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}class AvatarRender{constructor(t){this.TAG="[AvatarRender]",this.canvas=document.createElement("canvas"),this.currentBodyFrame=null,this.lastFaceFrame=null,this.isInit=!1,this.isFirstRender=!0,this.lastFrameState="",this.lastRenderState=RenderState.init,this.onStateChange=()=>{},this.onRenderChange=()=>{},this.sendVideoInfo=()=>{},this.lostHandler=()=>{},this.restoreHandler=()=>{},this.avatarCanvasVisible=!0,this.lastRealFaceFrameData=null,this.lastRealFaceFrame=-1,this.lastWeight=0,this.lastFrameIndex=-1,this.canvasOffsetX=-1,this.baseWalkOffset=0,this.lastBodyOffset=0,this.pendingCharData=null,this.interrupt=!1,this.walkConfig=null,this.layout=null,this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.maxLostFrameCount=300,this.forceSyncDecoder=()=>{},this.createPipelineLock=!1,this.restoreTimeout=null,this.isRecovering=!1,this.recoverStartTime=0,this.recoveryStage="light",this.recoveryMaxAttempts={light:2,medium:3,full:2},this.recoveryBaseDelays={light:300,medium:4e3,full:5e3},this.recoveryMaxDelay=3e4,this.currentStageAttempts=0,this.isUsingReducedResolution=!1,this.resolutionRestoreTimer=null,this.RESOLUTION_RESTORE_DELAY=3e4,this.scale=1,this.sendSdkPoint=()=>{},this.options=t,this.onDownloadProgress=t.onDownloadProgress,this.onStateChange=t.onStateChange,this.onRenderChange=t.onRenderChange,this.sendVideoInfo=t.sendVideoInfo,this.saveAndDownload=t.saveAndDownload,this.forceSyncDecoder=t.forceSyncDecoder,this.lostHandler=this._lostHandler.bind(this),this.restoreHandler=this._restoreHandler.bind(this),this.setCanvasVisibility(this.avatarCanvasVisible),this.sendSdkPoint=t.sendSdkPoint,this.device=null,this.pipeline=null,this.copyCanvas=document.createElement("canvas"),this.copyCtx=this.copyCanvas.getContext("2d")}resetFaceFrameState(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")}createPipeline(){this.pipeline||!this.device||this.createPipelineLock||(this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()))}_lostHandler(t){if(t.preventDefault(),window.avatarSDKLogger.error("Context lost.",t),this.device)try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler)}catch(t){}if(this.device)try{this.device.destroy()}catch(t){}if(this.pipeline)try{this.pipeline.destroy()}catch(t){}this.device=null,this.pipeline=null,this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_LOST,message:"Context lost.",e:{event:t,timestamp:Date.now()}}),this.isRecovering?window.avatarSDKLogger.warn("Context recovery already in progress, skipping."):(this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null,window.avatarSDKLogger.log("[Recovery] Cancelled resolution restore due to context loss")),this.isRecovering=!0,this.recoverStartTime=Date.now(),this.recoveryStage="light",this.currentStageAttempts=0,this._scheduleNextAttempt())}_restoreHandler(t){this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering?window.avatarSDKLogger.warn("Context restore event received during recovery, skipping duplicate recovery."):(this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RESTORED,message:"Context restored event received.",e:{event:t,timestamp:Date.now()}}),this.isRecovering=!0,this.recoveryStage="light",this.currentStageAttempts=0,this._recoverContext())}_recoverContext(){if(this.device&&this.pipeline&&this.device.gl&&!this.device.gl.isContextLost())return window.avatarSDKLogger.log("[Recovery] Already recovered, skipping."),void(this.isRecovering=!1);window.avatarSDKLogger.log(`[Recovery] stage=${this.recoveryStage}, attempt=${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[this.recoveryStage]}`),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null);let t=!1;try{switch(this.recoveryStage){case"light":t=this._tryLightRecovery();break;case"medium":t=this._tryMediumRecovery();break;case"full":t=this._tryFullRecovery()}}catch(t){window.avatarSDKLogger.error(`[Recovery] stage=${this.recoveryStage} threw:`,t)}t?this._onRecoverySuccess():(this.currentStageAttempts++,this.isRecovering=!1,this.currentStageAttempts<this.recoveryMaxAttempts[this.recoveryStage]?this._scheduleNextAttempt():this._advanceStage())}_tryLightRecovery(){try{if(window.avatarSDKLogger.log("[Recovery] Trying light recovery (reuse canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after light recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Light recovery failed:",t),this._reportRecoveryFailure("light",t),!1}}_tryMediumRecovery(){try{var t;if(window.avatarSDKLogger.log("[Recovery] Trying medium recovery (replace canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after medium recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Medium recovery failed:",t),this._reportRecoveryFailure("medium",t),!1}}_tryFullRecovery(){try{var t,e,n;if(window.avatarSDKLogger.log("[Recovery] Trying full recovery (reduced resolution)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,l=.75,h=Math.round((null!=(e=null==o?void 0:o.width)?e:1080)*l),d=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=h,a.height=d,a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,window.avatarSDKLogger.log(`[Recovery] Using reduced resolution: ${h}x${d} (scale=${l})`),this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after full recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Full recovery failed:",t),this._reportRecoveryFailure("full",t),!1}}_onRecoverySuccess(){const t=Date.now()-this.recoverStartTime,e="full"===this.recoveryStage;window.avatarSDKLogger.log(`[Recovery] Success! stage=${this.recoveryStage}, time=${t}ms${e?" (reduced resolution)":""}`),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERED,message:`Context recovered via ${this.recoveryStage} recovery in ${t}ms.`,e:{timestamp:Date.now(),recoveryTime:t,stage:this.recoveryStage,attempts:this.currentStageAttempts+1,reducedResolution:e}}),e&&(this.isUsingReducedResolution=!0,this._scheduleResolutionRestore()),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0}_scheduleResolutionRestore(){this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log(`[Recovery] Scheduling resolution restore in ${this.RESOLUTION_RESTORE_DELAY}ms`),this.resolutionRestoreTimer=setTimeout(()=>{this._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)}_restoreOriginalResolution(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");const i=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,r=null!=(e=null==i?void 0:i.width)?e:1080,s=null!=(n=null==i?void 0:i.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=r,l.height=s,l.setAttribute("style",a),o&&o.replaceChild(l,this.canvas),this.canvas=l,this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("Context lost after resolution restore");this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isUsingReducedResolution=!1,window.avatarSDKLogger.log(`[Recovery] Resolution restored to ${r}x${s}`),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:`Resolution restored to ${r}x${s}.`,e:{timestamp:Date.now(),resolution:{width:r,height:s}}})}catch(t){window.avatarSDKLogger.warn("[Recovery] Failed to restore resolution, keeping reduced:",t)}finally{this.resolutionRestoreTimer=null}else window.avatarSDKLogger.warn("[Recovery] Cannot restore resolution: not in reduced mode or context lost")}_advanceStage(){const t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){const n=t[e+1];window.avatarSDKLogger.log(`[Recovery] Stage "${this.recoveryStage}" exhausted, upgrading to "${n}"`),this.recoveryStage=n,this.currentStageAttempts=0,this._scheduleNextAttempt()}else window.avatarSDKLogger.error("[Recovery] All recovery stages exhausted. Giving up."),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS,message:"All WebGL recovery stages exhausted. SDK restart required.",e:{timestamp:Date.now(),elapsedTime:Date.now()-this.recoverStartTime,stagesAttempted:{light:this.recoveryMaxAttempts.light,medium:this.recoveryMaxAttempts.medium,full:this.recoveryMaxAttempts.full}}}),this.isRecovering=!1}_scheduleNextAttempt(){const t=this.recoveryBaseDelays[this.recoveryStage],e=this.recoveryMaxAttempts[this.recoveryStage],n=t*Math.pow(2,this.currentStageAttempts),i=Math.min(n,this.recoveryMaxDelay);window.avatarSDKLogger.log(`[Recovery] Scheduling ${this.recoveryStage} attempt ${this.currentStageAttempts+1}/${e} in ${i}ms (base=${t}ms, exp=${n}ms)`),this.restoreTimeout=setTimeout(()=>{this.isRecovering=!0,this._recoverContext()},i)}_reportRecoveryFailure(t,e){this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_FAILED,message:`[${t}] recovery attempt ${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[t]} failed.`,e:{error:e,stage:t,attempt:this.currentStageAttempts+1,timestamp:Date.now()}})}init(t){var e,n,i,r,s;let a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(i=null==(r=this.options.resourceManager.getConfig())||null==(r=r.resolution)?void 0:r.height)?i:1920),this.setCharacterCanvasAnchor(),null!=(s=a)&&s.char||(a={char:this.options.resourceManager.getMouthShapeLib().char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4}),this.pendingCharData=a,this.isInit=!0,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),this.createPipeline()}style(t=0,e=0){t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)}setCanvasStyle(t){var e,n,i,r,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;const h=null!=(e=null!=(n=null==(i=this.walkConfig)?void 0:i.init_point)?n:null==(r=this.options.resourceManager.getConfig())||null==(r=r.walk_config)?void 0:r.init_point)?e:null,{width:d=1080,height:c=1920}=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},[u,f]=null!=(o=null==(l=t.container)?void 0:l.size)?o:[d,c];let{v_align:p="center",h_align:_="center",scale:m=1,offset_x:g=0,offset_y:y=0}=t.avatar||{};if(null!=h&&(_="left",g=0),"string"==typeof m&&m.includes("vh")){const t=parseFloat(m.replace("vh",""));m=isNaN(t)?1:t/100*f/c}this.scale=Number(m);const v=c*Number(m),b=d*Number(m),S=b/2,E=v/2,w={position:"absolute",zIndex:100,height:`${v}px`,width:`${b}px`,objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(_){case"left":w.left=null!=h?h-S+"px":"0",w.marginLeft=`${g}px`;break;case"right":w.right=`-${S}px`,w.marginLeft=`${g}px`;break;default:w.position="absolute",w.left="50%",w.marginLeft=`${-S+g}px`}switch(p){case"top":w.top="0",w.marginTop=`${y}px`;break;case"bottom":w.bottom="0",w.marginTop=`${y}px`;break;default:w.position="absolute",w.top="50%",w.marginTop=`${-E+y}px`}const x=getStyleStr(w);this.canvas.setAttribute("style",x)}setWalkConfig(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)}setCharacterCanvasAnchor(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n;const t=(null==(n=this.options.resourceManager.getConfig())?void 0:n.layout)||{avatar:{v_align:"default",h_align:"default",scale:1,offset_x:0,offset_y:0}};this.setCanvasStyle(t)}else{var i;const t=getStyleStr({position:"absolute",zIndex:100,height:"100%",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0"});this.canvas.setAttribute("style",t);const e=(null==(i=this.options.resourceManager.getConfig())||null==(i=i.init_events)?void 0:i.find(t=>"SetCharacterCanvasAnchor"===t.type))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1},{x_location:n,y_location:r,width:s,height:a}=e;this.canvas.setAttribute("style",this.canvas.style.cssText+`left: calc(${n} * 100%); top: calc(${r} * 100%); transform: scale(${s}, ${a}); transform-origin: top left;`)}}computeWeight(t){const e=t-this.lastFrameIndex;return this.lastWeight=t>this.lastRealFaceFrame?Math.min(this.lastWeight+e,12):Math.max(this.lastWeight-e,0),this.lastWeight/12}render(t){var e,n,i,r,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};const l=this.options.dataCacheQueue._getBodyImageBitmap(t);let h=this.options.dataCacheQueue._getFaceImageBitmap(t,null!=(e=null!=(n=null==l?void 0:l.body_id)?n:null==l?void 0:l.id)?e:0),d=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(i=null!=(r=null==l?void 0:l.body_id)?r:null==l?void 0:l.id)?i:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)h=d;else if(null!=(s=h)&&s.FaceFrameData&&null!=(a=h)&&a.face_frame_type){if(this.lastRealFaceFrameData=h.FaceFrameData,this.lastRealFaceFrame=t,-1!==this.lastRealFaceFrame&&this.lastWeight>0&&d){var c,u;const e=this.computeWeight(t);h={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(c=h)?void 0:c.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)h=d;else if(null!=d&&d.FaceFrameData)if(null===this.lastRealFaceFrameData)h=d;else{var f,p;const e=this.computeWeight(t);h={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(f=h)?void 0:f.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(p=this.options.resourceManager.resource_pack)?void 0:p.interpolate_joints)||[])}}if(this._setCurrentBodyFrame(l),!(l&&h||null==l)&&l.hfd||!(null!=l&&l.hfd||null!=l&&l.frame))return l?h||(this.allLostFaceFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_FACE_ERROR,message:`Error: 第${t}帧 faceFrame为空`,e:{bodyFrame:l,faceFrame:h}})):(this.allLostFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_BODY_ERROR,message:`Error: 第${t}帧 bodyFrame为空`,e:{bodyFrame:l,faceFrame:h}})),this.allLostFrameCount===this.maxLostFrameCount&&(this.options.reportMessage({code:EErrorCode.RENDER_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 身体渲染数据缺失`,e:{bodyFrame:l,faceFrame:h}}),this.forceSyncDecoder(),this.allLostFrameCount=0),this.allLostFaceFrameCount===this.maxLostFrameCount&&this.options.reportMessage({code:EErrorCode.RENDER_FACE_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 渲染表情数据缺失.`,e:{bodyFrame:l,frameIndex:t}}),window.avatarSDKLogger.log(this.TAG,"render第",t,"丢帧,bodyFrame",l,"faceFrame",h),{canvas:this.canvas,rendered:!1};if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,(l&&null!=(o=h)&&o.FaceFrameData&&null!=l&&l.hfd||(null==l||!l.hfd)&&null!=l&&l.frame)&&this.device){var _,m;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(_=this.onStateChange)||_.call(this,null==l?void 0:l.frameState),"speak"!==l.frameState&&window.performanceTracker.markEnd(performanceConstant.start_action_render,l.frameState),this.lastFrameState=null==l?void 0:l.frameState),this.isFirstRender&&(window.performanceTracker.markEnd(performanceConstant.first_avatar_render),this.isFirstRender=!1,this.renderBackground(),window.performanceTracker.markStart(performanceConstant.first_render),null==(m=this.onDownloadProgress)||m.call(this,100));let e=!1;if(this.pipeline){var g;try{var y,v,b,S,E,w,x;const n=this.options.resourceManager.getIsEnableRobotExpression()?null!=(y=null==(v=h)?void 0:v.FaceFrameData)?y:null:null!=l&&l.hfd&&null!=(b=null==(S=h)?void 0:S.FaceFrameData)?b:null;n&&this.saveAndDownload.appendMultipleToArray("render_faceData",[h]),this.lastFaceFrame=h;let i=l.frame;var T;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(T=this.copyCtx)||T.drawImage(l.frame,0,0),i=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:i,data:n,backgroundTexture:null,fx:null!=(E=null==(w=this.options.resourceManager.getConfig())?void 0:w.fx)?E:{},onPostRender:()=>null});let r=[0,0,0],s=[...r];const a=null!=(x=null==l?void 0:l.offset)?x:0;this.lastBodyOffset=a,s[0]+=a-this.baseWalkOffset;const o=this.pipeline.getBillboardTransform2D([r[0],r[1],r[2]],[s[0],s[1],s[2]]).offsetX*this.canvas.width*this.scale;o!==this.canvasOffsetX&&(this.canvasOffsetX=o,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:o}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(o):updateCanvasXOffset(this.canvas,o)),this.lastFrameIndex=t,e=!0}catch(e){window.avatarSDKLogger.error(this.TAG,"渲染帧失败:",e),this.options.reportMessage({code:EErrorCode.WebGL_RENDER_ERROR,message:`Error: 第${t}帧 webgl渲染异常`,e:{bodyFrame:l,faceFrame:h,error:e}})}finally{l.frame&&"function"==typeof l.frame.close&&l.frame.close()}null==(g=this.onRenderChange)||g.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:e}}return{canvas:this.canvas,rendered:!1}}renderBackground(){const t=this.options.resourceManager.getBackgroundImageElement();if(!t)return;const e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage=`url(${t.src})`,e.style.backgroundSize="cover",e.style.backgroundPosition="center")}_setCurrentBodyFrame(t){t&&(this.currentBodyFrame=t)}_getCurrentBodyFrameInfo(t){return this.currentBodyFrame&&t>0?{client_frame:t,current_ani:this.currentBodyFrame.name,current_ani_frame:this.currentBodyFrame.frameIndex-this.currentBodyFrame.sf,next_state:this.lastFrameState||"idle"}:{client_frame:0,current_ani:"",current_ani_frame:0,next_state:"idle"}}_getCurrentFrameData(t){var e,n,i,r,s;const a=this.currentBodyFrame,o=this.lastFaceFrame;return{body:a?{body_id:null!=(e=null!=(n=a.body_id)?n:a.id)?e:0,name:a.name,video_frame:a.frameIndex-a.sf,sf:a.sf,state:a.frameState}:null,face:o?{body_id:null!=(i=null!=(r=o.body_id)?r:o.id)?i:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}}setCanvasVisibility(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")}getCanvasVisibility(){return this.avatarCanvasVisible}destroy(){if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0,this.device)if(this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.pipeline&&(this.pipeline.destroy(),this.pipeline=null),this.device.gl){const t=this.device;this.device=null,requestAnimationFrame(()=>{try{t&&t.destroy()}catch(t){var e;null==(e=window.avatarSDKLogger)||null==e.warn||e.warn("[AvatarRenderer] 销毁 device 时出错:",t)}})}else this.device=null;this.isInit=!1,this.isFirstRender=!0,this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,this.onStateChange=void 0,this.lastFrameState="",this.pipeline=null,this.pendingCharData=null,this.scale=1;const t=document.getElementById("avatar-bg-container");t&&t.parentNode&&t.parentNode.removeChild(t),this.canvas&&this.canvas.parentNode&&this.canvas.remove()}setInterrupt(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)}simulateContextLoss(t=5e3,e=!1){if(!this.device||!this.device.gl)return void window.avatarSDKLogger.warn("[Test] No WebGL device available for testing");const n=this.device.gl.getExtension("WEBGL_lose_context");n?(window.avatarSDKLogger.log("[Test] Simulating WebGL context loss..."),e&&window.avatarSDKLogger.warn("[Test] Force fail mode enabled - will not auto-restore"),n.loseContext(),t>0&&!e&&setTimeout(()=>{window.avatarSDKLogger.log(`[Test] Auto-restoring context after ${t}ms...`),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}getRecoveryStatus(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}}async testStagedRecovery(){window.avatarSDKLogger.log("[Test] Starting staged recovery test...");const t=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}];for(let e=0;e<t.length;e++){const n=t[e];window.avatarSDKLogger.log(`[Test] Step ${e+1}: ${n.desc}`),await new Promise(t=>{setTimeout(()=>{this.simulateContextLoss(n.delay,n.forceFail),t()},n.delay)}),await new Promise(t=>setTimeout(t,n.delay+2e3));const i=this.getRecoveryStatus();window.avatarSDKLogger.log(`[Test] After step ${e+1}:`,i)}window.avatarSDKLogger.log("[Test] Staged recovery test completed!")}restartWebGL(){window.avatarSDKLogger.log("[restartWebGL] Starting manual WebGL restart..."),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0;try{var t;if(this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after creating new canvas");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,window.avatarSDKLogger.log("[restartWebGL] WebGL restart successful!"),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_MANUAL_RESTARTED,message:"WebGL context recovered via manual restart.",e:{timestamp:Date.now(),method:"manual_restart"}}),!0}catch(t){return window.avatarSDKLogger.error("[restartWebGL] Failed:",t),this._reportRecoveryFailure("manual",t),!1}}}class BaseTrack{render(){}stop(){}}class ImageTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null}}class SubtitleTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)}}class TrackRenderer{constructor(t,e){this.TAG="[TrackRenderer]",this.instance=e;const{type:n,data:i,text:r=""}=t;var s;"widget_pic"===n&&(this.tracker=new ImageTrack(i,e)),("subtitle_on"===n||"subtitle_off"===n)&&(this.tracker=new SubtitleTrack({type:n,text:r,axis_id:null!=(s=null==i?void 0:i.axis_id)?s:1e3},e))}render(){var t;return null==(t=this.tracker)?void 0:t.render()}stop(){this.tracker.stop()}destroy(){WidgetDefaultRenderer.destroy(this.instance)}}class UIRenderer{constructor(t){this.TAG="[UIRenderer]",this.trackerRenderer=[],this.root=document.createElement("div"),this.lastFrameIndex=-1,this.initEventsRendered=!1,this.lastSpeechId=-1,this.interruptSpeechId=-1,this.enableClientInterrupt=!1,this.options=t,this.root.setAttribute("style","position:absolute;"),this.onVoiceStart=t.onVoiceStart,this.onVoiceEnd=t.onVoiceEnd,this.initEventsRendered=!1,this.onWalkStateChange=t.onWalkStateChange,this.enableClientInterrupt=t.enableClientInterrupt,this.onSpeakStateChange=t.onSpeakStateChange}render(t){var e,n,i,r,s,a,o,l,h;let d=[];if(-1===this.lastFrameIndex){const t=this.options.resourceManager.getConfig();t.init_events&&t.init_events.length>0&&(d=t.init_events.map(t=>_extends({},t,{speech_id:0})))}let c=null;if(c=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,c?c.e=c.e.concat(d):c={e:d}),null==(e=c)||!e.e)return;window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(c));const u=null==(n=c.e)?void 0:n.filter(t=>null==(null==t?void 0:t.speech_id));if(null!=u&&u.length){const t=u.map(t=>t.type).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:`Error: 事件中存在不包含speech_id的事件${t}`,e:u})}var f,p;if(this.enableClientInterrupt&&(c.e=null==(f=c.e)?void 0:f.filter(t=>t.speech_id>this.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type)),-1!==this.lastSpeechId&&this.lastSpeechId&&(c.e=null==(p=c.e)?void 0:p.filter(t=>(null==t?void 0:t.speech_id)>=this.lastSpeechId)),null!=(i=c.e)&&i.some(t=>"speak_start"===t.type)){const t=c.e.find(t=>"speak_start"===t.type);this.lastSpeechId=null==t?void 0:t.speech_id,this.onSpeakStateChange("speak_start",t.client_speak_id,(null==t?void 0:t.speech_id)||0)}if((null!=(r=c.e)&&r.some(t=>"walk_start"===t.type)||null!=(s=c.e)&&s.some(t=>"speak_walk_start"===t.type))&&this.onWalkStateChange("walk_start"),null!=(a=c.e)&&a.some(t=>"voice_start"===t.type)){const t=c.e.find(t=>"voice_start"===t.type),e=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==t?void 0:t.multi_turn_conversation_id}),this.onVoiceStart(e,null==t?void 0:t.client_speak_id)}if((null!=(o=c.e)&&o.some(t=>"walk_end"===t.type)||null!=(l=c.e)&&l.some(t=>"speak_walk_end"===t.type))&&this.onWalkStateChange("walk_end"),null!=(h=c.e)&&h.some(t=>"voice_end"===t.type)){const t=c.e.find(t=>"voice_end"===t.type);this.onVoiceEnd((null==t?void 0:t.client_speak_id)||"",(null==t?void 0:t.speech_id)||0)}["speak_end","speak_error"].forEach(t=>{const e=c.e.find(e=>e.type===t);e&&this.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});const _=[...c.e];for(let t=0;t<c.e.length;t++){const e=c.e[t];if(!Object.prototype.hasOwnProperty.call(e,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(e);const t=_.indexOf(e);t>-1&&_.splice(t,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[e.type]){WidgetDefaultRenderer.PROXY_WIDGET[e.type](e);const t=_.indexOf(e);t>-1&&_.splice(t,1)}}if(_.length>0)for(const t of _){const e=new TrackRenderer(t,this.options.sdk);this.trackerRenderer.push(e)}return this.trackerRenderer}clearTrackerRenderer(){this.trackerRenderer=[]}setInterrupt(t){this.interruptSpeechId=t}destroy(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(t=>t.destroy())}}class FPSTracker{constructor(t=60){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0,this.maxSamples=t}tick(t=!0){const e=performance.now();if(this.lastFrameTime>0){const n=e-this.lastFrameTime;this.frameTimestamps.push(n),this.frameTimestamps.length>this.maxSamples&&this.frameTimestamps.shift(),this.totalFrames++,this.totalTime+=n,t?(this.frameCount++,this.totalRenderedFrames++):this.droppedFrames++,e-this.lastUpdateTime>=1e3&&(this.currentFPS=Math.round(1e3*this.frameCount/(e-this.lastUpdateTime)),this.frameCount=0,this.lastUpdateTime=e)}this.lastFrameTime=e}getStats(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};const t=this.frameTimestamps.reduce((t,e)=>t+e,0)/this.frameTimestamps.length,e=Math.min(...this.frameTimestamps),n=Math.max(...this.frameTimestamps);return{current:this.currentFPS,average:this.frameTimestamps.length>0?Math.round(1e3/t):0,min:e>0?Math.round(1e3/n):0,max:n>0?Math.round(1e3/e):0,droppedFrames:this.droppedFrames,totalFrames:this.totalFrames}}getCurrentFPS(){return this.currentFPS}getAverageFPS(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)}reset(){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0}getDroppedFrames(){return this.droppedFrames}}class Composition{constructor(t){this.TAG="[Composition]",this.container=t.container,this.avatarRenderer=t.avatarRenderer,this.restRenderers=t.restRenderers,this.audioRenderer=t.audioRenderer,this.onFPSUpdate=t.onFPSUpdate,this.audioOnlyMode=t.audioOnlyMode||!1,this.fpsTracker=new FPSTracker,this.audioOnlyMode||this.container.appendChild(t.avatarRenderer.canvas)}compose(t){if(!this.audioOnlyMode){const e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);const n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(const e of this.restRenderers){const n=e.render(t);if(e.clearTrackerRenderer(),n)for(const t of n){const e=null==t?void 0:t.render();e&&this.container.appendChild(e)}}}getFPSStats(){return this.fpsTracker.getStats()}stop(){this.audioRenderer.stop(-1)}destroy(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(t=>t.destroy())}}const mp4boxSource='\nvar Log = function() {\n\tvar i = new Date,\n\tr = 4;\n\treturn {\n\t\tsetLogLevel: function(t) {\n\t\t\tr = t == this.debug ? 1 : t == this.info ? 2 : t == this.warn ? 3 : (this.error, 4)\n\t\t},\n\t\tdebug: function(t, e) {\n\t\t\tvoid 0 === console.debug && (console.debug = console.log),\n\t\t\tr <= 1 && console.debug("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\tlog: function(t, e) {\n\t\t\tthis.debug(t.msg)\n\t\t},\n\t\tinfo: function(t, e) {\n\t\t\tr <= 2 && console.info("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\twarn: function(t, e) {\n\t\t\tr <= 3 && console.warn("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\terror: function(t, e) {\n\t\t\tr <= 4 && console.error("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t}\n\t}\n} ();\nLog.getDurationString = function(t, e) {\n\tvar i;\n\tfunction r(t, e) {\n\t\tfor (var i = ("" + t).split("."); i[0].length < e;) i[0] = "0" + i[0];\n\t\treturn i.join(".")\n\t}\n\tt < 0 ? (i = !0, t = -t) : i = !1;\n\tvar s = t / (e || 1),\n\ta = Math.floor(s / 3600);\n\ts -= 3600 * a;\n\tt = Math.floor(s / 60),\n\te = 1e3 * (s -= 60 * t);\n\treturn e -= 1e3 * (s = Math.floor(s)),\n\te = Math.floor(e),\n\t(i ? "-": "") + a + ":" + r(t, 2) + ":" + r(s, 2) + "." + r(e, 3)\n},\nLog.printRanges = function(t) {\n\tvar e = t.length;\n\tif (0 < e) {\n\t\tfor (var i = "",\n\t\tr = 0; r < e; r++) 0 < r && (i += ","),\n\t\ti += "[" + Log.getDurationString(t.start(r)) + "," + Log.getDurationString(t.end(r)) + "]";\n\t\treturn i\n\t}\n\treturn "(empty)"\n},\n"undefined" != typeof exports && (exports.Log = Log);\nvar MP4BoxStream = function(t) {\n\tif (! (t instanceof ArrayBuffer)) throw "Needs an array buffer";\n\tthis.buffer = t,\n\tthis.dataview = new DataView(t),\n\tthis.position = 0\n};\nMP4BoxStream.prototype.getPosition = function() {\n\treturn this.position\n},\nMP4BoxStream.prototype.getEndPosition = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.getLength = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.buffer.byteLength, t));\n\treturn this.position = isNaN(t) || !isFinite(t) ? 0 : t,\n\t!0\n},\nMP4BoxStream.prototype.isEos = function() {\n\treturn this.getPosition() >= this.getEndPosition()\n},\nMP4BoxStream.prototype.readAnyInt = function(t, e) {\n\tvar i = 0;\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tswitch (t) {\n\t\tcase 1:\n\t\t\ti = e ? this.dataview.getInt8(this.position) : this.dataview.getUint8(this.position);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ti = e ? this.dataview.getInt16(this.position) : this.dataview.getUint16(this.position);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tif (e) throw "No method for reading signed 24 bits values";\n\t\t\ti = this.dataview.getUint8(this.position) << 16,\n\t\t\ti |= this.dataview.getUint8(this.position + 1) << 8,\n\t\t\ti |= this.dataview.getUint8(this.position + 2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ti = e ? this.dataview.getInt32(this.position) : this.dataview.getUint32(this.position);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tif (e) throw "No method for reading signed 64 bits values";\n\t\t\ti = this.dataview.getUint32(this.position) << 32,\n\t\t\ti |= this.dataview.getUint32(this.position + 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "readInt method not implemented for size: " + t\n\t\t}\n\t\treturn this.position += t,\n\t\ti\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readUint8 = function() {\n\treturn this.readAnyInt(1, !1)\n},\nMP4BoxStream.prototype.readUint16 = function() {\n\treturn this.readAnyInt(2, !1)\n},\nMP4BoxStream.prototype.readUint24 = function() {\n\treturn this.readAnyInt(3, !1)\n},\nMP4BoxStream.prototype.readUint32 = function() {\n\treturn this.readAnyInt(4, !1)\n},\nMP4BoxStream.prototype.readUint64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readString = function(t) {\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tfor (var e = "",\n\t\ti = 0; i < t; i++) e += String.fromCharCode(this.readUint8());\n\t\treturn e\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readCString = function() {\n\tfor (var t = [];;) {\n\t\tvar e = this.readUint8();\n\t\tif (0 === e) break;\n\t\tt.push(e)\n\t}\n\treturn String.fromCharCode.apply(null, t)\n},\nMP4BoxStream.prototype.readInt8 = function() {\n\treturn this.readAnyInt(1, !0)\n},\nMP4BoxStream.prototype.readInt16 = function() {\n\treturn this.readAnyInt(2, !0)\n},\nMP4BoxStream.prototype.readInt32 = function() {\n\treturn this.readAnyInt(4, !0)\n},\nMP4BoxStream.prototype.readInt64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readUint8Array = function(t) {\n\tfor (var e = new Uint8Array(t), i = 0; i < t; i++) e[i] = this.readUint8();\n\treturn e\n},\nMP4BoxStream.prototype.readInt16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readInt16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readUint16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint32Array = function(t) {\n\tfor (var e = new Uint32Array(t), i = 0; i < t; i++) e[i] = this.readUint32();\n\treturn e\n},\nMP4BoxStream.prototype.readInt32Array = function(t) {\n\tfor (var e = new Int32Array(t), i = 0; i < t; i++) e[i] = this.readInt32();\n\treturn e\n},\n"undefined" != typeof exports && (exports.MP4BoxStream = MP4BoxStream);\nvar DataStream = function(t, e, i) {\n\tthis._byteOffset = e || 0,\n\tt instanceof ArrayBuffer ? this.buffer = t: "object" == typeof t ? (this.dataView = t, e && (this._byteOffset += e)) : this.buffer = new ArrayBuffer(t || 0),\n\tthis.position = 0,\n\tthis.endianness = null == i ? DataStream.LITTLE_ENDIAN: i\n};\nDataStream.prototype = {},\nDataStream.prototype.getPosition = function() {\n\treturn this.position\n},\nDataStream.prototype._realloc = function(t) {\n\tif (this._dynamicSize) {\n\t\tvar e = this._byteOffset + this.position + t,\n\t\ti = this._buffer.byteLength;\n\t\tif (e <= i) e > this._byteLength && (this._byteLength = e);\n\t\telse {\n\t\t\tfor (i < 1 && (i = 1); i < e;) i *= 2;\n\t\t\tvar r = new ArrayBuffer(i),\n\t\t\tt = new Uint8Array(this._buffer);\n\t\t\tnew Uint8Array(r, 0, t.length).set(t),\n\t\t\tthis.buffer = r,\n\t\t\tthis._byteLength = e\n\t\t}\n\t}\n},\nDataStream.prototype._trimAlloc = function() {\n\tvar t, e, i;\n\tthis._byteLength != this._buffer.byteLength && (t = new ArrayBuffer(this._byteLength), e = new Uint8Array(t), i = new Uint8Array(this._buffer, 0, e.length), e.set(i), this.buffer = t)\n},\nDataStream.BIG_ENDIAN = !1,\nDataStream.LITTLE_ENDIAN = !0,\nDataStream.prototype._byteLength = 0,\nObject.defineProperty(DataStream.prototype, "byteLength", {\n\tget: function() {\n\t\treturn this._byteLength - this._byteOffset\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "buffer", {\n\tget: function() {\n\t\treturn this._trimAlloc(),\n\t\tthis._buffer\n\t},\n\tset: function(t) {\n\t\tthis._buffer = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "byteOffset", {\n\tget: function() {\n\t\treturn this._byteOffset\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "dataView", {\n\tget: function() {\n\t\treturn this._dataView\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t.byteOffset,\n\t\tthis._buffer = t.buffer,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._byteOffset + t.byteLength\n\t}\n}),\nDataStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.byteLength, t));\n\tthis.position = isNaN(t) || !isFinite(t) ? 0 : t\n},\nDataStream.prototype.isEof = function() {\n\treturn this.position >= this._byteLength\n},\nDataStream.prototype.mapUint8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Uint8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.readInt32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Int32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Int16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Int8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readUint32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Uint32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Uint16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Uint8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readFloat64Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 8 : t;\n\tvar i = new Float64Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readFloat32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Float32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt32 = function(t) {\n\tt = this._dataView.getInt32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readInt16 = function(t) {\n\tt = this._dataView.getInt16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readInt8 = function() {\n\tvar t = this._dataView.getInt8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readUint32 = function(t) {\n\tt = this._dataView.getUint32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readUint16 = function(t) {\n\tt = this._dataView.getUint16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readUint8 = function() {\n\tvar t = this._dataView.getUint8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readFloat32 = function(t) {\n\tt = this._dataView.getFloat32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readFloat64 = function(t) {\n\tt = this._dataView.getFloat64(this.position, null == t ? this.endianness: t);\n\treturn this.position += 8,\n\tt\n},\nDataStream.endianness = 0 < new Int8Array(new Int16Array([1]).buffer)[0],\nDataStream.memcpy = function(t, e, i, r, s) {\n\te = new Uint8Array(t, e, s),\n\ts = new Uint8Array(i, r, s);\n\te.set(s)\n},\nDataStream.arrayToNative = function(t, e) {\n\treturn e == this.endianness ? t: this.flipArrayEndianness(t)\n},\nDataStream.nativeToEndian = function(t, e) {\n\treturn this.endianness == e ? t: this.flipArrayEndianness(t)\n},\nDataStream.flipArrayEndianness = function(t) {\n\tfor (var e = new Uint8Array(t.buffer, t.byteOffset, t.byteLength), i = 0; i < t.byteLength; i += t.BYTES_PER_ELEMENT) for (var r = i + t.BYTES_PER_ELEMENT - 1,\n\ts = i; s < r; r--, s++) {\n\t\tvar a = e[s];\n\t\te[s] = e[r],\n\t\te[r] = a\n\t}\n\treturn t\n},\nDataStream.prototype.failurePosition = 0,\nString.fromCharCodeUint8 = function(t) {\n\tfor (var e = [], i = 0; i < t.length; i++) e[i] = t[i];\n\treturn String.fromCharCode.apply(null, e)\n},\nDataStream.prototype.readString = function(t, e) {\n\treturn null == e || "ASCII" == e ? String.fromCharCodeUint8.apply(null, [this.mapUint8Array(null == t ? this.byteLength - this.position: t)]) : new TextDecoder(e).decode(this.mapUint8Array(t))\n},\nDataStream.prototype.readCString = function(t) {\n\tvar e = this.byteLength - this.position,\n\ti = new Uint8Array(this._buffer, this._byteOffset + this.position),\n\tr = e;\n\tnull != t && (r = Math.min(t, e));\n\tfor (var s = 0; s < r && 0 !== i[s]; s++);\n\tvar a = String.fromCharCodeUint8.apply(null, [this.mapUint8Array(s)]);\n\treturn null != t ? this.position += r - s: s != e && (this.position += 1),\n\ta\n};\nvar MAX_SIZE = Math.pow(2, 32);\nDataStream.prototype.readInt64 = function() {\n\treturn this.readInt32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readInt64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint24 = function() {\n\treturn (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8()\n},\n"undefined" != typeof exports && (exports.DataStream = DataStream),\nDataStream.prototype.save = function(t) {\n\tvar e = new Blob([this.buffer]);\n\tif (!window.URL || !URL.createObjectURL) throw "DataStream.save: Can\'t create object URL.";\n\tvar i = window.URL.createObjectURL(e),\n\te = document.createElement("a");\n\tdocument.body.appendChild(e),\n\te.setAttribute("href", i),\n\te.setAttribute("download", t),\n\te.setAttribute("target", "_self"),\n\te.click(),\n\twindow.URL.revokeObjectURL(i)\n},\nDataStream.prototype._dynamicSize = !0,\nObject.defineProperty(DataStream.prototype, "dynamicSize", {\n\tget: function() {\n\t\treturn this._dynamicSize\n\t},\n\tset: function(t) {\n\t\tt || this._trimAlloc(),\n\t\tthis._dynamicSize = t\n\t}\n}),\nDataStream.prototype.shift = function(t) {\n\tvar e = new ArrayBuffer(this._byteLength - t),\n\ti = new Uint8Array(e),\n\tr = new Uint8Array(this._buffer, t, i.length);\n\ti.set(r),\n\tthis.buffer = e,\n\tthis.position -= t\n},\nDataStream.prototype.writeInt32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Int32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt32(t[i], e)\n},\nDataStream.prototype.writeInt16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Int16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt16(t[i], e)\n},\nDataStream.prototype.writeInt8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Int8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeInt8(t[e])\n},\nDataStream.prototype.writeUint32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Uint32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint32(t[i], e)\n},\nDataStream.prototype.writeUint16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Uint16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint16(t[i], e)\n},\nDataStream.prototype.writeUint8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Uint8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeUint8(t[e])\n},\nDataStream.prototype.writeFloat64Array = function(t, e) {\n\tif (this._realloc(8 * t.length), t instanceof Float64Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat64Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat64(t[i], e)\n},\nDataStream.prototype.writeFloat32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Float32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat32(t[i], e)\n},\nDataStream.prototype.writeInt32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setInt32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeInt16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setInt16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeInt8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setInt8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeUint32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setUint32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeUint16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setUint16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeUint8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setUint8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeFloat32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setFloat32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeFloat64 = function(t, e) {\n\tthis._realloc(8),\n\tthis._dataView.setFloat64(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 8\n},\nDataStream.prototype.writeUCS2String = function(t, e, i) {\n\tnull == i && (i = t.length);\n\tfor (var r = 0; r < t.length && r < i; r++) this.writeUint16(t.charCodeAt(r), e);\n\tfor (; r < i; r++) this.writeUint16(0)\n},\nDataStream.prototype.writeString = function(t, e, i) {\n\tvar r = 0;\n\tif (null == e || "ASCII" == e) if (null != i) {\n\t\tfor (var s = Math.min(t.length, i), r = 0; r < s; r++) this.writeUint8(t.charCodeAt(r));\n\t\tfor (; r < i; r++) this.writeUint8(0)\n\t} else for (r = 0; r < t.length; r++) this.writeUint8(t.charCodeAt(r));\n\telse this.writeUint8Array(new TextEncoder(e).encode(t.substring(0, i)))\n},\nDataStream.prototype.writeCString = function(t, e) {\n\tvar i = 0;\n\tif (null != e) {\n\t\tfor (var r = Math.min(t.length, e), i = 0; i < r; i++) this.writeUint8(t.charCodeAt(i));\n\t\tfor (; i < e; i++) this.writeUint8(0)\n\t} else {\n\t\tfor (i = 0; i < t.length; i++) this.writeUint8(t.charCodeAt(i));\n\t\tthis.writeUint8(0)\n\t}\n},\nDataStream.prototype.writeStruct = function(t, e) {\n\tfor (var i = 0; i < t.length; i += 2) {\n\t\tvar r = t[i + 1];\n\t\tthis.writeType(r, e[t[i]], e)\n\t}\n},\nDataStream.prototype.writeType = function(t, e, i) {\n\tvar r;\n\tif ("function" == typeof t) return t(this, e);\n\tif ("object" == typeof t && !(t instanceof Array)) return t.set(this, e, i);\n\tvar s = null,\n\ta = "ASCII",\n\ti = this.position;\n\tswitch ("string" == typeof t && /:/.test(t) && (t = (r = t.split(":"))[0], s = parseInt(r[1])), "string" == typeof t && /,/.test(t) && (t = (r = t.split(","))[0], a = parseInt(r[1])), t) {\n\tcase "uint8":\n\t\tthis.writeUint8(e);\n\t\tbreak;\n\tcase "int8":\n\t\tthis.writeInt8(e);\n\t\tbreak;\n\tcase "uint16":\n\t\tthis.writeUint16(e, this.endianness);\n\t\tbreak;\n\tcase "int16":\n\t\tthis.writeInt16(e, this.endianness);\n\t\tbreak;\n\tcase "uint32":\n\t\tthis.writeUint32(e, this.endianness);\n\t\tbreak;\n\tcase "int32":\n\t\tthis.writeInt32(e, this.endianness);\n\t\tbreak;\n\tcase "float32":\n\t\tthis.writeFloat32(e, this.endianness);\n\t\tbreak;\n\tcase "float64":\n\t\tthis.writeFloat64(e, this.endianness);\n\t\tbreak;\n\tcase "uint16be":\n\t\tthis.writeUint16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int16be":\n\t\tthis.writeInt16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint32be":\n\t\tthis.writeUint32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int32be":\n\t\tthis.writeInt32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float32be":\n\t\tthis.writeFloat32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float64be":\n\t\tthis.writeFloat64(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint16le":\n\t\tthis.writeUint16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int16le":\n\t\tthis.writeInt16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "uint32le":\n\t\tthis.writeUint32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int32le":\n\t\tthis.writeInt32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float32le":\n\t\tthis.writeFloat32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float64le":\n\t\tthis.writeFloat64(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "cstring":\n\t\tthis.writeCString(e, s);\n\t\tbreak;\n\tcase "string":\n\t\tthis.writeString(e, a, s);\n\t\tbreak;\n\tcase "u16string":\n\t\tthis.writeUCS2String(e, this.endianness, s);\n\t\tbreak;\n\tcase "u16stringle":\n\t\tthis.writeUCS2String(e, DataStream.LITTLE_ENDIAN, s);\n\t\tbreak;\n\tcase "u16stringbe":\n\t\tthis.writeUCS2String(e, DataStream.BIG_ENDIAN, s);\n\t\tbreak;\n\tdefault:\n\t\tif (3 == t.length) {\n\t\t\tfor (var n = t[1], o = 0; o < e.length; o++) this.writeType(n, e[o]);\n\t\t\tbreak\n\t\t}\n\t\tthis.writeStruct(t, e)\n\t}\n\tnull != s && (this.position = i, this._realloc(s), this.position = i + s)\n},\nDataStream.prototype.writeUint64 = function(t) {\n\tvar e = Math.floor(t / MAX_SIZE);\n\tthis.writeUint32(e),\n\tthis.writeUint32(4294967295 & t)\n},\nDataStream.prototype.writeUint24 = function(t) {\n\tthis.writeUint8((16711680 & t) >> 16),\n\tthis.writeUint8((65280 & t) >> 8),\n\tthis.writeUint8(255 & t)\n},\nDataStream.prototype.adjustUint32 = function(t, e) {\n\tvar i = this.position;\n\tthis.seek(t),\n\tthis.writeUint32(e),\n\tthis.seek(i)\n},\nDataStream.prototype.mapInt32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Int32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapInt16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Int16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapInt8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Int8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.mapUint32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Uint32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapUint16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Uint16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapFloat64Array = function(t, e) {\n\tthis._realloc(8 * t);\n\tvar i = new Float64Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 8 * t,\n\ti\n},\nDataStream.prototype.mapFloat32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Float32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n};\nvar MultiBufferStream = function(t) {\n\tthis.buffers = [],\n\tthis.bufferIndex = -1,\n\tt && (this.insertBuffer(t), this.bufferIndex = 0)\n};\nMultiBufferStream.prototype = new DataStream(new ArrayBuffer, 0, DataStream.BIG_ENDIAN),\nMultiBufferStream.prototype.initialized = function() {\n\tvar t;\n\treturn - 1 < this.bufferIndex || (0 < this.buffers.length ? 0 === (t = this.buffers[0]).fileStart ? (this.buffer = t, this.bufferIndex = 0, Log.debug("MultiBufferStream", "Stream ready for parsing"), !0) : (Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0"), this.logBufferLevel(), !1) : (Log.warn("MultiBufferStream", "No buffer to start parsing from"), this.logBufferLevel(), !1))\n},\nArrayBuffer.concat = function(t, e) {\n\tLog.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (t.byteLength + e.byteLength));\n\tvar i = new Uint8Array(t.byteLength + e.byteLength);\n\treturn i.set(new Uint8Array(t), 0),\n\ti.set(new Uint8Array(e), t.byteLength),\n\ti.buffer\n},\nMultiBufferStream.prototype.reduceBuffer = function(t, e, i) {\n\tvar r = new Uint8Array(i);\n\treturn r.set(new Uint8Array(t, e, i)),\n\tr.buffer.fileStart = t.fileStart + e,\n\tr.buffer.usedBytes = 0,\n\tr.buffer\n},\nMultiBufferStream.prototype.insertBuffer = function(t) {\n\tfor (var e = !0,\n\ti = 0; i < this.buffers.length; i++) {\n\t\tvar r = this.buffers[i];\n\t\tif (t.fileStart <= r.fileStart) {\n\t\t\tif (t.fileStart === r.fileStart) {\n\t\t\t\tif (t.byteLength > r.byteLength) {\n\t\t\t\t\tthis.buffers.splice(i, 1),\n\t\t\t\t\ti--;\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tLog.warn("MultiBufferStream", "Buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ") already appended, ignoring")\n\t\t\t} else t.fileStart + t.byteLength <= r.fileStart || (t = this.reduceBuffer(t, 0, r.fileStart - t.fileStart)),\n\t\t\tLog.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"),\n\t\t\tthis.buffers.splice(i, 0, t),\n\t\t\t0 === i && (this.buffer = t);\n\t\t\te = !1;\n\t\t\tbreak\n\t\t}\n\t\tif (t.fileStart < r.fileStart + r.byteLength) {\n\t\t\tvar s = r.fileStart + r.byteLength - t.fileStart,\n\t\t\tr = t.byteLength - s;\n\t\t\tif (! (0 < r)) {\n\t\t\t\te = !1;\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt = this.reduceBuffer(t, s, r)\n\t\t}\n\t}\n\te && (Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"), this.buffers.push(t), 0 === i && (this.buffer = t))\n},\nMultiBufferStream.prototype.logBufferLevel = function(t) {\n\tfor (var e, i, r = [], s = "", a = 0, n = 0, o = 0; o < this.buffers.length; o++) e = this.buffers[o],\n\t0 === o ? (i = {},\n\tr.push(i), i.start = e.fileStart, i.end = e.fileStart + e.byteLength, s += "[" + i.start + "-") : i.end === e.fileStart ? i.end = e.fileStart + e.byteLength: ((i = {}).start = e.fileStart, s += r[r.length - 1].end - 1 + "], [" + i.start + "-", i.end = e.fileStart + e.byteLength, r.push(i)),\n\ta += e.usedBytes,\n\tn += e.byteLength;\n\t0 < r.length && (s += i.end - 1 + "]");\n\tt = t ? Log.info: Log.debug;\n\t0 === this.buffers.length ? t("MultiBufferStream", "No more buffer in memory") : t("MultiBufferStream", this.buffers.length + " stored buffer(s) (" + a + "/" + n + " bytes), continuous ranges: " + s)\n},\nMultiBufferStream.prototype.cleanBuffers = function() {\n\tfor (var t, e = 0; e < this.buffers.length; e++)(t = this.buffers[e]).usedBytes === t.byteLength && (Log.debug("MultiBufferStream", "Removing buffer #" + e), this.buffers.splice(e, 1), e--)\n},\nMultiBufferStream.prototype.mergeNextBuffer = function() {\n\tvar t;\n\tif (this.bufferIndex + 1 < this.buffers.length) {\n\t\tif ((t = this.buffers[this.bufferIndex + 1]).fileStart !== this.buffer.fileStart + this.buffer.byteLength) return ! 1;\n\t\tvar e = this.buffer.byteLength,\n\t\ti = this.buffer.usedBytes,\n\t\tr = this.buffer.fileStart;\n\t\treturn this.buffers[this.bufferIndex] = ArrayBuffer.concat(this.buffer, t),\n\t\tthis.buffer = this.buffers[this.bufferIndex],\n\t\tthis.buffers.splice(this.bufferIndex + 1, 1),\n\t\tthis.buffer.usedBytes = i,\n\t\tthis.buffer.fileStart = r,\n\t\tLog.debug("ISOFile", "Concatenating buffer for box parsing (length: " + e + "->" + this.buffer.byteLength + ")"),\n\t\t!0\n\t}\n\treturn ! 1\n},\nMultiBufferStream.prototype.findPosition = function(t, e, i) {\n\tfor (var r = null,\n\ts = -1,\n\ta = !0 === t ? 0 : this.bufferIndex; a < this.buffers.length && (r = this.buffers[a]).fileStart <= e;) s = a,\n\ti && (r.fileStart + r.byteLength <= e ? r.usedBytes = r.byteLength: r.usedBytes = e - r.fileStart, this.logBufferLevel()),\n\ta++;\n\treturn - 1 !== s && (r = this.buffers[s]).fileStart + r.byteLength >= e ? (Log.debug("MultiBufferStream", "Found position in existing buffer #" + s), s) : -1\n},\nMultiBufferStream.prototype.findEndContiguousBuf = function(t) {\n\tvar e, i, t = void 0 !== t ? t: this.bufferIndex,\n\tr = this.buffers[t];\n\tif (this.buffers.length > t + 1) for (e = t + 1; e < this.buffers.length && (i = this.buffers[e]).fileStart === r.fileStart + r.byteLength; e++) r = i;\n\treturn r.fileStart + r.byteLength\n},\nMultiBufferStream.prototype.getEndFilePositionAfter = function(t) {\n\tvar e = this.findPosition(!0, t, !1);\n\treturn - 1 !== e ? this.findEndContiguousBuf(e) : t\n},\nMultiBufferStream.prototype.addUsedBytes = function(t) {\n\tthis.buffer.usedBytes += t,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.setAllUsedBytes = function() {\n\tthis.buffer.usedBytes = this.buffer.byteLength,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.seek = function(t, e, i) {\n\ti = this.findPosition(e, t, i);\n\treturn - 1 !== i ? (this.buffer = this.buffers[i], this.bufferIndex = i, this.position = t - this.buffer.fileStart, Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position), !0) : (Log.debug("MultiBufferStream", "Position " + t + " not found in buffered data"), !1)\n},\nMultiBufferStream.prototype.getPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.position\n},\nMultiBufferStream.prototype.getLength = function() {\n\treturn this.byteLength\n},\nMultiBufferStream.prototype.getEndPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.byteLength\n},\n"undefined" != typeof exports && (exports.MultiBufferStream = MultiBufferStream);\nvar MPEG4DescriptorParser = function() {\n\tvar s = [];\n\ts[3] = "ES_Descriptor",\n\ts[4] = "DecoderConfigDescriptor",\n\ts[5] = "DecoderSpecificInfo",\n\ts[6] = "SLConfigDescriptor",\n\tthis.getDescriptorName = function(t) {\n\t\treturn s[t]\n\t};\n\tvar r = this,\n\ta = {};\n\treturn this.parseOneDescriptor = function(t) {\n\t\tvar e, i = 0,\n\t\tr = t.readUint8();\n\t\tfor (e = t.readUint8(), 0; 128 & e;) i = (i << 7) + (127 & e),\n\t\te = t.readUint8(),\n\t\t0;\n\t\treturn i = (i << 7) + (127 & e),\n\t\tLog.debug("MPEG4DescriptorParser", "Found " + (s[r] || "Descriptor " + r) + ", size " + i + " at position " + t.getPosition()),\n\t\t(r = new(s[r] ? a[s[r]] : a.Descriptor)(i)).parse(t),\n\t\tr\n\t},\n\ta.Descriptor = function(t, e) {\n\t\tthis.tag = t,\n\t\tthis.size = e,\n\t\tthis.descs = []\n\t},\n\ta.Descriptor.prototype.parse = function(t) {\n\t\tthis.data = t.readUint8Array(this.size)\n\t},\n\ta.Descriptor.prototype.findDescriptor = function(t) {\n\t\tfor (var e = 0; e < this.descs.length; e++) if (this.descs[e].tag == t) return this.descs[e];\n\t\treturn null\n\t},\n\ta.Descriptor.prototype.parseRemainingDescriptors = function(t) {\n\t\tfor (var e = t.position; t.position < e + this.size;) {\n\t\t\tvar i = r.parseOneDescriptor(t);\n\t\t\tthis.descs.push(i)\n\t\t}\n\t},\n\ta.ES_Descriptor = function(t) {\n\t\ta.Descriptor.call(this, 3, t)\n\t},\n\ta.ES_Descriptor.prototype = new a.Descriptor,\n\ta.ES_Descriptor.prototype.parse = function(t) {\n\t\tvar e;\n\t\tthis.ES_ID = t.readUint16(),\n\t\tthis.flags = t.readUint8(),\n\t\tthis.size -= 3,\n\t\t128 & this.flags ? (this.dependsOn_ES_ID = t.readUint16(), this.size -= 2) : this.dependsOn_ES_ID = 0,\n\t\t64 & this.flags ? (e = t.readUint8(), this.URL = t.readString(e), this.size -= e + 1) : this.URL = "",\n\t\t32 & this.flags ? (this.OCR_ES_ID = t.readUint16(), this.size -= 2) : this.OCR_ES_ID = 0,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.ES_Descriptor.prototype.getOTI = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\treturn e ? e.oti: 0\n\t},\n\ta.ES_Descriptor.prototype.getAudioConfig = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\tif (!e) return null;\n\t\tvar i = e.findDescriptor(5);\n\t\tif (i && i.data) {\n\t\t\te = (248 & i.data[0]) >> 3;\n\t\t\treturn 31 === e && 2 <= i.data.length && (e = 32 + ((7 & i.data[0]) << 3) + ((224 & i.data[1]) >> 5)),\n\t\t\te\n\t\t}\n\t\treturn null\n\t},\n\ta.DecoderConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 4, t)\n\t},\n\ta.DecoderConfigDescriptor.prototype = new a.Descriptor,\n\ta.DecoderConfigDescriptor.prototype.parse = function(t) {\n\t\tthis.oti = t.readUint8(),\n\t\tthis.streamType = t.readUint8(),\n\t\tthis.upStream = 0 != (this.streamType >> 1 & 1),\n\t\tthis.streamType = this.streamType >>> 2,\n\t\tthis.bufferSize = t.readUint24(),\n\t\tthis.maxBitrate = t.readUint32(),\n\t\tthis.avgBitrate = t.readUint32(),\n\t\tthis.size -= 13,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.DecoderSpecificInfo = function(t) {\n\t\ta.Descriptor.call(this, 5, t)\n\t},\n\ta.DecoderSpecificInfo.prototype = new a.Descriptor,\n\ta.SLConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 6, t)\n\t},\n\ta.SLConfigDescriptor.prototype = new a.Descriptor,\n\tthis\n};\n"undefined" != typeof exports && (exports.MPEG4DescriptorParser = MPEG4DescriptorParser);\nvar BoxParser = {\n\tERR_INVALID_DATA: -1,\n\tERR_NOT_ENOUGH_DATA: 0,\n\tOK: 1,\n\tBASIC_BOXES: [{\n\t\ttype: "mdat",\n\t\tname: "MediaDataBox"\n\t},\n\t{\n\t\ttype: "idat",\n\t\tname: "ItemDataBox"\n\t},\n\t{\n\t\ttype: "free",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "skip",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t},\n\t{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}],\n\tFULL_BOXES: [{\n\t\ttype: "hmhd",\n\t\tname: "HintMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "nmhd",\n\t\tname: "NullMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "iods",\n\t\tname: "ObjectDescriptorBox"\n\t},\n\t{\n\t\ttype: "xml ",\n\t\tname: "XMLBox"\n\t},\n\t{\n\t\ttype: "bxml",\n\t\tname: "BinaryXMLBox"\n\t},\n\t{\n\t\ttype: "ipro",\n\t\tname: "ItemProtectionBox"\n\t},\n\t{\n\t\ttype: "mere",\n\t\tname: "MetaboxRelationBox"\n\t}],\n\tCONTAINER_BOXES: [[{\n\t\ttype: "moov",\n\t\tname: "CompressedMovieBox"\n\t},\n\t["trak", "pssh"]], [{\n\t\ttype: "trak",\n\t\tname: "TrackBox"\n\t}], [{\n\t\ttype: "edts",\n\t\tname: "EditBox"\n\t}], [{\n\t\ttype: "mdia",\n\t\tname: "MediaBox"\n\t}], [{\n\t\ttype: "minf",\n\t\tname: "MediaInformationBox"\n\t}], [{\n\t\ttype: "dinf",\n\t\tname: "DataInformationBox"\n\t}], [{\n\t\ttype: "stbl",\n\t\tname: "SampleTableBox"\n\t},\n\t["sgpd", "sbgp"]], [{\n\t\ttype: "mvex",\n\t\tname: "MovieExtendsBox"\n\t},\n\t["trex"]], [{\n\t\ttype: "moof",\n\t\tname: "CompressedMovieFragmentBox"\n\t},\n\t["traf"]], [{\n\t\ttype: "traf",\n\t\tname: "TrackFragmentBox"\n\t},\n\t["trun", "sgpd", "sbgp"]], [{\n\t\ttype: "vttc",\n\t\tname: "VTTCueBox"\n\t}], [{\n\t\ttype: "tref",\n\t\tname: "TrackReferenceBox"\n\t}], [{\n\t\ttype: "iref",\n\t\tname: "ItemReferenceBox"\n\t}], [{\n\t\ttype: "mfra",\n\t\tname: "MovieFragmentRandomAccessBox"\n\t},\n\t["tfra"]], [{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t}], [{\n\t\ttype: "hnti",\n\t\tname: "trackhintinformation"\n\t}], [{\n\t\ttype: "hinf",\n\t\tname: "hintstatisticsbox"\n\t}], [{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}], [{\n\t\ttype: "strd",\n\t\tname: "SubTrackDefinitionBox"\n\t}], [{\n\t\ttype: "sinf",\n\t\tname: "ProtectionSchemeInfoBox"\n\t}], [{\n\t\ttype: "rinf",\n\t\tname: "RestrictedSchemeInfoBox"\n\t}], [{\n\t\ttype: "schi",\n\t\tname: "SchemeInformationBox"\n\t}], [{\n\t\ttype: "trgr",\n\t\tname: "TrackGroupBox"\n\t}], [{\n\t\ttype: "udta",\n\t\tname: "UserDataBox"\n\t},\n\t["kind"]], [{\n\t\ttype: "iprp",\n\t\tname: "ItemPropertiesBox"\n\t},\n\t["ipma"]], [{\n\t\ttype: "ipco",\n\t\tname: "ItemPropertyContainerBox"\n\t}], [{\n\t\ttype: "grpl",\n\t\tname: "GroupsListBox"\n\t}], [{\n\t\ttype: "j2kH",\n\t\tname: "J2KHeaderInfoBox"\n\t}], [{\n\t\ttype: "etyp",\n\t\tname: "ExtendedTypeBox"\n\t},\n\t["tyco"]]],\n\tboxCodes: [],\n\tfullBoxCodes: [],\n\tcontainerBoxCodes: [],\n\tsampleEntryCodes: {},\n\tsampleGroupEntryCodes: [],\n\ttrackGroupTypes: [],\n\tUUIDBoxes: {},\n\tUUIDs: [],\n\tinitialize: function() {\n\t\tBoxParser.FullBox.prototype = new BoxParser.Box,\n\t\tBoxParser.ContainerBox.prototype = new BoxParser.Box,\n\t\tBoxParser.SampleEntry.prototype = new BoxParser.Box,\n\t\tBoxParser.TrackGroupTypeBox.prototype = new BoxParser.FullBox,\n\t\tBoxParser.BASIC_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.FULL_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createFullBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.CONTAINER_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createContainerBoxCtor(t[0].type, t[0].name, null, t[1])\n\t\t})\n\t},\n\tBox: function(t, e, i, r) {\n\t\tthis.type = t,\n\t\tthis.box_name = i,\n\t\tthis.size = e,\n\t\tthis.uuid = r\n\t},\n\tFullBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.flags = 0,\n\t\tthis.version = 0\n\t},\n\tContainerBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.boxes = []\n\t},\n\tSampleEntry: function(t, e, i, r) {\n\t\tBoxParser.ContainerBox.call(this, t, e),\n\t\tthis.hdr_size = i,\n\t\tthis.start = r\n\t},\n\tSampleGroupEntry: function(t) {\n\t\tthis.grouping_type = t\n\t},\n\tTrackGroupTypeBox: function(t, e) {\n\t\tBoxParser.FullBox.call(this, t, e)\n\t},\n\tcreateBoxCtor: function(e, i, t) {\n\t\tBoxParser.boxCodes.push(e),\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.Box.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.Box,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateFullBoxCtor: function(e, i, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.FullBox.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\t\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\tr && r.call(this, t)\n\t\t}\n\t},\n\taddSubBoxArrays: function(t) {\n\t\tif (t) for (var e = (this.subBoxNames = t).length, i = 0; i < e; i++) this[t[i] + "s"] = []\n\t},\n\tcreateContainerBoxCtor: function(e, i, t, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.ContainerBox.call(this, e, t, i),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.ContainerBox,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateMediaSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.sampleEntryCodes[t] = [],\n\t\tBoxParser[t + "SampleEntry"] = function(t, e) {\n\t\t\tBoxParser.SampleEntry.call(this, t, e),\n\t\t\tBoxParser.addSubBoxArrays.call(this, i)\n\t\t},\n\t\tBoxParser[t + "SampleEntry"].prototype = new BoxParser.SampleEntry,\n\t\te && (BoxParser[t + "SampleEntry"].prototype.parse = e)\n\t},\n\tcreateSampleEntryCtor: function(e, i, t, r) {\n\t\tBoxParser.sampleEntryCodes[e].push(i),\n\t\tBoxParser[i + "SampleEntry"] = function(t) {\n\t\t\tBoxParser[e + "SampleEntry"].call(this, i, t),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[i + "SampleEntry"].prototype = new BoxParser[e + "SampleEntry"],\n\t\tt && (BoxParser[i + "SampleEntry"].prototype.parse = t)\n\t},\n\tcreateEncryptedSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.createSampleEntryCtor.call(this, t, e, i, ["sinf"])\n\t},\n\tcreateSampleGroupCtor: function(e, t) {\n\t\tBoxParser[e + "SampleGroupEntry"] = function(t) {\n\t\t\tBoxParser.SampleGroupEntry.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "SampleGroupEntry"].prototype = new BoxParser.SampleGroupEntry,\n\t\tt && (BoxParser[e + "SampleGroupEntry"].prototype.parse = t)\n\t},\n\tcreateTrackGroupCtor: function(e, t) {\n\t\tBoxParser[e + "TrackGroupTypeBox"] = function(t) {\n\t\t\tBoxParser.TrackGroupTypeBox.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "TrackGroupTypeBox"].prototype = new BoxParser.TrackGroupTypeBox,\n\t\tt && (BoxParser[e + "TrackGroupTypeBox"].prototype.parse = t)\n\t},\n\tcreateUUIDBox: function(e, i, r, s, a) {\n\t\tBoxParser.UUIDs.push(e),\n\t\tBoxParser.UUIDBoxes[e] = function(t) { (r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box).call(this, "uuid", t, i, e)\n\t\t},\n\t\tBoxParser.UUIDBoxes[e].prototype = new(r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box),\n\t\ta && (BoxParser.UUIDBoxes[e].prototype.parse = r ?\n\t\tfunction(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\ta && a.call(this, t)\n\t\t}: a)\n\t}\n};\nfunction printPS(t) {\n\tvar e = "<table class=\'inner-table\'>";\n\te += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",\n\te += "<tbody>";\n\tfor (var i = 0; i < t.length; i++) {\n\t\tvar r = t[i];\n\t\te += "<tr>",\n\t\te += "<td>" + r.length + "</td>",\n\t\te += "<td>",\n\t\te += r.nalu.reduce(function(t, e) {\n\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t},\n\t\t"0x"),\n\t\te += "</td></tr>"\n\t}\n\treturn e += "</tbody></table>"\n}\nfunction ColorPoint(t, e) {\n\tthis.x = t,\n\tthis.y = e\n}\nfunction Pixel(t, e) {\n\tthis.bad_pixel_row = t,\n\tthis.bad_pixel_column = e\n}\nBoxParser.initialize(),\nBoxParser.TKHD_FLAG_ENABLED = 1,\nBoxParser.TKHD_FLAG_IN_MOVIE = 2,\nBoxParser.TKHD_FLAG_IN_PREVIEW = 4,\nBoxParser.TFHD_FLAG_BASE_DATA_OFFSET = 1,\nBoxParser.TFHD_FLAG_SAMPLE_DESC = 2,\nBoxParser.TFHD_FLAG_SAMPLE_DUR = 8,\nBoxParser.TFHD_FLAG_SAMPLE_SIZE = 16,\nBoxParser.TFHD_FLAG_SAMPLE_FLAGS = 32,\nBoxParser.TFHD_FLAG_DUR_EMPTY = 65536,\nBoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072,\nBoxParser.TRUN_FLAGS_DATA_OFFSET = 1,\nBoxParser.TRUN_FLAGS_FIRST_FLAG = 4,\nBoxParser.TRUN_FLAGS_DURATION = 256,\nBoxParser.TRUN_FLAGS_SIZE = 512,\nBoxParser.TRUN_FLAGS_FLAGS = 1024,\nBoxParser.TRUN_FLAGS_CTS_OFFSET = 2048,\nBoxParser.Box.prototype.add = function(t) {\n\treturn this.addBox(new BoxParser[t + "Box"])\n},\nBoxParser.Box.prototype.addBox = function(t) {\n\treturn this.boxes.push(t),\n\tthis[t.type + "s"] ? this[t.type + "s"].push(t) : this[t.type] = t,\n\tt\n},\nBoxParser.Box.prototype.set = function(t, e) {\n\treturn this[t] = e,\n\tthis\n},\nBoxParser.Box.prototype.addEntry = function(t, e) {\n\te = e || "entries";\n\treturn this[e] || (this[e] = []),\n\tthis[e].push(t),\n\tthis\n},\n"undefined" != typeof exports && (exports.BoxParser = BoxParser),\nBoxParser.parseUUID = function(t) {\n\treturn BoxParser.parseHex16(t)\n},\nBoxParser.parseHex16 = function(t) {\n\tfor (var e = "",\n\ti = 0; i < 16; i++) {\n\t\tvar r = t.readUint8().toString(16);\n\t\te += 1 === r.length ? "0" + r: r\n\t}\n\treturn e\n},\nBoxParser.parseOneBox = function(t, e, i) {\n\tvar r, s, a = t.getPosition(),\n\tn = 0;\n\tif (t.getEndPosition() - a < 8) return Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tif (i && i < 8) return Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tvar o = t.readUint32(),\n\th = t.readString(4),\n\td = h;\n\tif (Log.debug("BoxParser", "Found box of type \'" + h + "\' and size " + o + " at position " + a), n = 8, "uuid" == h) {\n\t\tif (t.getEndPosition() - t.getPosition() < 16 || i - n < 16) return t.seek(a),\n\t\tLog.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box"),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\tn += 16,\n\t\td = s = BoxParser.parseUUID(t)\n\t}\n\tif (1 == o) {\n\t\tif (t.getEndPosition() - t.getPosition() < 8 || i && i - n < 8) return t.seek(a),\n\t\tLog.warn("BoxParser", \'Not enough data in stream to parse the extended size of the "\' + h + \'" box\'),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\to = t.readUint64(),\n\t\tn += 8\n\t} else if (0 === o) if (i) o = i;\n\telse if ("mdat" !== h) return Log.error("BoxParser", "Unlimited box size not supported for type: \'" + h + "\'"),\n\tr = new BoxParser.Box(h, o),\n\t{\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t};\n\treturn 0 !== o && o < n ? (Log.error("BoxParser", "Box of type " + h + " has an invalid size " + o + " (too small to be a box)"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && i && i < o ? (Log.error("BoxParser", "Box of type \'" + h + "\' has a size " + o + " greater than its container size " + i), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && a + o > t.getEndPosition() ? (t.seek(a), Log.info("BoxParser", "Not enough data in stream to parse the entire \'" + h + "\' box"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : e ? {\n\t\tcode: BoxParser.OK,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}: (BoxParser[h + "Box"] ? r = new BoxParser[h + "Box"](o) : "uuid" !== h ? (Log.warn("BoxParser", "Unknown box type: \'" + h + "\'"), (r = new BoxParser.Box(h, o)).has_unparsed_data = !0) : BoxParser.UUIDBoxes[s] ? r = new BoxParser.UUIDBoxes[s](o) : (Log.warn("BoxParser", "Unknown uuid type: \'" + s + "\'"), (r = new BoxParser.Box(h, o)).uuid = s, r.has_unparsed_data = !0), r.hdr_size = n, r.start = a, r.write === BoxParser.Box.prototype.write && "mdat" !== r.type && (Log.info("BoxParser", "\'" + d + "\' box writing not yet implemented, keeping unparsed data in memory for later write"), r.parseDataAndRewind(t)), r.parse(t), (a = t.getPosition() - (r.start + r.size)) < 0 ? (Log.warn("BoxParser", "Parsing of box \'" + d + "\' did not read the entire indicated box data size (missing " + -a + " bytes), seeking forward"), t.seek(r.start + r.size)) : 0 < a && (Log.error("BoxParser", "Parsing of box \'" + d + "\' read " + a + " more bytes than the indicated box data size, seeking backwards"), 0 !== r.size && t.seek(r.start + r.size)), {\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t})\n},\nBoxParser.Box.prototype.parse = function(t) {\n\t"mdat" != this.type ? this.data = t.readUint8Array(this.size - this.hdr_size) : 0 === this.size ? t.seek(t.getEndPosition()) : t.seek(this.start + this.size)\n},\nBoxParser.Box.prototype.parseDataAndRewind = function(t) {\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseDataAndRewind = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 4,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseFullHeader = function(t) {\n\tthis.version = t.readUint8(),\n\tthis.flags = t.readUint24(),\n\tthis.hdr_size += 4\n},\nBoxParser.FullBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.ContainerBox.prototype.parse = function(t) {\n\tfor (; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tvar e, i = e.box;\n\t\tthis.boxes.push(i),\n\t\tthis.subBoxNames && -1 != this.subBoxNames.indexOf(i.type) ? this[this.subBoxNames[this.subBoxNames.indexOf(i.type)] + "s"].push(i) : this[e = "uuid" !== i.type ? i.type: i.uuid] ? Log.warn("Box of type " + e + " already stored in field of this type") : this[e] = i\n\t}\n},\nBoxParser.Box.prototype.parseLanguage = function(t) {\n\tthis.language = t.readUint16();\n\tt = [];\n\tt[0] = this.language >> 10 & 31,\n\tt[1] = this.language >> 5 & 31,\n\tt[2] = 31 & this.language,\n\tthis.languageString = String.fromCharCode(t[0] + 96, t[1] + 96, t[2] + 96)\n},\nBoxParser.SAMPLE_ENTRY_TYPE_VISUAL = "Visual",\nBoxParser.SAMPLE_ENTRY_TYPE_AUDIO = "Audio",\nBoxParser.SAMPLE_ENTRY_TYPE_HINT = "Hint",\nBoxParser.SAMPLE_ENTRY_TYPE_METADATA = "Metadata",\nBoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE = "Subtitle",\nBoxParser.SAMPLE_ENTRY_TYPE_SYSTEM = "System",\nBoxParser.SAMPLE_ENTRY_TYPE_TEXT = "Text",\nBoxParser.SampleEntry.prototype.parseHeader = function(t) {\n\tt.readUint8Array(6),\n\tthis.data_reference_index = t.readUint16(),\n\tthis.hdr_size += 8\n},\nBoxParser.SampleEntry.prototype.parse = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.SampleEntry.prototype.parseDataAndRewind = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 8,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.SampleEntry.prototype.parseFooter = function(t) {\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n},\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_HINT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL,\nfunction(t) {\n\tvar e;\n\tthis.parseHeader(t),\n\tt.readUint16(),\n\tt.readUint16(),\n\tt.readUint32Array(3),\n\tthis.width = t.readUint16(),\n\tthis.height = t.readUint16(),\n\tthis.horizresolution = t.readUint32(),\n\tthis.vertresolution = t.readUint32(),\n\tt.readUint32(),\n\tthis.frame_count = t.readUint16(),\n\te = Math.min(31, t.readUint8()),\n\tthis.compressorname = t.readString(e),\n\te < 31 && t.readString(31 - e),\n\tthis.depth = t.readUint16(),\n\tt.readUint16(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO,\nfunction(t) {\n\tthis.parseHeader(t),\n\tt.readUint32Array(2),\n\tthis.channel_count = t.readUint16(),\n\tthis.samplesize = t.readUint16(),\n\tt.readUint16(),\n\tt.readUint16(),\n\tthis.samplerate = t.readUint32() / 65536,\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "av01"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dav1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hev1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvt1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "lhe1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvh1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvhe"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvi1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvs1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvcN"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp08"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp09"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avs3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "j2ki"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjp2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjpg"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "uncv"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mp4a"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ec-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "Opus"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "fLaC"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "encv"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "enca"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "encu"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM, "encs"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT, "enct"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "encm"),\nBoxParser.createBoxCtor("a1lx", "AV1LayeredImageIndexingProperty",\nfunction(t) {\n\tvar e = 16 * (1 + (1 & (1 & t.readUint8())));\n\tthis.layer_size = [];\n\tfor (var i = 0; i < 3; i++) this.layer_size[i] = 16 == e ? t.readUint16() : t.readUint32()\n}),\nBoxParser.createBoxCtor("a1op", "OperatingPointSelectorProperty",\nfunction(t) {\n\tthis.op_index = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("auxC", "AuxiliaryTypeProperty",\nfunction(t) {\n\tthis.aux_type = t.readCString();\n\tvar e = this.size - this.hdr_size - (this.aux_type.length + 1);\n\tthis.aux_subtype = t.readUint8Array(e)\n}),\nBoxParser.createBoxCtor("av1C", "AV1CodecConfigurationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tif (1 == (e >> 7 & 1)) if (this.version = 127 & e, 1 === this.version) if (e = t.readUint8(), this.seq_profile = e >> 5 & 7, this.seq_level_idx_0 = 31 & e, e = t.readUint8(), this.seq_tier_0 = e >> 7 & 1, this.high_bitdepth = e >> 6 & 1, this.twelve_bit = e >> 5 & 1, this.monochrome = e >> 4 & 1, this.chroma_subsampling_x = e >> 3 & 1, this.chroma_subsampling_y = e >> 2 & 1, this.chroma_sample_position = 3 & e, e = t.readUint8(), this.reserved_1 = e >> 5 & 7, 0 === this.reserved_1) {\n\t\tif (this.initial_presentation_delay_present = e >> 4 & 1, 1 === this.initial_presentation_delay_present) this.initial_presentation_delay_minus_one = 15 & e;\n\t\telse if (this.reserved_2 = 15 & e, 0 !== this.reserved_2) return void Log.error("av1C reserved_2 parsing problem");\n\t\te = this.size - this.hdr_size - 4;\n\t\tthis.configOBUs = t.readUint8Array(e)\n\t} else Log.error("av1C reserved_1 parsing problem");\n\telse Log.error("av1C version " + this.version + " not supported");\n\telse Log.error("av1C marker problem")\n}),\nBoxParser.createBoxCtor("avcC", "AVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (this.configurationVersion = t.readUint8(), this.AVCProfileIndication = t.readUint8(), this.profile_compatibility = t.readUint8(), this.AVCLevelIndication = t.readUint8(), this.lengthSizeMinusOne = 3 & t.readUint8(), this.nb_SPS_nalus = 31 & t.readUint8(), i = this.size - this.hdr_size - 6, this.SPS = [], this.SPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_SPS_nalus; e++) this.SPS[e] = {},\n\tthis.SPS[e].length = t.readUint16(),\n\tthis.SPS[e].nalu = t.readUint8Array(this.SPS[e].length),\n\ti -= 2 + this.SPS[e].length;\n\tfor (this.nb_PPS_nalus = t.readUint8(), i--, this.PPS = [], this.PPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_PPS_nalus; e++) this.PPS[e] = {},\n\tthis.PPS[e].length = t.readUint16(),\n\tthis.PPS[e].nalu = t.readUint8Array(this.PPS[e].length),\n\ti -= 2 + this.PPS[e].length;\n\t0 < i && (this.ext = t.readUint8Array(i))\n}),\nBoxParser.createBoxCtor("btrt", "BitRateBox",\nfunction(t) {\n\tthis.bufferSizeDB = t.readUint32(),\n\tthis.maxBitrate = t.readUint32(),\n\tthis.avgBitrate = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("ccst", "CodingConstraintsBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.all_ref_pics_intra = 128 == (128 & e),\n\tthis.intra_pred_used = 64 == (64 & e),\n\tthis.max_ref_per_pic = (63 & e) >> 2,\n\tt.readUint24()\n}),\nBoxParser.createBoxCtor("cdef", "ComponentDefinitionBox",\nfunction(t) {\n\tvar e;\n\tfor (this.channel_count = t.readUint16(), this.channel_indexes = [], this.channel_types = [], this.channel_associations = [], e = 0; e < this.channel_count; e++) this.channel_indexes.push(t.readUint16()),\n\tthis.channel_types.push(t.readUint16()),\n\tthis.channel_associations.push(t.readUint16())\n}),\nBoxParser.createBoxCtor("clap", "CleanApertureBox",\nfunction(t) {\n\tthis.cleanApertureWidthN = t.readUint32(),\n\tthis.cleanApertureWidthD = t.readUint32(),\n\tthis.cleanApertureHeightN = t.readUint32(),\n\tthis.cleanApertureHeightD = t.readUint32(),\n\tthis.horizOffN = t.readUint32(),\n\tthis.horizOffD = t.readUint32(),\n\tthis.vertOffN = t.readUint32(),\n\tthis.vertOffD = t.readUint32()\n}),\nBoxParser.createBoxCtor("clli", "ContentLightLevelBox",\nfunction(t) {\n\tthis.max_content_light_level = t.readUint16(),\n\tthis.max_pic_average_light_level = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("cmex", "CameraExtrinsicMatrixProperty",\nfunction(t) {\n\t1 & this.flags && (this.pos_x = t.readInt32()),\n\t2 & this.flags && (this.pos_y = t.readInt32()),\n\t4 & this.flags && (this.pos_z = t.readInt32()),\n\t8 & this.flags && (0 == this.version ? 16 & this.flags ? (this.quat_x = t.readInt32(), this.quat_y = t.readInt32(), this.quat_z = t.readInt32()) : (this.quat_x = t.readInt16(), this.quat_y = t.readInt16(), this.quat_z = t.readInt16()) : this.version),\n\t32 & this.flags && (this.id = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("cmin", "CameraIntrinsicMatrixProperty",\nfunction(t) {\n\tthis.focal_length_x = t.readInt32(),\n\tthis.principal_point_x = t.readInt32(),\n\tthis.principal_point_y = t.readInt32(),\n\t1 & this.flags && (this.focal_length_y = t.readInt32(), this.skew_factor = t.readInt32())\n}),\nBoxParser.createBoxCtor("cmpd", "ComponentDefinitionBox",\nfunction(t) {\n\tfor (this.component_count = t.readUint32(), this.component_types = [], this.component_type_urls = [], i = 0; i < this.component_count; i++) {\n\t\tvar e = t.readUint16();\n\t\tthis.component_types.push(e),\n\t\t32768 <= e && this.component_type_urls.push(t.readCString())\n\t}\n}),\nBoxParser.createFullBoxCtor("co64", "ChunkLargeOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (e = 0; e < i; e++) this.chunk_offsets.push(t.readUint64())\n}),\nBoxParser.createFullBoxCtor("CoLL", "ContentLightLevelBox",\nfunction(t) {\n\tthis.maxCLL = t.readUint16(),\n\tthis.maxFALL = t.readUint16()\n}),\nBoxParser.createBoxCtor("colr", "ColourInformationBox",\nfunction(t) {\n\tvar e;\n\tthis.colour_type = t.readString(4),\n\t"nclx" === this.colour_type ? (this.colour_primaries = t.readUint16(), this.transfer_characteristics = t.readUint16(), this.matrix_coefficients = t.readUint16(), e = t.readUint8(), this.full_range_flag = e >> 7) : "rICC" !== this.colour_type && "prof" !== this.colour_type || (this.ICC_profile = t.readUint8Array(this.size - 4))\n}),\nBoxParser.createFullBoxCtor("cprt", "CopyrightBox",\nfunction(t) {\n\tthis.parseLanguage(t),\n\tthis.notice = t.readCString()\n}),\nBoxParser.createFullBoxCtor("cslg", "CompositionToDecodeBox",\nfunction(t) {\n\t0 === this.version && (this.compositionToDTSShift = t.readInt32(), this.leastDecodeToDisplayDelta = t.readInt32(), this.greatestDecodeToDisplayDelta = t.readInt32(), this.compositionStartTime = t.readInt32(), this.compositionEndTime = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("ctts", "CompositionOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.sample_counts = [], this.sample_offsets = [], 0 === this.version) for (e = 0; e < i; e++) {\n\t\tthis.sample_counts.push(t.readUint32());\n\t\tvar r = t.readInt32();\n\t\tr < 0 && Log.warn("BoxParser", "ctts box uses negative values without using version 1"),\n\t\tthis.sample_offsets.push(r)\n\t} else if (1 == this.version) for (e = 0; e < i; e++) this.sample_counts.push(t.readUint32()),\n\tthis.sample_offsets.push(t.readInt32())\n}),\nBoxParser.createBoxCtor("dac3", "AC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint8(),\n\ti = t.readUint8(),\n\tt = t.readUint8();\n\tthis.fscod = e >> 6,\n\tthis.bsid = e >> 1 & 31,\n\tthis.bsmod = (1 & e) << 2 | i >> 6 & 3,\n\tthis.acmod = i >> 3 & 7,\n\tthis.lfeon = i >> 2 & 1,\n\tthis.bit_rate_code = 3 & i | t >> 5 & 7\n}),\nBoxParser.createBoxCtor("dec3", "EC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint16();\n\tthis.data_rate = e >> 3,\n\tthis.num_ind_sub = 7 & e,\n\tthis.ind_subs = [];\n\tfor (var i = 0; i < this.num_ind_sub + 1; i++) {\n\t\tvar r = {};\n\t\tthis.ind_subs.push(r);\n\t\tvar s = t.readUint8(),\n\t\ta = t.readUint8(),\n\t\tn = t.readUint8();\n\t\tr.fscod = s >> 6,\n\t\tr.bsid = s >> 1 & 31,\n\t\tr.bsmod = (1 & s) << 4 | a >> 4 & 15,\n\t\tr.acmod = a >> 1 & 7,\n\t\tr.lfeon = 1 & a,\n\t\tr.num_dep_sub = n >> 1 & 15,\n\t\t0 < r.num_dep_sub && (r.chan_loc = (1 & n) << 8 | t.readUint8())\n\t}\n}),\nBoxParser.createFullBoxCtor("dfLa", "FLACSpecificBox",\nfunction(t) {\n\tfor (var e = [], i = ["STREAMINFO", "PADDING", "APPLICATION", "SEEKTABLE", "VORBIS_COMMENT", "CUESHEET", "PICTURE", "RESERVED"];;) {\n\t\tvar r = t.readUint8(),\n\t\ts = Math.min(127 & r, i.length - 1);\n\t\tif (s ? t.readUint8Array(t.readUint24()) : (t.readUint8Array(13), this.samplerate = t.readUint32() >> 12, t.readUint8Array(20)), e.push(i[s]), 128 & r) break\n\t}\n\tthis.numMetadataBlocks = e.length + " (" + e.join(", ") + ")"\n}),\nBoxParser.createBoxCtor("dimm", "hintimmediateBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dmax", "hintlongestpacket",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("dmed", "hintmediaBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dOps", "OpusSpecificBox",\nfunction(t) {\n\tif (this.Version = t.readUint8(), this.OutputChannelCount = t.readUint8(), this.PreSkip = t.readUint16(), this.InputSampleRate = t.readUint32(), this.OutputGain = t.readInt16(), this.ChannelMappingFamily = t.readUint8(), 0 !== this.ChannelMappingFamily) {\n\t\tthis.StreamCount = t.readUint8(),\n\t\tthis.CoupledCount = t.readUint8(),\n\t\tthis.ChannelMapping = [];\n\t\tfor (var e = 0; e < this.OutputChannelCount; e++) this.ChannelMapping[e] = t.readUint8()\n\t}\n}),\nBoxParser.createFullBoxCtor("dref", "DataReferenceBox",\nfunction(t) {\n\tvar e;\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\te = e.box,\n\t\tthis.entries.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("drep", "hintrepeatedBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("elng", "ExtendedLanguageBox",\nfunction(t) {\n\tthis.extended_language = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("elst", "EditListBox",\nfunction(t) {\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\t1 === this.version ? (r.segment_duration = t.readUint64(), r.media_time = t.readInt64()) : (r.segment_duration = t.readUint32(), r.media_time = t.readInt32()),\n\t\tr.media_rate_integer = t.readInt16(),\n\t\tr.media_rate_fraction = t.readInt16()\n\t}\n}),\nBoxParser.createFullBoxCtor("emsg", "EventMessageBox",\nfunction(t) {\n\t1 == this.version ? (this.timescale = t.readUint32(), this.presentation_time = t.readUint64(), this.event_duration = t.readUint32(), this.id = t.readUint32(), this.scheme_id_uri = t.readCString(), this.value = t.readCString()) : (this.scheme_id_uri = t.readCString(), this.value = t.readCString(), this.timescale = t.readUint32(), this.presentation_time_delta = t.readUint32(), this.event_duration = t.readUint32(), this.id = t.readUint32());\n\tvar e = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));\n\t1 == this.version && (e -= 4),\n\tthis.message_data = t.readUint8Array(e)\n}),\nBoxParser.createEntityToGroupCtor = function(e, r) {\n\tBoxParser[e + "Box"] = function(t) {\n\t\tBoxParser.FullBox.call(this, e, t)\n\t},\n\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\tif (this.parseFullHeader(t), r) r.call(this, t);\n\t\telse for (this.group_id = t.readUint32(), this.num_entities_in_group = t.readUint32(), this.entity_ids = [], i = 0; i < this.num_entities_in_group; i++) {\n\t\t\tvar e = t.readUint32();\n\t\t\tthis.entity_ids.push(e)\n\t\t}\n\t}\n},\nBoxParser.createEntityToGroupCtor("aebr"),\nBoxParser.createEntityToGroupCtor("afbr"),\nBoxParser.createEntityToGroupCtor("albc"),\nBoxParser.createEntityToGroupCtor("altr"),\nBoxParser.createEntityToGroupCtor("brst"),\nBoxParser.createEntityToGroupCtor("dobr"),\nBoxParser.createEntityToGroupCtor("eqiv"),\nBoxParser.createEntityToGroupCtor("favc"),\nBoxParser.createEntityToGroupCtor("fobr"),\nBoxParser.createEntityToGroupCtor("iaug"),\nBoxParser.createEntityToGroupCtor("pano"),\nBoxParser.createEntityToGroupCtor("slid"),\nBoxParser.createEntityToGroupCtor("ster"),\nBoxParser.createEntityToGroupCtor("tsyn"),\nBoxParser.createEntityToGroupCtor("wbbr"),\nBoxParser.createEntityToGroupCtor("prgr"),\nBoxParser.createEntityToGroupCtor("pymd",\nfunction(t) {\n\tthis.group_id = t.readUint32(),\n\tthis.num_entities_in_group = t.readUint32(),\n\tthis.entity_ids = [];\n\tfor (var e = 0; e < this.num_entities_in_group; e++) {\n\t\tvar i = t.readUint32();\n\t\tthis.entity_ids.push(i)\n\t}\n\tfor (this.tile_size_x = t.readUint16(), this.tile_size_y = t.readUint16(), this.layer_binning = [], this.tiles_in_layer_column_minus1 = [], this.tiles_in_layer_row_minus1 = [], e = 0; e < this.num_entities_in_group; e++) this.layer_binning[e] = t.readUint16(),\n\tthis.tiles_in_layer_row_minus1[e] = t.readUint16(),\n\tthis.tiles_in_layer_column_minus1[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("esds", "ElementaryStreamDescriptorBox",\nfunction(t) {\n\tvar e = t.readUint8Array(this.size - this.hdr_size);\n\tvoid 0 !== MPEG4DescriptorParser && (t = new MPEG4DescriptorParser, this.esd = t.parseOneDescriptor(new DataStream(e.buffer, 0, DataStream.BIG_ENDIAN)))\n}),\nBoxParser.createBoxCtor("fiel", "FieldHandlingBox",\nfunction(t) {\n\tthis.fieldCount = t.readUint8(),\n\tthis.fieldOrdering = t.readUint8()\n}),\nBoxParser.createBoxCtor("frma", "OriginalFormatBox",\nfunction(t) {\n\tthis.data_format = t.readString(4)\n}),\nBoxParser.createBoxCtor("ftyp", "FileTypeBox",\nfunction(t) {\n\tvar e = this.size - this.hdr_size;\n\tthis.major_brand = t.readString(4),\n\tthis.minor_version = t.readUint32(),\n\te -= 8,\n\tthis.compatible_brands = [];\n\tfor (var i = 0; 4 <= e;) this.compatible_brands[i] = t.readString(4),\n\te -= 4,\n\ti++\n}),\nBoxParser.createFullBoxCtor("hdlr", "HandlerBox",\nfunction(t) {\n\t0 === this.version && (t.readUint32(), this.handler = t.readString(4), t.readUint32Array(3), this.name = t.readString(this.size - this.hdr_size - 20), "\0" === this.name[this.name.length - 1] && (this.name = this.name.slice(0, -1)))\n}),\nBoxParser.createBoxCtor("hvcC", "HEVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tthis.configurationVersion = t.readUint8(),\n\ti = t.readUint8(),\n\tthis.general_profile_space = i >> 6,\n\tthis.general_tier_flag = (32 & i) >> 5,\n\tthis.general_profile_idc = 31 & i,\n\tthis.general_profile_compatibility = t.readUint32(),\n\tthis.general_constraint_indicator = t.readUint8Array(6),\n\tthis.general_level_idc = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\tthis.chroma_format_idc = 3 & t.readUint8(),\n\tthis.bit_depth_luma_minus8 = 7 & t.readUint8(),\n\tthis.bit_depth_chroma_minus8 = 7 & t.readUint8(),\n\tthis.avgFrameRate = t.readUint16(),\n\ti = t.readUint8(),\n\tthis.constantFrameRate = i >> 6,\n\tthis.numTemporalLayers = (13 & i) >> 3,\n\tthis.temporalIdNested = (4 & i) >> 2,\n\tthis.lengthSizeMinusOne = 3 & i,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var r = t.readUint8(), s = 0; s < r; s++) {\n\t\tvar a = [];\n\t\tthis.nalu_arrays.push(a),\n\t\ti = t.readUint8(),\n\t\ta.completeness = (128 & i) >> 7,\n\t\ta.nalu_type = 63 & i;\n\t\tfor (var n = t.readUint16(), o = 0; o < n; o++) {\n\t\t\tvar h = {};\n\t\t\ta.push(h),\n\t\t\te = t.readUint16(),\n\t\t\th.data = t.readUint8Array(e)\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iinf", "ItemInfoBox",\nfunction(t) {\n\tvar e;\n\t0 === this.version ? this.entry_count = t.readUint16() : this.entry_count = t.readUint32(),\n\tthis.item_infos = [];\n\tfor (var i = 0; i < this.entry_count; i++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\t"infe" !== e.box.type && Log.error("BoxParser", "Expected \'infe\' box, got " + e.box.type),\n\t\tthis.item_infos[i] = e.box\n\t}\n}),\nBoxParser.createFullBoxCtor("iloc", "ItemLocationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.offset_size = e >> 4 & 15,\n\tthis.length_size = 15 & e,\n\te = t.readUint8(),\n\tthis.base_offset_size = e >> 4 & 15,\n\t1 === this.version || 2 === this.version ? this.index_size = 15 & e: this.index_size = 0,\n\tthis.items = [];\n\tvar i = 0;\n\tif (this.version < 2) i = t.readUint16();\n\telse {\n\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\ti = t.readUint32()\n\t}\n\tfor (var r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tif (this.items.push(s), this.version < 2) s.item_ID = t.readUint16();\n\t\telse {\n\t\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\t\ts.item_ID = t.readUint32()\n\t\t}\n\t\tswitch (1 === this.version || 2 === this.version ? s.construction_method = 15 & t.readUint16() : s.construction_method = 0, s.data_reference_index = t.readUint16(), this.base_offset_size) {\n\t\tcase 0:\n\t\t\ts.base_offset = 0;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ts.base_offset = t.readUint32();\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ts.base_offset = t.readUint64();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "Error reading base offset size"\n\t\t}\n\t\tvar a = t.readUint16();\n\t\ts.extents = [];\n\t\tfor (var n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\tif (s.extents.push(o), 1 === this.version || 2 === this.version) switch (this.index_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_index = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_index = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_index = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.offset_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_offset = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_offset = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_offset = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.length_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_length = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_length = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_length = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("imir", "ImageMirror",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.reserved = t >> 7,\n\tthis.axis = 1 & t\n}),\nBoxParser.createFullBoxCtor("infe", "ItemInfoEntry",\nfunction(t) {\n\treturn 0 !== this.version && 1 !== this.version || (this.item_ID = t.readUint16(), this.item_protection_index = t.readUint16(), this.item_name = t.readCString(), this.content_type = t.readCString(), this.content_encoding = t.readCString()),\n\t1 === this.version ? (this.extension_type = t.readString(4), Log.warn("BoxParser", "Cannot parse extension type"), void t.seek(this.start + this.size)) : void(2 <= this.version && (2 === this.version ? this.item_ID = t.readUint16() : 3 === this.version && (this.item_ID = t.readUint32()), this.item_protection_index = t.readUint16(), this.item_type = t.readString(4), this.item_name = t.readCString(), "mime" === this.item_type ? (this.content_type = t.readCString(), this.content_encoding = t.readCString()) : "uri " === this.item_type && (this.item_uri_type = t.readCString())))\n}),\nBoxParser.createFullBoxCtor("ipma", "ItemPropertyAssociationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (entry_count = t.readUint32(), this.associations = [], e = 0; e < entry_count; e++) {\n\t\tvar r = {};\n\t\tthis.associations.push(r),\n\t\tthis.version < 1 ? r.id = t.readUint16() : r.id = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tfor (r.props = [], i = 0; i < s; i++) {\n\t\t\tvar a = t.readUint8(),\n\t\t\tn = {};\n\t\t\tr.props.push(n),\n\t\t\tn.essential = (128 & a) >> 7 == 1,\n\t\t\t1 & this.flags ? n.property_index = (127 & a) << 8 | t.readUint8() : n.property_index = 127 & a\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iref", "ItemReferenceBox",\nfunction(t) {\n\tvar e;\n\tfor (this.references = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new(0 === this.version ? BoxParser.SingleItemTypeReferenceBox: BoxParser.SingleItemTypeReferenceBoxLarge)(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.warn("BoxParser", e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.references.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("irot", "ImageRotation",\nfunction(t) {\n\tthis.angle = 3 & t.readUint8()\n}),\nBoxParser.createFullBoxCtor("ispe", "ImageSpatialExtentsProperty",\nfunction(t) {\n\tthis.image_width = t.readUint32(),\n\tthis.image_height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("kind", "KindBox",\nfunction(t) {\n\tthis.schemeURI = t.readCString(),\n\tthis.value = t.readCString()\n}),\nBoxParser.createFullBoxCtor("leva", "LevelAssignmentBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.levels = [];\n\tfor (var i = 0; i < e; i++) {\n\t\tvar r = {}; (this.levels[i] = r).track_ID = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tswitch (r.padding_flag = s >> 7, r.assignment_type = 127 & s, r.assignment_type) {\n\t\tcase 0:\n\t\t\tr.grouping_type = t.readString(4);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tr.grouping_type = t.readString(4),\n\t\t\tr.grouping_type_parameter = t.readUint32();\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tr.sub_track_id = t.readUint32();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLog.warn("BoxParser", "Unknown leva assignement type")\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lhvC", "LHEVCConfigurationBox",\nfunction(t) {\n\tvar e;\n\tthis.configurationVersion = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\te = t.readUint8(),\n\tthis.numTemporalLayers = (13 & e) >> 3,\n\tthis.temporalIdNested = (4 & e) >> 2,\n\tthis.lengthSizeMinusOne = 3 & e,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = [];\n\t\tthis.nalu_arrays.push(s),\n\t\te = t.readUint8(),\n\t\ts.completeness = (128 & e) >> 7,\n\t\ts.nalu_type = 63 & e;\n\t\tfor (var a = t.readUint16(), n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\ts.push(o);\n\t\t\tvar h = t.readUint16();\n\t\t\to.data = t.readUint8Array(h)\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lsel", "LayerSelectorProperty",\nfunction(t) {\n\tthis.layer_id = t.readUint16()\n}),\nBoxParser.createBoxCtor("maxr", "hintmaxrate",\nfunction(t) {\n\tthis.period = t.readUint32(),\n\tthis.bytes = t.readUint32()\n}),\nColorPoint.prototype.toString = function() {\n\treturn "(" + this.x + "," + this.y + ")"\n},\nBoxParser.createBoxCtor("mdcv", "MasteringDisplayColourVolumeBox",\nfunction(t) {\n\tthis.display_primaries = [],\n\tthis.display_primaries[0] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[1] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[2] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.white_point = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.max_display_mastering_luminance = t.readUint32(),\n\tthis.min_display_mastering_luminance = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mdhd", "MediaHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.parseLanguage(t),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("mehd", "MovieExtendsHeaderBox",\nfunction(t) {\n\t1 & this.flags && (Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1"), this.version = 1),\n\t1 == this.version ? this.fragment_duration = t.readUint64() : this.fragment_duration = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("meta", "MetaBox",\nfunction(t) {\n\tthis.boxes = [],\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("mfhd", "MovieFragmentHeaderBox",\nfunction(t) {\n\tthis.sequence_number = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mfro", "MovieFragmentRandomAccessOffsetBox",\nfunction(t) {\n\tthis._size = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mskC", "MaskConfigurationProperty",\nfunction(t) {\n\tthis.bits_per_pixel = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("mvhd", "MovieHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.rate = t.readUint32(),\n\tthis.volume = t.readUint16() >> 8,\n\tt.readUint16(),\n\tt.readUint32Array(2),\n\tthis.matrix = t.readUint32Array(9),\n\tt.readUint32Array(6),\n\tthis.next_track_id = t.readUint32()\n}),\nBoxParser.createBoxCtor("npck", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint32()\n}),\nBoxParser.createBoxCtor("nump", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("padb", "PaddingBitsBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.padbits = [];\n\tfor (var i = 0; i < Math.floor((e + 1) / 2); i++) this.padbits = t.readUint8()\n}),\nBoxParser.createBoxCtor("pasp", "PixelAspectRatioBox",\nfunction(t) {\n\tthis.hSpacing = t.readUint32(),\n\tthis.vSpacing = t.readUint32()\n}),\nBoxParser.createBoxCtor("payl", "CuePayloadBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createBoxCtor("payt", "hintpayloadID",\nfunction(t) {\n\tthis.payloadID = t.readUint32();\n\tvar e = t.readUint8();\n\tthis.rtpmap_string = t.readString(e)\n}),\nBoxParser.createFullBoxCtor("pdin", "ProgressiveDownloadInfoBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 8;\n\tthis.rate = [],\n\tthis.initial_delay = [];\n\tfor (var i = 0; i < e; i++) this.rate[i] = t.readUint32(),\n\tthis.initial_delay[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pitm", "PrimaryItemBox",\nfunction(t) {\n\t0 === this.version ? this.item_id = t.readUint16() : this.item_id = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pixi", "PixelInformationProperty",\nfunction(t) {\n\tvar e;\n\tfor (this.num_channels = t.readUint8(), this.bits_per_channels = [], e = 0; e < this.num_channels; e++) this.bits_per_channels[e] = t.readUint8()\n}),\nBoxParser.createBoxCtor("pmax", "hintlargestpacket",\nfunction(t) {\n\tthis.bytes = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prdi", "ProgressiveDerivedImageItemInformationProperty",\nfunction(t) {\n\tif (this.step_count = t.readUint16(), this.item_count = [], 2 & this.flags) for (var e = 0; e < this.step_count; e++) this.item_count[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("prft", "ProducerReferenceTimeBox",\nfunction(t) {\n\tthis.ref_track_id = t.readUint32(),\n\tthis.ntp_timestamp = t.readUint64(),\n\t0 === this.version ? this.media_time = t.readUint32() : this.media_time = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("pssh", "ProtectionSystemSpecificHeaderBox",\nfunction(t) {\n\tif (this.system_id = BoxParser.parseHex16(t), 0 < this.version) {\n\t\tvar e = t.readUint32();\n\t\tthis.kid = [];\n\t\tfor (var i = 0; i < e; i++) this.kid[i] = BoxParser.parseHex16(t)\n\t}\n\tvar r = t.readUint32();\n\t0 < r && (this.data = t.readUint8Array(r))\n}),\nBoxParser.createFullBoxCtor("clef", "TrackCleanApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("enof", "TrackEncodedPixelsDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prof", "TrackProductionApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createContainerBoxCtor("tapt", "TrackApertureModeDimensionsBox", null, ["clef", "prof", "enof"]),\nBoxParser.createBoxCtor("rtp ", "rtpmoviehintinformation",\nfunction(t) {\n\tthis.descriptionformat = t.readString(4),\n\tthis.sdptext = t.readString(this.size - this.hdr_size - 4)\n}),\nBoxParser.createFullBoxCtor("saio", "SampleAuxiliaryInformationOffsetsBox",\nfunction(t) {\n\t1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32());\n\tvar e = t.readUint32();\n\tthis.offset = [];\n\tfor (var i = 0; i < e; i++) 0 === this.version ? this.offset[i] = t.readUint32() : this.offset[i] = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("saiz", "SampleAuxiliaryInformationSizesBox",\nfunction(t) {\n\tif (1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32()), this.default_sample_info_size = t.readUint8(), this.sample_count = t.readUint32(), this.sample_info_size = [], 0 === this.default_sample_info_size) for (var e = 0; e < this.sample_count; e++) this.sample_info_size[e] = t.readUint8()\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "mett",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "metx",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "sbtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stpp",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.auxiliary_mime_types = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stxt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "tx3g",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.displayFlags = t.readUint32(),\n\tthis.horizontal_justification = t.readInt8(),\n\tthis.vertical_justification = t.readInt8(),\n\tthis.bg_color_rgba = t.readUint8Array(4),\n\tthis.box_record = t.readInt16Array(4),\n\tthis.style_record = t.readUint8Array(12),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "wvtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleGroupCtor("alst",\nfunction(t) {\n\tvar e, i = t.readUint16();\n\tfor (this.first_output_sample = t.readUint16(), this.sample_offset = [], e = 0; e < i; e++) this.sample_offset[e] = t.readUint32();\n\tvar r = this.description_length - 4 - 4 * i;\n\tfor (this.num_output_samples = [], this.num_total_samples = [], e = 0; e < r / 4; e++) this.num_output_samples[e] = t.readUint16(),\n\tthis.num_total_samples[e] = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avll",\nfunction(t) {\n\tthis.layerNumber = t.readUint8(),\n\tthis.accurateStatisticsFlag = t.readUint8(),\n\tthis.avgBitRate = t.readUint16(),\n\tthis.avgFrameRate = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avss",\nfunction(t) {\n\tthis.subSequenceIdentifier = t.readUint16(),\n\tthis.layerNumber = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.durationFlag = e >> 7,\n\tthis.avgRateFlag = e >> 6 & 1,\n\tthis.durationFlag && (this.duration = t.readUint32()),\n\tthis.avgRateFlag && (this.accurateStatisticsFlag = t.readUint8(), this.avgBitRate = t.readUint16(), this.avgFrameRate = t.readUint16()),\n\tthis.dependency = [];\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tthis.dependency.push(s),\n\t\ts.subSeqDirectionFlag = t.readUint8(),\n\t\ts.layerNumber = t.readUint8(),\n\t\ts.subSequenceIdentifier = t.readUint16()\n\t}\n}),\nBoxParser.createSampleGroupCtor("dtrt",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("mvif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("prol",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.createSampleGroupCtor("rap ",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.num_leading_samples_known = t >> 7,\n\tthis.num_leading_samples = 127 & t\n}),\nBoxParser.createSampleGroupCtor("rash",\nfunction(t) {\n\tif (this.operation_point_count = t.readUint16(), this.description_length !== 2 + (1 === this.operation_point_count ? 2 : 6 * this.operation_point_count) + 9) Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length"),\n\tthis.data = t.readUint8Array(this.description_length - 2);\n\telse {\n\t\tif (1 === this.operation_point_count) this.target_rate_share = t.readUint16();\n\t\telse {\n\t\t\tthis.target_rate_share = [],\n\t\t\tthis.available_bitrate = [];\n\t\t\tfor (var e = 0; e < this.operation_point_count; e++) this.available_bitrate[e] = t.readUint32(),\n\t\t\tthis.target_rate_share[e] = t.readUint16()\n\t\t}\n\t\tthis.maximum_bitrate = t.readUint32(),\n\t\tthis.minimum_bitrate = t.readUint32(),\n\t\tthis.discard_priority = t.readUint8()\n\t}\n}),\nBoxParser.createSampleGroupCtor("roll",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.SampleGroupEntry.prototype.parse = function(t) {\n\tLog.warn("BoxParser", "Unknown Sample Group type: " + this.grouping_type),\n\tthis.data = t.readUint8Array(this.description_length)\n},\nBoxParser.createSampleGroupCtor("scif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("scnm",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("seig",\nfunction(t) {\n\tthis.reserved = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.crypt_byte_block = e >> 4,\n\tthis.skip_byte_block = 15 & e,\n\tthis.isProtected = t.readUint8(),\n\tthis.Per_Sample_IV_Size = t.readUint8(),\n\tthis.KID = BoxParser.parseHex16(t),\n\tthis.constant_IV_size = 0,\n\tthis.constant_IV = 0,\n\t1 === this.isProtected && 0 === this.Per_Sample_IV_Size && (this.constant_IV_size = t.readUint8(), this.constant_IV = t.readUint8Array(this.constant_IV_size))\n}),\nBoxParser.createSampleGroupCtor("stsa",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("sync",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.NAL_unit_type = 63 & t\n}),\nBoxParser.createSampleGroupCtor("tele",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.level_independently_decodable = t >> 7\n}),\nBoxParser.createSampleGroupCtor("tsas",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("tscl",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("vipr",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createFullBoxCtor("sbgp", "SampleToGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\t1 === this.version ? this.grouping_type_parameter = t.readUint32() : this.grouping_type_parameter = 0,\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\tr.sample_count = t.readInt32(),\n\t\tr.group_description_index = t.readInt32()\n\t}\n}),\nPixel.prototype.toString = function() {\n\treturn "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]"\n},\nBoxParser.createFullBoxCtor("sbpm", "SensorBadPixelsMapBox",\nfunction(t) {\n\tvar e;\n\tfor (this.component_count = t.readUint16(), this.component_index = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16());\n\tvar i = t.readUint8();\n\tfor (this.correction_applied = 128 == (128 & i), this.num_bad_rows = t.readUint32(), this.num_bad_cols = t.readUint32(), this.num_bad_pixels = t.readUint32(), this.bad_rows = [], this.bad_columns = [], this.bad_pixels = [], e = 0; e < this.num_bad_rows; e++) this.bad_rows.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_cols; e++) this.bad_columns.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_pixels; e++) {\n\t\tvar r = t.readUint32(),\n\t\ts = t.readUint32();\n\t\tthis.bad_pixels.push(new Pixel(r, s))\n\t}\n}),\nBoxParser.createFullBoxCtor("schm", "SchemeTypeBox",\nfunction(t) {\n\tthis.scheme_type = t.readString(4),\n\tthis.scheme_version = t.readUint32(),\n\t1 & this.flags && (this.scheme_uri = t.readString(this.size - this.hdr_size - 8))\n}),\nBoxParser.createBoxCtor("sdp ", "rtptracksdphintinformation",\nfunction(t) {\n\tthis.sdptext = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("sdtp", "SampleDependencyTypeBox",\nfunction(t) {\n\tvar e, i = this.size - this.hdr_size;\n\tthis.is_leading = [],\n\tthis.sample_depends_on = [],\n\tthis.sample_is_depended_on = [],\n\tthis.sample_has_redundancy = [];\n\tfor (var r = 0; r < i; r++) e = t.readUint8(),\n\tthis.is_leading[r] = e >> 6,\n\tthis.sample_depends_on[r] = e >> 4 & 3,\n\tthis.sample_is_depended_on[r] = e >> 2 & 3,\n\tthis.sample_has_redundancy[r] = 3 & e\n}),\nBoxParser.createFullBoxCtor("senc", "SampleEncryptionBox"),\nBoxParser.createFullBoxCtor("sgpd", "SampleGroupDescriptionBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\tLog.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type),\n\t1 === this.version ? this.default_length = t.readUint32() : this.default_length = 0,\n\t2 <= this.version && (this.default_group_description_index = t.readUint32()),\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = new(BoxParser[this.grouping_type + "SampleGroupEntry"] ? BoxParser[this.grouping_type + "SampleGroupEntry"] : BoxParser.SampleGroupEntry)(this.grouping_type);\n\t\tthis.entries.push(r),\n\t\t1 === this.version && 0 === this.default_length ? r.description_length = t.readUint32() : r.description_length = this.default_length,\n\t\tr.write === BoxParser.SampleGroupEntry.prototype.write && (Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write"), r.data = t.readUint8Array(r.description_length), t.position -= r.description_length),\n\t\tr.parse(t)\n\t}\n}),\nBoxParser.createFullBoxCtor("sidx", "CompressedSegmentIndexBox",\nfunction(t) {\n\tthis.reference_ID = t.readUint32(),\n\tthis.timescale = t.readUint32(),\n\t0 === this.version ? (this.earliest_presentation_time = t.readUint32(), this.first_offset = t.readUint32()) : (this.earliest_presentation_time = t.readUint64(), this.first_offset = t.readUint64()),\n\tt.readUint16(),\n\tthis.references = [];\n\tfor (var e = t.readUint16(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.references.push(r);\n\t\tvar s = t.readUint32();\n\t\tr.reference_type = s >> 31 & 1,\n\t\tr.referenced_size = 2147483647 & s,\n\t\tr.subsegment_duration = t.readUint32(),\n\t\ts = t.readUint32(),\n\t\tr.starts_with_SAP = s >> 31 & 1,\n\t\tr.SAP_type = s >> 28 & 7,\n\t\tr.SAP_delta_time = 268435455 & s\n\t}\n}),\nBoxParser.SingleItemTypeReferenceBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBox.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBox.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint16();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint16()\n},\nBoxParser.SingleItemTypeReferenceBoxLarge = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint32()\n},\nBoxParser.createFullBoxCtor("SmDm", "SMPTE2086MasteringDisplayMetadataBox",\nfunction(t) {\n\tthis.primaryRChromaticity_x = t.readUint16(),\n\tthis.primaryRChromaticity_y = t.readUint16(),\n\tthis.primaryGChromaticity_x = t.readUint16(),\n\tthis.primaryGChromaticity_y = t.readUint16(),\n\tthis.primaryBChromaticity_x = t.readUint16(),\n\tthis.primaryBChromaticity_y = t.readUint16(),\n\tthis.whitePointChromaticity_x = t.readUint16(),\n\tthis.whitePointChromaticity_y = t.readUint16(),\n\tthis.luminanceMax = t.readUint32(),\n\tthis.luminanceMin = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("smhd", "SoundMediaHeaderBox",\nfunction(t) {\n\tthis.balance = t.readUint16(),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("ssix", "CompressedSubsegmentIndexBox",\nfunction(t) {\n\tthis.subsegments = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.subsegments.push(r),\n\t\tr.ranges = [];\n\t\tfor (var s = t.readUint32(), a = 0; a < s; a++) {\n\t\t\tvar n = {};\n\t\t\tr.ranges.push(n),\n\t\t\tn.level = t.readUint8(),\n\t\t\tn.range_size = t.readUint24()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("stco", "ChunkOffsetBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (var i = 0; i < e; i++) this.chunk_offsets.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stdp", "DegradationPriorityBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 2;\n\tthis.priority = [];\n\tfor (var i = 0; i < e; i++) this.priority[i] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("sthd", "SubtitleMediaHeaderBox"),\nBoxParser.createFullBoxCtor("stri", "SubTrackInformationBox",\nfunction(t) {\n\tthis.switch_group = t.readUint16(),\n\tthis.alternate_group = t.readUint16(),\n\tthis.sub_track_id = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 8) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsc", "SampleToChunkBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.first_chunk = [], this.samples_per_chunk = [], this.sample_description_index = [], 0 === this.version) for (e = 0; e < i; e++) this.first_chunk.push(t.readUint32()),\n\tthis.samples_per_chunk.push(t.readUint32()),\n\tthis.sample_description_index.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsd", "SampleDescriptionBox",\nfunction(t) {\n\tvar e, i, r, s;\n\tfor (this.entries = [], r = t.readUint32(), e = 1; e <= r; e++) {\n\t\tif ((i = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tBoxParser[i.type + "SampleEntry"] ? ((s = new BoxParser[i.type + "SampleEntry"](i.size)).hdr_size = i.hdr_size, s.start = i.start) : (Log.warn("BoxParser", "Unknown sample entry type: " + i.type), s = new BoxParser.SampleEntry(i.type, i.size, i.hdr_size, i.start)),\n\t\ts.write === BoxParser.SampleEntry.prototype.write && (Log.info("BoxParser", "SampleEntry " + s.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), s.parseDataAndRewind(t)),\n\t\ts.parse(t),\n\t\tthis.entries.push(s)\n\t}\n}),\nBoxParser.createFullBoxCtor("stsg", "SubTrackSampleGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.group_description_index = [];\n\tfor (var i = 0; i < e; i++) this.group_description_index[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsh", "ShadowSyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.shadowed_sample_numbers = [], this.sync_sample_numbers = [], 0 === this.version) for (e = 0; e < i; e++) this.shadowed_sample_numbers.push(t.readUint32()),\n\tthis.sync_sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stss", "SyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (0 === this.version) for (this.sample_numbers = [], e = 0; e < i; e++) this.sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsz", "SampleSizeBox",\nfunction(t) {\n\tvar e;\n\tif (this.sample_sizes = [], 0 === this.version) for (this.sample_size = t.readUint32(), this.sample_count = t.readUint32(), e = 0; e < this.sample_count; e++) 0 === this.sample_size ? this.sample_sizes.push(t.readUint32()) : this.sample_sizes[e] = this.sample_size\n}),\nBoxParser.createFullBoxCtor("stts", "TimeToSampleBox",\nfunction(t) {\n\tvar e, i, r = t.readUint32();\n\tif (this.sample_counts = [], this.sample_deltas = [], 0 === this.version) for (e = 0; e < r; e++) this.sample_counts.push(t.readUint32()),\n\t(i = t.readInt32()) < 0 && (Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!"), i = 1),\n\tthis.sample_deltas.push(i)\n}),\nBoxParser.createFullBoxCtor("stvi", "StereoVideoBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.single_view_allowed = 3 & e,\n\tthis.stereo_scheme = t.readUint32();\n\tvar i, e = t.readUint32();\n\tfor (this.stereo_indication_type = t.readString(e), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((i = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\ti = i.box,\n\t\tthis.boxes.push(i),\n\t\tthis[i.type] = i\n\t}\n}),\nBoxParser.createBoxCtor("styp", "SegmentTypeBox",\nfunction(t) {\n\tBoxParser.ftypBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("stz2", "CompactSampleSizeBox",\nfunction(t) {\n\tvar e, i;\n\tif (this.sample_sizes = [], 0 === this.version) if (this.reserved = t.readUint24(), this.field_size = t.readUint8(), i = t.readUint32(), 4 === this.field_size) for (e = 0; e < i; e += 2) {\n\t\tvar r = t.readUint8();\n\t\tthis.sample_sizes[e] = r >> 4 & 15,\n\t\tthis.sample_sizes[e + 1] = 15 & r\n\t} else if (8 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint8();\n\telse if (16 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint16();\n\telse Log.error("BoxParser", "Error in length field in stz2 box")\n}),\nBoxParser.createFullBoxCtor("subs", "SubSampleInformationBox",\nfunction(t) {\n\tvar e, i, r, s = t.readUint32();\n\tfor (this.entries = [], e = 0; e < s; e++) {\n\t\tvar a = {};\n\t\tif ((this.entries[e] = a).sample_delta = t.readUint32(), a.subsamples = [], 0 < (r = t.readUint16())) for (i = 0; i < r; i++) {\n\t\t\tvar n = {};\n\t\t\ta.subsamples.push(n),\n\t\t\t1 == this.version ? n.size = t.readUint32() : n.size = t.readUint16(),\n\t\t\tn.priority = t.readUint8(),\n\t\t\tn.discardable = t.readUint8(),\n\t\t\tn.codec_specific_parameters = t.readUint32()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("tenc", "TrackEncryptionBox",\nfunction(t) {\n\tvar e;\n\tt.readUint8(),\n\t0 === this.version ? t.readUint8() : (e = t.readUint8(), this.default_crypt_byte_block = e >> 4 & 15, this.default_skip_byte_block = 15 & e),\n\tthis.default_isProtected = t.readUint8(),\n\tthis.default_Per_Sample_IV_Size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t),\n\t1 === this.default_isProtected && 0 === this.default_Per_Sample_IV_Size && (this.default_constant_IV_size = t.readUint8(), this.default_constant_IV = t.readUint8Array(this.default_constant_IV_size))\n}),\nBoxParser.createFullBoxCtor("tfdt", "TrackFragmentBaseMediaDecodeTimeBox",\nfunction(t) {\n\t1 == this.version ? this.baseMediaDecodeTime = t.readUint64() : this.baseMediaDecodeTime = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("tfhd", "TrackFragmentHeaderBox",\nfunction(t) {\n\tvar e = 0;\n\tthis.track_id = t.readUint32(),\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET ? (this.base_data_offset = t.readUint64(), e += 8) : this.base_data_offset = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? (this.default_sample_description_index = t.readUint32(), e += 4) : this.default_sample_description_index = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? (this.default_sample_duration = t.readUint32(), e += 4) : this.default_sample_duration = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? (this.default_sample_size = t.readUint32(), e += 4) : this.default_sample_size = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? (this.default_sample_flags = t.readUint32(), e += 4) : this.default_sample_flags = 0\n}),\nBoxParser.createFullBoxCtor("tfra", "TrackFragmentRandomAccessBox",\nfunction(t) {\n\tthis.track_ID = t.readUint32(),\n\tt.readUint24();\n\tvar e = t.readUint8();\n\tthis.length_size_of_traf_num = e >> 4 & 3,\n\tthis.length_size_of_trun_num = e >> 2 & 3,\n\tthis.length_size_of_sample_num = 3 & e,\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) 1 === this.version ? (this.time = t.readUint64(), this.moof_offset = t.readUint64()) : (this.time = t.readUint32(), this.moof_offset = t.readUint32()),\n\tthis.traf_number = t["readUint" + 8 * (this.length_size_of_traf_num + 1)](),\n\tthis.trun_number = t["readUint" + 8 * (this.length_size_of_trun_num + 1)](),\n\tthis.sample_number = t["readUint" + 8 * (this.length_size_of_sample_num + 1)]()\n}),\nBoxParser.createFullBoxCtor("tkhd", "TrackHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint32()),\n\tt.readUint32Array(2),\n\tthis.layer = t.readInt16(),\n\tthis.alternate_group = t.readInt16(),\n\tthis.volume = t.readInt16() >> 8,\n\tt.readUint16(),\n\tthis.matrix = t.readInt32Array(9),\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmax", "hintmaxrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmin", "hintminrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("totl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpay", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpyl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.TrackGroupTypeBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.track_group_id = t.readUint32()\n},\nBoxParser.createTrackGroupCtor("msrc"),\nBoxParser.TrackReferenceTypeBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.TrackReferenceTypeBox.prototype = new BoxParser.Box,\nBoxParser.TrackReferenceTypeBox.prototype.parse = function(t) {\n\tthis.track_ids = t.readUint32Array((this.size - this.hdr_size) / 4)\n},\nBoxParser.trefBox.prototype.parse = function(t) {\n\tfor (var e; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new BoxParser.TrackReferenceTypeBox(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.info("BoxParser", "TrackReference " + e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.boxes.push(e)\n\t}\n},\nBoxParser.createFullBoxCtor("trep", "TrackExtensionPropertiesBox",\nfunction(t) {\n\tfor (this.track_ID = t.readUint32(), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif (ret = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start)), ret.code !== BoxParser.OK) return;\n\t\tbox = ret.box,\n\t\tthis.boxes.push(box)\n\t}\n}),\nBoxParser.createFullBoxCtor("trex", "TrackExtendsBox",\nfunction(t) {\n\tthis.track_id = t.readUint32(),\n\tthis.default_sample_description_index = t.readUint32(),\n\tthis.default_sample_duration = t.readUint32(),\n\tthis.default_sample_size = t.readUint32(),\n\tthis.default_sample_flags = t.readUint32()\n}),\nBoxParser.createBoxCtor("trpy", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("trun", "TrackRunBox",\nfunction(t) {\n\tvar e = 0;\n\tif (this.sample_count = t.readUint32(), e += 4, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET ? (this.data_offset = t.readInt32(), e += 4) : this.data_offset = 0, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG ? (this.first_sample_flags = t.readUint32(), e += 4) : this.first_sample_flags = 0, this.sample_duration = [], this.sample_size = [], this.sample_flags = [], this.sample_composition_time_offset = [], this.size - this.hdr_size > e) for (var i = 0; i < this.sample_count; i++) this.flags & BoxParser.TRUN_FLAGS_DURATION && (this.sample_duration[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.sample_size[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.sample_flags[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? this.sample_composition_time_offset[i] = t.readUint32() : this.sample_composition_time_offset[i] = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("tsel", "TrackSelectionBox",\nfunction(t) {\n\tthis.switch_group = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 4) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("txtC", "TextConfigBox",\nfunction(t) {\n\tthis.config = t.readCString()\n}),\nBoxParser.createBoxCtor("tyco", "TypeCombinationBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 4;\n\tthis.compatible_brands = [];\n\tfor (var i = 0; i < e; i++) this.compatible_brands[i] = t.readString(4)\n}),\nBoxParser.createFullBoxCtor("udes", "UserDescriptionProperty",\nfunction(t) {\n\tthis.lang = t.readCString(),\n\tthis.name = t.readCString(),\n\tthis.description = t.readCString(),\n\tthis.tags = t.readCString()\n}),\nBoxParser.createFullBoxCtor("uncC", "UncompressedFrameConfigBox",\nfunction(t) {\n\tvar e;\n\tif (this.profile = t.readString(4), 1 != this.version && 0 == this.version) {\n\t\tfor (this.component_count = t.readUint32(), this.component_index = [], this.component_bit_depth_minus_one = [], this.component_format = [], this.component_align_size = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16()),\n\t\tthis.component_bit_depth_minus_one.push(t.readUint8()),\n\t\tthis.component_format.push(t.readUint8()),\n\t\tthis.component_align_size.push(t.readUint8());\n\t\tthis.sampling_type = t.readUint8(),\n\t\tthis.interleave_type = t.readUint8(),\n\t\tthis.block_size = t.readUint8();\n\t\tvar i = t.readUint8();\n\t\tthis.component_little_endian = i >> 7 & 1,\n\t\tthis.block_pad_lsb = i >> 6 & 1,\n\t\tthis.block_little_endian = i >> 5 & 1,\n\t\tthis.block_reversed = i >> 4 & 1,\n\t\tthis.pad_unknown = i >> 3 & 1,\n\t\tthis.pixel_size = t.readUint32(),\n\t\tthis.row_align_size = t.readUint32(),\n\t\tthis.tile_align_size = t.readUint32(),\n\t\tthis.num_tile_cols_minus_one = t.readUint32(),\n\t\tthis.num_tile_rows_minus_one = t.readUint32()\n\t}\n}),\nBoxParser.createFullBoxCtor("url ", "DataEntryUrlBox",\nfunction(t) {\n\t1 !== this.flags && (this.location = t.readCString())\n}),\nBoxParser.createFullBoxCtor("urn ", "DataEntryUrnBox",\nfunction(t) {\n\tthis.name = t.readCString(),\n\t0 < this.size - this.hdr_size - this.name.length - 1 && (this.location = t.readCString())\n}),\nBoxParser.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66", "LiveServerManifestBox", !0, !1,\nfunction(t) {\n\tthis.LiveServerManifest = t.readString(this.size - this.hdr_size).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\'/g, "&#039;")\n}),\nBoxParser.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3", "PiffProtectionSystemSpecificHeaderBox", !0, !1,\nfunction(t) {\n\tthis.system_id = BoxParser.parseHex16(t);\n\tvar e = t.readUint32();\n\t0 < e && (this.data = t.readUint8Array(e))\n}),\nBoxParser.createUUIDBox("a2394f525a9b4f14a2446c427c648df4", "PiffSampleEncryptionBox", !0, !1),\nBoxParser.createUUIDBox("8974dbce7be74c5184f97148f9882554", "PiffTrackEncryptionBox", !0, !1,\nfunction(t) {\n\tthis.default_AlgorithmID = t.readUint24(),\n\tthis.default_IV_size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t)\n}),\nBoxParser.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f", "TfrfBox", !0, !1,\nfunction(t) {\n\tthis.fragment_count = t.readUint8(),\n\tthis.entries = [];\n\tfor (var e = 0; e < this.fragment_count; e++) {\n\t\tvar i = {},\n\t\tr = 0,\n\t\ts = 0,\n\t\ts = 1 === this.version ? (r = t.readUint64(), t.readUint64()) : (r = t.readUint32(), t.readUint32());\n\t\ti.absolute_time = r,\n\t\ti.absolute_duration = s,\n\t\tthis.entries.push(i)\n\t}\n}),\nBoxParser.createUUIDBox("6d1d9b0542d544e680e2141daff757b2", "TfxdBox", !0, !1,\nfunction(t) {\n\t1 === this.version ? (this.absolute_time = t.readUint64(), this.duration = t.readUint64()) : (this.absolute_time = t.readUint32(), this.duration = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("vmhd", "VideoMediaHeaderBox",\nfunction(t) {\n\tthis.graphicsmode = t.readUint16(),\n\tthis.opcolor = t.readUint16Array(3)\n}),\nBoxParser.createFullBoxCtor("vpcC", "VPCodecConfigurationRecord",\nfunction(t) {\n\tvar e;\n\t1 === this.version ? (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4, this.chromaSubsampling = e >> 1 & 7, this.videoFullRangeFlag = 1 & e, this.colourPrimaries = t.readUint8(), this.transferCharacteristics = t.readUint8(), this.matrixCoefficients = t.readUint8()) : (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4 & 15, this.colorSpace = 15 & e, e = t.readUint8(), this.chromaSubsampling = e >> 4 & 15, this.transferFunction = e >> 1 & 7, this.videoFullRangeFlag = 1 & e),\n\tthis.codecIntializationDataSize = t.readUint16(),\n\tthis.codecIntializationData = t.readUint8Array(this.codecIntializationDataSize)\n}),\nBoxParser.createBoxCtor("vttC", "WebVTTConfigurationBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("vvcC", "VvcConfigurationBox",\nfunction(t) {\n\tvar e, i = {\n\t\theld_bits: void 0,\n\t\tnum_held_bits: 0,\n\t\tstream_read_1_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint8(),\n\t\t\tthis.num_held_bits = 8\n\t\t},\n\t\tstream_read_2_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint16(),\n\t\t\tthis.num_held_bits = 16\n\t\t},\n\t\textract_bits: function(t) {\n\t\t\tvar e = this.held_bits >> this.num_held_bits - t & (1 << t) - 1;\n\t\t\treturn this.num_held_bits -= t,\n\t\t\te\n\t\t}\n\t};\n\tif (i.stream_read_1_bytes(t), i.extract_bits(5), this.lengthSizeMinusOne = i.extract_bits(2), this.ptl_present_flag = i.extract_bits(1), this.ptl_present_flag) {\n\t\tif (i.stream_read_2_bytes(t), this.ols_idx = i.extract_bits(9), this.num_sublayers = i.extract_bits(3), this.constant_frame_rate = i.extract_bits(2), this.chroma_format_idc = i.extract_bits(2), i.stream_read_1_bytes(t), this.bit_depth_minus8 = i.extract_bits(3), i.extract_bits(5), i.stream_read_2_bytes(t), i.extract_bits(2), this.num_bytes_constraint_info = i.extract_bits(6), this.general_profile_idc = i.extract_bits(7), this.general_tier_flag = i.extract_bits(1), this.general_level_idc = t.readUint8(), i.stream_read_1_bytes(t), this.ptl_frame_only_constraint_flag = i.extract_bits(1), this.ptl_multilayer_enabled_flag = i.extract_bits(1), this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info), this.num_bytes_constraint_info) {\n\t\t\tfor (o = 0; o < this.num_bytes_constraint_info - 1; o++) {\n\t\t\t\tvar r = i.extract_bits(6);\n\t\t\t\ti.stream_read_1_bytes(t);\n\t\t\t\tvar s = i.extract_bits(2);\n\t\t\t\tthis.general_constraint_info[o] = r << 2 | s\n\t\t\t}\n\t\t\tthis.general_constraint_info[this.num_bytes_constraint_info - 1] = i.extract_bits(6)\n\t\t} else i.extract_bits(6);\n\t\tif (1 < this.num_sublayers) {\n\t\t\tfor (i.stream_read_1_bytes(t), this.ptl_sublayer_present_mask = 0, e = this.num_sublayers - 2; 0 <= e; --e) {\n\t\t\t\tvar a = i.extract_bits(1);\n\t\t\t\tthis.ptl_sublayer_present_mask |= a << e\n\t\t\t}\n\t\t\tfor (e = this.num_sublayers; e <= 8 && 1 < this.num_sublayers; ++e) i.extract_bits(1);\n\t\t\tfor (this.sublayer_level_idc = [], e = this.num_sublayers - 2; 0 <= e; --e) this.ptl_sublayer_present_mask & 1 << e && (this.sublayer_level_idc[e] = t.readUint8())\n\t\t}\n\t\tif (this.ptl_num_sub_profiles = t.readUint8(), this.general_sub_profile_idc = [], this.ptl_num_sub_profiles) for (o = 0; o < this.ptl_num_sub_profiles; o++) this.general_sub_profile_idc.push(t.readUint32());\n\t\tthis.max_picture_width = t.readUint16(),\n\t\tthis.max_picture_height = t.readUint16(),\n\t\tthis.avg_frame_rate = t.readUint16()\n\t}\n\tthis.nalu_arrays = [];\n\tfor (var n = t.readUint8(), o = 0; o < n; o++) {\n\t\tvar h = [];\n\t\tthis.nalu_arrays.push(h),\n\t\ti.stream_read_1_bytes(t),\n\t\th.completeness = i.extract_bits(1),\n\t\ti.extract_bits(2),\n\t\th.nalu_type = i.extract_bits(5);\n\t\tvar d = 1;\n\t\tfor (13 != h.nalu_type && 12 != h.nalu_type && (d = t.readUint16()), e = 0; e < d; e++) {\n\t\t\tvar l = t.readUint16();\n\t\t\th.push({\n\t\t\t\tdata: t.readUint8Array(l),\n\t\t\t\tlength: l\n\t\t\t})\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("vvnC", "VvcNALUConfigBox",\nfunction(t) {\n\tvar e = strm.readUint8();\n\tthis.lengthSizeMinusOne = 3 & e\n}),\nBoxParser.SampleEntry.prototype.isVideo = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isAudio = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isSubtitle = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isMetadata = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isHint = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.getCodec = function() {\n\treturn this.type.replace(".", "")\n},\nBoxParser.SampleEntry.prototype.getWidth = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getHeight = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getChannelCount = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleRate = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleSize = function() {\n\treturn ""\n},\nBoxParser.VisualSampleEntry.prototype.isVideo = function() {\n\treturn ! 0\n},\nBoxParser.VisualSampleEntry.prototype.getWidth = function() {\n\treturn this.width\n},\nBoxParser.VisualSampleEntry.prototype.getHeight = function() {\n\treturn this.height\n},\nBoxParser.AudioSampleEntry.prototype.isAudio = function() {\n\treturn ! 0\n},\nBoxParser.AudioSampleEntry.prototype.getChannelCount = function() {\n\treturn this.channel_count\n},\nBoxParser.AudioSampleEntry.prototype.getSampleRate = function() {\n\treturn this.samplerate\n},\nBoxParser.AudioSampleEntry.prototype.getSampleSize = function() {\n\treturn this.samplesize\n},\nBoxParser.SubtitleSampleEntry.prototype.isSubtitle = function() {\n\treturn ! 0\n},\nBoxParser.MetadataSampleEntry.prototype.isMetadata = function() {\n\treturn ! 0\n},\nBoxParser.decimalToHex = function(t, e) {\n\tvar i = Number(t).toString(16);\n\tfor (e = null == e ? e = 2 : e; i.length < e;) i = "0" + i;\n\treturn i\n},\nBoxParser.avc1SampleEntry.prototype.getCodec = BoxParser.avc2SampleEntry.prototype.getCodec = BoxParser.avc3SampleEntry.prototype.getCodec = BoxParser.avc4SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.avcC ? t + "." + BoxParser.decimalToHex(this.avcC.AVCProfileIndication) + BoxParser.decimalToHex(this.avcC.profile_compatibility) + BoxParser.decimalToHex(this.avcC.AVCLevelIndication) : t\n},\nBoxParser.hev1SampleEntry.prototype.getCodec = BoxParser.hvc1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.hvcC) {\n\t\tswitch (t += ".", this.hvcC.general_profile_space) {\n\t\tcase 0:\n\t\t\tt += "";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tt += "A";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tt += "B";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tt += "C"\n\t\t}\n\t\tt += this.hvcC.general_profile_idc,\n\t\tt += ".";\n\t\tfor (var e = this.hvcC.general_profile_compatibility,\n\t\ti = 0,\n\t\tr = 0; r < 32 && (i |= 1 & e, 31 != r); r++) i <<= 1,\n\t\te >>= 1;\n\t\tt += BoxParser.decimalToHex(i, 0),\n\t\tt += ".",\n\t\t0 === this.hvcC.general_tier_flag ? t += "L": t += "H",\n\t\tt += this.hvcC.general_level_idc;\n\t\tvar s = !1,\n\t\ta = "";\n\t\tfor (r = 5; 0 <= r; r--)(this.hvcC.general_constraint_indicator[r] || s) && (a = "." + BoxParser.decimalToHex(this.hvcC.general_constraint_indicator[r], 0) + a, s = !0);\n\t\tt += a\n\t}\n\treturn t\n},\nBoxParser.vvc1SampleEntry.prototype.getCodec = BoxParser.vvi1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.vvcC) {\n\t\tt += "." + this.vvcC.general_profile_idc,\n\t\tthis.vvcC.general_tier_flag ? t += ".H": t += ".L",\n\t\tt += this.vvcC.general_level_idc;\n\t\tvar e = "";\n\t\tif (this.vvcC.general_constraint_info) {\n\t\t\tvar i, r = [],\n\t\t\ts = 0;\n\t\t\tfor (s |= this.vvcC.ptl_frame_only_constraint << 7, s |= this.vvcC.ptl_multilayer_enabled << 6, h = 0; h < this.vvcC.general_constraint_info.length; ++h) s |= this.vvcC.general_constraint_info[h] >> 2 & 63,\n\t\t\tr.push(s),\n\t\t\ts && (i = h),\n\t\t\ts = this.vvcC.general_constraint_info[h] >> 2 & 3;\n\t\t\tif (void 0 === i) e = ".CA";\n\t\t\telse {\n\t\t\t\te = ".C";\n\t\t\t\tfor (var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",\n\t\t\t\tn = 0,\n\t\t\t\to = 0,\n\t\t\t\th = 0; h <= i; ++h) for (n = n << 8 | r[h], o += 8; 5 <= o;) e += a[n >> o - 5 & 31],\n\t\t\t\tn &= (1 << (o -= 5)) - 1;\n\t\t\t\to && (e += a[31 & (n <<= 5 - o)])\n\t\t\t}\n\t\t}\n\t\tt += e\n\t}\n\treturn t\n},\nBoxParser.mp4aSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.esds && this.esds.esd) {\n\t\tvar e = this.esds.esd.getOTI(),\n\t\ti = this.esds.esd.getAudioConfig();\n\t\treturn t + "." + BoxParser.decimalToHex(e) + (i ? "." + i: "")\n\t}\n\treturn t\n},\nBoxParser.stxtSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.mime_format ? t + "." + this.mime_format: t\n},\nBoxParser.vp08SampleEntry.prototype.getCodec = BoxParser.vp09SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\te = this.vpcC.level;\n\t0 == e && (e = "00");\n\tvar i = this.vpcC.bitDepth;\n\treturn 8 == i && (i = "08"),\n\tt + ".0" + this.vpcC.profile + "." + e + "." + i\n},\nBoxParser.av01SampleEntry.prototype.getCodec = function() {\n\tvar t, e = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\ti = this.av1C.seq_level_idx_0;\n\treturn i < 10 && (i = "0" + i),\n\t2 === this.av1C.seq_profile && 1 === this.av1C.high_bitdepth ? t = 1 === this.av1C.twelve_bit ? "12": "10": this.av1C.seq_profile <= 2 && (t = 1 === this.av1C.high_bitdepth ? "10": "08"),\n\te + "." + this.av1C.seq_profile + "." + i + (this.av1C.seq_tier_0 ? "H": "M") + "." + t\n},\nBoxParser.Box.prototype.writeHeader = function(t, e) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tLog.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + t.getPosition() + (e || "")),\n\tthis.size > MAX_SIZE ? t.writeUint32(1) : (this.sizePosition = t.getPosition(), t.writeUint32(this.size)),\n\tt.writeString(this.type, null, 4),\n\t"uuid" === this.type && t.writeUint8Array(this.uuid),\n\tthis.size > MAX_SIZE && t.writeUint64(this.size)\n},\nBoxParser.FullBox.prototype.writeHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.writeHeader.call(this, t, " v=" + this.version + " f=" + this.flags),\n\tt.writeUint8(this.version),\n\tt.writeUint24(this.flags)\n},\nBoxParser.Box.prototype.write = function(t) {\n\t"mdat" === this.type ? this.data && (this.size = this.data.length, this.writeHeader(t), t.writeUint8Array(this.data)) : (this.size = this.data ? this.data.length: 0, this.writeHeader(t), this.data && t.writeUint8Array(this.data))\n},\nBoxParser.ContainerBox.prototype.write = function(t) {\n\tthis.size = 0,\n\tthis.writeHeader(t);\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && (this.boxes[e].write(t), this.size += this.boxes[e].size);\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.TrackReferenceTypeBox.prototype.write = function(t) {\n\tthis.size = 4 * this.track_ids.length,\n\tthis.writeHeader(t),\n\tt.writeUint32Array(this.track_ids)\n},\nBoxParser.avcCBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.size = 7, e = 0; e < this.SPS.length; e++) this.size += 2 + this.SPS[e].length;\n\tfor (e = 0; e < this.PPS.length; e++) this.size += 2 + this.PPS[e].length;\n\tfor (this.ext && (this.size += this.ext.length), this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8(this.AVCProfileIndication), t.writeUint8(this.profile_compatibility), t.writeUint8(this.AVCLevelIndication), t.writeUint8(this.lengthSizeMinusOne + 252), t.writeUint8(this.SPS.length + 224), e = 0; e < this.SPS.length; e++) t.writeUint16(this.SPS[e].length),\n\tt.writeUint8Array(this.SPS[e].nalu);\n\tfor (t.writeUint8(this.PPS.length), e = 0; e < this.PPS.length; e++) t.writeUint16(this.PPS[e].length),\n\tt.writeUint8Array(this.PPS[e].nalu);\n\tthis.ext && t.writeUint8Array(this.ext)\n},\nBoxParser.co64Box.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.chunk_offsets.length, this.writeHeader(t), t.writeUint32(this.chunk_offsets.length), e = 0; e < this.chunk_offsets.length; e++) t.writeUint64(this.chunk_offsets[e])\n},\nBoxParser.cslgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeInt32(this.compositionToDTSShift),\n\tt.writeInt32(this.leastDecodeToDisplayDelta),\n\tt.writeInt32(this.greatestDecodeToDisplayDelta),\n\tt.writeInt32(this.compositionStartTime),\n\tt.writeInt32(this.compositionEndTime)\n},\nBoxParser.cttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\t1 === this.version ? t.writeInt32(this.sample_offsets[e]) : t.writeUint32(this.sample_offsets[e])\n},\nBoxParser.drefBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.elngBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.extended_language.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.extended_language)\n},\nBoxParser.elstBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 12 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeUint32(i.segment_duration),\n\t\tt.writeInt32(i.media_time),\n\t\tt.writeInt16(i.media_rate_integer),\n\t\tt.writeInt16(i.media_rate_fraction)\n\t}\n},\nBoxParser.emsgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.scheme_id_uri),\n\tt.writeCString(this.value),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.presentation_time_delta),\n\tt.writeUint32(this.event_duration),\n\tt.writeUint32(this.id),\n\tt.writeUint8Array(this.message_data)\n},\nBoxParser.ftypBox.prototype.write = function(t) {\n\tthis.size = 8 + 4 * this.compatible_brands.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.major_brand, null, 4),\n\tt.writeUint32(this.minor_version);\n\tfor (var e = 0; e < this.compatible_brands.length; e++) t.writeString(this.compatible_brands[e], null, 4)\n},\nBoxParser.hdlrBox.prototype.write = function(t) {\n\tthis.size = 20 + this.name.length + 1,\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(0),\n\tt.writeString(this.handler, null, 4),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeCString(this.name)\n},\nBoxParser.hvcCBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.size = 23, e = 0; e < this.nalu_arrays.length; e++) for (this.size += 3, i = 0; i < this.nalu_arrays[e].length; i++) this.size += 2 + this.nalu_arrays[e][i].data.length;\n\tfor (this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc), t.writeUint32(this.general_profile_compatibility), t.writeUint8Array(this.general_constraint_indicator), t.writeUint8(this.general_level_idc), t.writeUint16(this.min_spatial_segmentation_idc + (15 << 24)), t.writeUint8(this.parallelismType + 252), t.writeUint8(this.chroma_format_idc + 252), t.writeUint8(this.bit_depth_luma_minus8 + 248), t.writeUint8(this.bit_depth_chroma_minus8 + 248), t.writeUint16(this.avgFrameRate), t.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne), t.writeUint8(this.nalu_arrays.length), e = 0; e < this.nalu_arrays.length; e++) for (t.writeUint8((this.nalu_arrays[e].completeness << 7) + this.nalu_arrays[e].nalu_type), t.writeUint16(this.nalu_arrays[e].length), i = 0; i < this.nalu_arrays[e].length; i++) t.writeUint16(this.nalu_arrays[e][i].data.length),\n\tt.writeUint8Array(this.nalu_arrays[e][i].data)\n},\nBoxParser.kindBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.schemeURI.length + 1 + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.schemeURI),\n\tt.writeCString(this.value)\n},\nBoxParser.mdhdBox.prototype.write = function(t) {\n\tthis.size = 20,\n\tthis.flags = 0,\n\tthis.version = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint16(this.language),\n\tt.writeUint16(0)\n},\nBoxParser.mehdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.fragment_duration)\n},\nBoxParser.mfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sequence_number)\n},\nBoxParser.mvhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 96,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(this.rate),\n\tt.writeUint16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32Array(this.matrix),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(this.next_track_id)\n},\nBoxParser.SampleEntry.prototype.writeHeader = function(t) {\n\tthis.size = 8,\n\tBoxParser.Box.prototype.writeHeader.call(this, t),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint16(this.data_reference_index)\n},\nBoxParser.SampleEntry.prototype.writeFooter = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t),\n\tthis.size += this.boxes[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.SampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tt.writeUint8Array(this.data),\n\tthis.size += this.data.length,\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.VisualSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 70,\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.width),\n\tt.writeUint16(this.height),\n\tt.writeUint32(this.horizresolution),\n\tt.writeUint32(this.vertresolution),\n\tt.writeUint32(0),\n\tt.writeUint16(this.frame_count),\n\tt.writeUint8(Math.min(31, this.compressorname.length)),\n\tt.writeString(this.compressorname, null, 31),\n\tt.writeUint16(this.depth),\n\tt.writeInt16(-1),\n\tthis.writeFooter(t)\n},\nBoxParser.AudioSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 20,\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.channel_count),\n\tt.writeUint16(this.samplesize),\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(this.samplerate << 16),\n\tthis.writeFooter(t)\n},\nBoxParser.stppSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1,\n\tt.writeCString(this.namespace),\n\tt.writeCString(this.schema_location),\n\tt.writeCString(this.auxiliary_mime_types),\n\tthis.writeFooter(t)\n},\nBoxParser.SampleGroupEntry.prototype.write = function(t) {\n\tt.writeUint8Array(this.data)\n},\nBoxParser.sbgpBox.prototype.write = function(t) {\n\tthis.version = 1,\n\tthis.flags = 0,\n\tthis.size = 12 + 8 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.grouping_type, null, 4),\n\tt.writeUint32(this.grouping_type_parameter),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeInt32(i.sample_count),\n\t\tt.writeInt32(i.group_description_index)\n\t}\n},\nBoxParser.sgpdBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.flags = 0, this.size = 12, e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && (0 === this.default_length && (this.size += 4), this.size += i.data.length);\n\tfor (this.writeHeader(t), t.writeString(this.grouping_type, null, 4), 1 === this.version && t.writeUint32(this.default_length), 2 <= this.version && t.writeUint32(this.default_sample_description_index), t.writeUint32(this.entries.length), e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && 0 === this.default_length && t.writeUint32(i.description_length),\n\ti.write(t)\n},\nBoxParser.sidxBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20 + 12 * this.references.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.reference_ID),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.earliest_presentation_time),\n\tt.writeUint32(this.first_offset),\n\tt.writeUint16(0),\n\tt.writeUint16(this.references.length);\n\tfor (var e = 0; e < this.references.length; e++) {\n\t\tvar i = this.references[e];\n\t\tt.writeUint32(i.reference_type << 31 | i.referenced_size),\n\t\tt.writeUint32(i.subsegment_duration),\n\t\tt.writeUint32(i.starts_with_SAP << 31 | i.SAP_type << 28 | i.SAP_delta_time)\n\t}\n},\nBoxParser.smhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.balance),\n\tt.writeUint16(0)\n},\nBoxParser.stcoBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.chunk_offsets.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.chunk_offsets.length),\n\tt.writeUint32Array(this.chunk_offsets)\n},\nBoxParser.stscBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 12 * this.first_chunk.length, this.writeHeader(t), t.writeUint32(this.first_chunk.length), e = 0; e < this.first_chunk.length; e++) t.writeUint32(this.first_chunk[e]),\n\tt.writeUint32(this.samples_per_chunk[e]),\n\tt.writeUint32(this.sample_description_index[e])\n},\nBoxParser.stsdBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 0, this.writeHeader(t), t.writeUint32(this.entries.length), this.size += 4, e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.stshBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.shadowed_sample_numbers.length, this.writeHeader(t), t.writeUint32(this.shadowed_sample_numbers.length), e = 0; e < this.shadowed_sample_numbers.length; e++) t.writeUint32(this.shadowed_sample_numbers[e]),\n\tt.writeUint32(this.sync_sample_numbers[e])\n},\nBoxParser.stssBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.sample_numbers.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_numbers.length),\n\tt.writeUint32Array(this.sample_numbers)\n},\nBoxParser.stszBox.prototype.write = function(t) {\n\tvar e, i = !0;\n\tif (this.version = 0, (this.flags = 0) < this.sample_sizes.length) for (e = 0; e + 1 < this.sample_sizes.length;) {\n\t\tif (this.sample_sizes[e + 1] !== this.sample_sizes[0]) {\n\t\t\ti = !1;\n\t\t\tbreak\n\t\t}\n\t\te++\n\t} else i = !1;\n\tthis.size = 8,\n\ti || (this.size += 4 * this.sample_sizes.length),\n\tthis.writeHeader(t),\n\ti ? t.writeUint32(this.sample_sizes[0]) : t.writeUint32(0),\n\tt.writeUint32(this.sample_sizes.length),\n\ti || t.writeUint32Array(this.sample_sizes)\n},\nBoxParser.sttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\tt.writeUint32(this.sample_deltas[e])\n},\nBoxParser.tfdtBox.prototype.write = function(t) {\n\tvar e = Math.pow(2, 32) - 1;\n\tthis.version = this.baseMediaDecodeTime > e ? 1 : 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\t1 === this.version && (this.size += 4),\n\tthis.writeHeader(t),\n\t1 === this.version ? t.writeUint64(this.baseMediaDecodeTime) : t.writeUint32(this.baseMediaDecodeTime)\n},\nBoxParser.tfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && (this.size += 8),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && (this.size += 4),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && t.writeUint64(this.base_data_offset),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && t.writeUint32(this.default_sample_description_index),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && t.writeUint32(this.default_sample_duration),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && t.writeUint32(this.default_sample_size),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && t.writeUint32(this.default_sample_flags)\n},\nBoxParser.tkhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 80,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(0),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeInt16(this.layer),\n\tt.writeInt16(this.alternate_group),\n\tt.writeInt16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeInt32Array(this.matrix),\n\tt.writeUint32(this.width),\n\tt.writeUint32(this.height)\n},\nBoxParser.trexBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(this.default_sample_description_index),\n\tt.writeUint32(this.default_sample_duration),\n\tt.writeUint32(this.default_sample_size),\n\tt.writeUint32(this.default_sample_flags)\n},\nBoxParser.trunBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_DURATION && (this.size += 4 * this.sample_duration.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.size += 4 * this.sample_size.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.size += 4 * this.sample_flags.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (this.size += 4 * this.sample_composition_time_offset.length),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_count),\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.data_offset_position = t.getPosition(), t.writeInt32(this.data_offset)),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && t.writeUint32(this.first_sample_flags);\n\tfor (var e = 0; e < this.sample_count; e++) this.flags & BoxParser.TRUN_FLAGS_DURATION && t.writeUint32(this.sample_duration[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && t.writeUint32(this.sample_size[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && t.writeUint32(this.sample_flags[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? t.writeUint32(this.sample_composition_time_offset[e]) : t.writeInt32(this.sample_composition_time_offset[e]))\n},\nBoxParser["url Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.location ? (this.flags = 0, this.size = this.location.length + 1) : (this.flags = 1, this.size = 0),\n\tthis.writeHeader(t),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser["urn Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0),\n\tthis.writeHeader(t),\n\tt.writeCString(this.name),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser.vmhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 8,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.graphicsmode),\n\tt.writeUint16Array(this.opcolor)\n},\nBoxParser.cttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].pts = t[i].dts + this.sample_offsets[r],\n\ti++\n},\nBoxParser.sttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].dts = 0 === i ? 0 : t[i - 1].dts + this.sample_deltas[r],\n\ti++\n},\nBoxParser.stcoBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.chunk_offsets.length; e++) t[e].offset = this.chunk_offsets[e]\n},\nBoxParser.stscBox.prototype.unpack = function(t) {\n\tfor (var e, i, r = 0,\n\ts = 0,\n\ta = 0; a < this.first_chunk.length; a++) for (e = 0; e < (a + 1 < this.first_chunk.length ? this.first_chunk[a + 1] : 1 / 0); e++) for (s++, i = 0; i < this.samples_per_chunk[a]; i++) {\n\t\tif (!t[r]) return;\n\t\tt[r].description_index = this.sample_description_index[a],\n\t\tt[r].chunk_index = s,\n\t\tr++\n\t}\n},\nBoxParser.stszBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.sample_sizes.length; e++) t[e].size = this.sample_sizes[e]\n},\nBoxParser.DIFF_BOXES_PROP_NAMES = ["boxes", "entries", "references", "subsamples", "items", "item_infos", "extents", "associations", "subsegments", "ranges", "seekLists", "seekPoints", "esd", "levels"],\nBoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES = ["compatible_brands", "matrix", "opcolor", "sample_counts", "sample_deltas", "first_chunk", "samples_per_chunk", "sample_sizes", "chunk_offsets", "sample_offsets", "sample_description_index", "sample_duration"],\nBoxParser.boxEqualFields = function(t, e) {\n\tif (t && !e) return ! 1;\n\tfor (var i in t) if (! (-1 < BoxParser.DIFF_BOXES_PROP_NAMES.indexOf(i) || t[i] instanceof BoxParser.Box || e[i] instanceof BoxParser.Box || void 0 === t[i] || void 0 === e[i] || "function" == typeof t[i] || "function" == typeof e[i] || t.subBoxNames && -1 < t.subBoxNames.indexOf(i.slice(0, 4)) || e.subBoxNames && -1 < e.subBoxNames.indexOf(i.slice(0, 4)) || "data" === i || "start" === i || "size" === i || "creation_time" === i || "modification_time" === i || -1 < BoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i) || t[i] === e[i])) return ! 1;\n\treturn ! 0\n},\nBoxParser.boxEqual = function(t, e) {\n\tif (!BoxParser.boxEqualFields(t, e)) return ! 1;\n\tfor (var i = 0; i < BoxParser.DIFF_BOXES_PROP_NAMES.length; i++) {\n\t\tvar r = BoxParser.DIFF_BOXES_PROP_NAMES[i];\n\t\tif (t[r] && e[r] && !BoxParser.boxEqual(t[r], e[r])) return ! 1\n\t}\n\treturn ! 0\n};\nvar VTTin4Parser = function() {};\nVTTin4Parser.prototype.parseSample = function(t) {\n\tfor (var e, i = new MP4BoxStream(t.buffer), r = []; ! i.isEos();)(e = BoxParser.parseOneBox(i, !1)).code === BoxParser.OK && "vttc" === e.box.type && r.push(e.box);\n\treturn r\n},\nVTTin4Parser.prototype.getText = function(t, e, i) {\n\tfunction s(t, e, i) {\n\t\treturn i = i || "0",\n\t\t(t += "").length >= e ? t: new Array(e - t.length + 1).join(i) + t\n\t}\n\tfunction r(t) {\n\t\tvar e = Math.floor(t / 3600),\n\t\ti = Math.floor((t - 3600 * e) / 60),\n\t\tr = Math.floor(t - 3600 * e - 60 * i),\n\t\tt = Math.floor(1e3 * (t - 3600 * e - 60 * i - r));\n\t\treturn s(e, 2) + ":" + s(i, 2) + ":" + s(r, 2) + "." + s(t, 3)\n\t}\n\tfor (var a = this.parseSample(i), n = "", o = 0; o < a.length; o++) {\n\t\tvar h = a[o];\n\t\tn += r(t) + " --\\x3e " + r(e) + "\\r\\n",\n\t\tn += h.payl.text\n\t}\n\treturn n\n};\nvar XMLSubtitlein4Parser = function() {};\nXMLSubtitlein4Parser.prototype.parseSample = function(t) {\n\tvar e, i = {\n\t\tresources: []\n\t},\n\tr = new MP4BoxStream(t.data.buffer);\n\tif (t.subsamples && 0 !== t.subsamples.length) {\n\t\tif (i.documentString = r.readString(t.subsamples[0].size), 1 < t.subsamples.length) for (e = 1; e < t.subsamples.length; e++) i.resources[e] = r.readUint8Array(t.subsamples[e].size)\n\t} else i.documentString = r.readString(t.data.length);\n\treturn "undefined" != typeof DOMParser && (i.document = (new DOMParser).parseFromString(i.documentString, "application/xml")),\n\ti\n};\nvar Textin4Parser = function() {};\nTextin4Parser.prototype.parseSample = function(t) {\n\treturn new MP4BoxStream(t.data.buffer).readString(t.data.length)\n},\nTextin4Parser.prototype.parseConfig = function(t) {\n\tt = new MP4BoxStream(t.buffer);\n\treturn t.readUint32(),\n\tt.readCString()\n},\n"undefined" != typeof exports && (exports.VTTin4Parser = VTTin4Parser, exports.XMLSubtitlein4Parser = XMLSubtitlein4Parser, exports.Textin4Parser = Textin4Parser);\nvar ISOFile = function(t) {\n\tthis.stream = t || new MultiBufferStream,\n\tthis.boxes = [],\n\tthis.mdats = [],\n\tthis.moofs = [],\n\tthis.isProgressive = !1,\n\tthis.moovStartFound = !1,\n\tthis.onMoovStart = null,\n\tthis.moovStartSent = !1,\n\tthis.onReady = null,\n\tthis.readySent = !1,\n\tthis.onSegment = null,\n\tthis.onSamples = null,\n\tthis.onError = null,\n\tthis.sampleListBuilt = !1,\n\tthis.fragmentedTracks = [],\n\tthis.extractedTracks = [],\n\tthis.isFragmentationInitialized = !1,\n\tthis.sampleProcessingStarted = !1,\n\tthis.nextMoofNumber = 0,\n\tthis.itemListBuilt = !1,\n\tthis.items = [],\n\tthis.entity_groups = [],\n\tthis.onSidx = null,\n\tthis.sidxSent = !1\n};\nISOFile.prototype.setSegmentOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.fragmentedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.segmentStream = null, r.nb_samples = 1e3, r.rapAlignement = !0, i && (i.nbSamples && (r.nb_samples = i.nbSamples), i.rapAlignement && (r.rapAlignement = i.rapAlignement)))\n},\nISOFile.prototype.unsetSegmentOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.fragmentedTracks.length; i++) this.fragmentedTracks[i].id == t && (e = i); - 1 < e && this.fragmentedTracks.splice(e, 1)\n},\nISOFile.prototype.setExtractionOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.extractedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.nb_samples = 1e3, r.samples = [], i && i.nbSamples && (r.nb_samples = i.nbSamples))\n},\nISOFile.prototype.unsetExtractionOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.extractedTracks.length; i++) this.extractedTracks[i].id == t && (e = i); - 1 < e && this.extractedTracks.splice(e, 1)\n},\nISOFile.prototype.parse = function() {\n\tvar t;\n\tif (!this.restoreParsePosition || this.restoreParsePosition()) for (;;) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) {\n\t\tif (!this.processIncompleteMdat()) return\n\t} else if (this.saveParsePosition && this.saveParsePosition(), (t = BoxParser.parseOneBox(this.stream, !1)).code === BoxParser.ERR_NOT_ENOUGH_DATA) {\n\t\tif (!this.processIncompleteBox) return;\n\t\tif (!this.processIncompleteBox(t)) return\n\t} else {\n\t\tvar e, i = "uuid" !== (e = t.box).type ? e.type: e.uuid;\n\t\tswitch (this.boxes.push(e), i) {\n\t\tcase "mdat":\n\t\t\tthis.mdats.push(e);\n\t\t\tbreak;\n\t\tcase "moof":\n\t\t\tthis.moofs.push(e);\n\t\t\tbreak;\n\t\tcase "moov":\n\t\t\tthis.moovStartFound = !0,\n\t\t\t0 === this.mdats.length && (this.isProgressive = !0);\n\t\tdefault:\n\t\t\tvoid 0 !== this[i] && Log.warn("ISOFile", "Duplicate Box of type: " + i + ", overriding previous occurrence"),\n\t\t\tthis[i] = e\n\t\t}\n\t\tthis.updateUsedBytes && this.updateUsedBytes(e, t)\n\t}\n},\nISOFile.prototype.checkBuffer = function(t) {\n\tif (null == t) throw "Buffer must be defined and non empty";\n\tif (void 0 === t.fileStart) throw "Buffer must have a fileStart property";\n\treturn 0 === t.byteLength ? (Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + t.fileStart + ")"), this.stream.logBufferLevel(), !1) : (Log.info("ISOFile", "Processing buffer (fileStart: " + t.fileStart + ")"), t.usedBytes = 0, this.stream.insertBuffer(t), this.stream.logBufferLevel(), !!this.stream.initialized() || (Log.warn("ISOFile", "Not ready to start parsing"), !1))\n},\nISOFile.prototype.appendBuffer = function(t, e) {\n\tvar i;\n\tif (this.checkBuffer(t)) return this.parse(),\n\tthis.moovStartFound && !this.moovStartSent && (this.moovStartSent = !0, this.onMoovStart && this.onMoovStart()),\n\tthis.moov ? (this.sampleListBuilt || (this.buildSampleLists(), this.sampleListBuilt = !0), this.updateSampleLists(), this.onReady && !this.readySent && (this.readySent = !0, this.onReady(this.getInfo())), this.processSamples(e), this.nextSeekPosition ? (i = this.nextSeekPosition, this.nextSeekPosition = void 0) : i = this.nextParsePosition, this.stream.getEndFilePositionAfter && (i = this.stream.getEndFilePositionAfter(i))) : i = this.nextParsePosition || 0,\n\tthis.sidx && this.onSidx && !this.sidxSent && (this.onSidx(this.sidx), this.sidxSent = !0),\n\tthis.meta && (this.flattenItemInfo && !this.itemListBuilt && (this.flattenItemInfo(), this.itemListBuilt = !0), this.processItems && this.processItems(this.onItem)),\n\tthis.stream.cleanBuffers && (Log.info("ISOFile", "Done processing buffer (fileStart: " + t.fileStart + ") - next buffer to fetch should have a fileStart position of " + i), this.stream.logBufferLevel(), this.stream.cleanBuffers(), this.stream.logBufferLevel(!0), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize())),\n\ti\n},\nISOFile.prototype.getInfo = function() {\n\tvar t, e, i, r, s, a, n = {},\n\to = new Date("1904-01-01T00:00:00Z").getTime();\n\tif (this.moov) for (n.hasMoov = !0, n.duration = this.moov.mvhd.duration, n.timescale = this.moov.mvhd.timescale, n.isFragmented = null != this.moov.mvex, n.isFragmented && this.moov.mvex.mehd && (n.fragment_duration = this.moov.mvex.mehd.fragment_duration), n.isProgressive = this.isProgressive, n.hasIOD = null != this.moov.iods, n.brands = [], n.brands.push(this.ftyp.major_brand), n.brands = n.brands.concat(this.ftyp.compatible_brands), n.created = new Date(o + 1e3 * this.moov.mvhd.creation_time), n.modified = new Date(o + 1e3 * this.moov.mvhd.modification_time), n.tracks = [], n.audioTracks = [], n.videoTracks = [], n.subtitleTracks = [], n.metadataTracks = [], n.hintTracks = [], n.otherTracks = [], t = 0; t < this.moov.traks.length; t++) {\n\t\tif (a = (i = this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0], r = {},\n\t\tn.tracks.push(r), r.id = i.tkhd.track_id, r.name = i.mdia.hdlr.name, r.references = [], i.tref) for (e = 0; e < i.tref.boxes.length; e++) s = {},\n\t\tr.references.push(s),\n\t\ts.type = i.tref.boxes[e].type,\n\t\ts.track_ids = i.tref.boxes[e].track_ids;\n\t\ti.edts && (r.edits = i.edts.elst.entries),\n\t\tr.created = new Date(o + 1e3 * i.tkhd.creation_time),\n\t\tr.modified = new Date(o + 1e3 * i.tkhd.modification_time),\n\t\tr.movie_duration = i.tkhd.duration,\n\t\tr.movie_timescale = n.timescale,\n\t\tr.layer = i.tkhd.layer,\n\t\tr.alternate_group = i.tkhd.alternate_group,\n\t\tr.volume = i.tkhd.volume,\n\t\tr.matrix = i.tkhd.matrix,\n\t\tr.track_width = i.tkhd.width / 65536,\n\t\tr.track_height = i.tkhd.height / 65536,\n\t\tr.timescale = i.mdia.mdhd.timescale,\n\t\tr.cts_shift = i.mdia.minf.stbl.cslg,\n\t\tr.duration = i.mdia.mdhd.duration,\n\t\tr.samples_duration = i.samples_duration,\n\t\tr.codec = a.getCodec(),\n\t\tr.kind = i.udta && i.udta.kinds.length ? i.udta.kinds[0] : {\n\t\t\tschemeURI: "",\n\t\t\tvalue: ""\n\t\t},\n\t\tr.language = i.mdia.elng ? i.mdia.elng.extended_language: i.mdia.mdhd.languageString,\n\t\tr.nb_samples = i.samples.length,\n\t\tr.size = i.samples_size,\n\t\tr.bitrate = 8 * r.size * r.timescale / r.samples_duration,\n\t\ta.isAudio() ? (r.type = "audio", n.audioTracks.push(r), r.audio = {},\n\t\tr.audio.sample_rate = a.getSampleRate(), r.audio.channel_count = a.getChannelCount(), r.audio.sample_size = a.getSampleSize()) : a.isVideo() ? (r.type = "video", n.videoTracks.push(r), r.video = {},\n\t\tr.video.width = a.getWidth(), r.video.height = a.getHeight()) : a.isSubtitle() ? (r.type = "subtitles", n.subtitleTracks.push(r)) : a.isHint() ? (r.type = "metadata", n.hintTracks.push(r)) : a.isMetadata() ? (r.type = "metadata", n.metadataTracks.push(r)) : (r.type = "metadata", n.otherTracks.push(r))\n\t} else n.hasMoov = !1;\n\tif (n.mime = "", n.hasMoov && n.tracks) {\n\t\tfor (n.videoTracks && 0 < n.videoTracks.length ? n.mime += \'video/mp4; codecs="\': n.audioTracks && 0 < n.audioTracks.length ? n.mime += \'audio/mp4; codecs="\': n.mime += \'application/mp4; codecs="\', t = 0; t < n.tracks.length; t++) 0 !== t && (n.mime += ","),\n\t\tn.mime += n.tracks[t].codec;\n\t\tn.mime += \'"; profiles="\',\n\t\tn.mime += this.ftyp.compatible_brands.join(),\n\t\tn.mime += \'"\'\n\t}\n\treturn n\n},\nISOFile.prototype.setNextSeekPositionFromSample = function(t) {\n\tt && (this.nextSeekPosition ? this.nextSeekPosition = Math.min(t.offset + t.alreadyRead, this.nextSeekPosition) : this.nextSeekPosition = t.offset + t.alreadyRead)\n},\nISOFile.prototype.processSamples = function(t) {\n\tvar e;\n\tif (this.sampleProcessingStarted) {\n\t\tif (this.isFragmentationInitialized && null !== this.onSegment) for (e = 0; e < this.fragmentedTracks.length; e++) for (var i = this.fragmentedTracks[e], r = i.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\tLog.debug("ISOFile", "Creating media fragment on track #" + i.id + " for sample " + r.nextSample);\n\t\t\tvar s = this.createFragment(i.id, r.nextSample, i.segmentStream);\n\t\t\tif (!s) break;\n\t\t\tif (i.segmentStream = s, r.nextSample++, (r.nextSample % i.nb_samples == 0 || t || r.nextSample >= r.samples.length) && (Log.info("ISOFile", "Sending fragmented data on track #" + i.id + " for samples [" + Math.max(0, r.nextSample - i.nb_samples) + "," + (r.nextSample - 1) + "]"), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize()), this.onSegment && this.onSegment(i.id, i.user, i.segmentStream.buffer, r.nextSample, t || r.nextSample >= r.samples.length), i.segmentStream = null, i !== this.fragmentedTracks[e])) break\n\t\t}\n\t\tif (null !== this.onSamples) for (e = 0; e < this.extractedTracks.length; e++) {\n\t\t\tvar a = this.extractedTracks[e];\n\t\t\tfor (r = a.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\t\tLog.debug("ISOFile", "Exporting on track #" + a.id + " sample #" + r.nextSample);\n\t\t\t\tvar n = this.getSample(r, r.nextSample);\n\t\t\t\tif (!n) {\n\t\t\t\t\tthis.setNextSeekPositionFromSample(r.samples[r.nextSample]);\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (r.nextSample++, a.samples.push(n), (r.nextSample % a.nb_samples == 0 || r.nextSample >= r.samples.length) && (Log.debug("ISOFile", "Sending samples on track #" + a.id + " for sample " + r.nextSample), this.onSamples && this.onSamples(a.id, a.user, a.samples), a.samples = [], a !== this.extractedTracks[e])) break\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getBox = function(t) {\n\tt = this.getBoxes(t, !0);\n\treturn t.length ? t[0] : null\n},\nISOFile.prototype.getBoxes = function(t, e) {\n\tvar i = [];\n\treturn ISOFile._sweep.call(this, t, i, e),\n\ti\n},\nISOFile._sweep = function(t, e, i) {\n\tfor (var r in this.type && this.type == t && e.push(this), this.boxes) {\n\t\tif (e.length && i) return;\n\t\tISOFile._sweep.call(this.boxes[r], t, e, i)\n\t}\n},\nISOFile.prototype.getTrackSamplesInfo = function(t) {\n\tt = this.getTrackById(t);\n\tif (t) return t.samples\n},\nISOFile.prototype.getTrackSample = function(t, e) {\n\tt = this.getTrackById(t);\n\treturn this.getSample(t, e)\n},\nISOFile.prototype.releaseUsedSamples = function(t, e) {\n\tvar i = 0,\n\tr = this.getTrackById(t);\n\tr.lastValidSample || (r.lastValidSample = 0);\n\tfor (var s = r.lastValidSample; s < e; s++) i += this.releaseSample(r, s);\n\tLog.info("ISOFile", "Track #" + t + " released samples up to " + e + " (released size: " + i + ", remaining: " + this.samplesDataSize + ")"),\n\tr.lastValidSample = e\n},\nISOFile.prototype.start = function() {\n\tthis.sampleProcessingStarted = !0,\n\tthis.processSamples(!1)\n},\nISOFile.prototype.stop = function() {\n\tthis.sampleProcessingStarted = !1\n},\nISOFile.prototype.flush = function() {\n\tLog.info("ISOFile", "Flushing remaining samples"),\n\tthis.updateSampleLists(),\n\tthis.processSamples(!0),\n\tthis.stream.cleanBuffers(),\n\tthis.stream.logBufferLevel(!0)\n},\nISOFile.prototype.seekTrack = function(t, e, i) {\n\tvar r, s, a, n, o = 0,\n\th = 0;\n\tif (0 === i.samples.length) return Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0"),\n\t{\n\t\toffset: 0,\n\t\ttime: 0\n\t};\n\tfor (r = 0; r < i.samples.length; r++) {\n\t\tif (s = i.samples[r], 0 === r) h = 0,\n\t\tn = s.timescale;\n\t\telse if (s.cts > t * s.timescale) {\n\t\t\th = r - 1;\n\t\t\tbreak\n\t\t}\n\t\te && s.is_sync && (o = r)\n\t}\n\tfor (e && (h = o), t = i.samples[h].cts, i.nextSample = h; i.samples[h].alreadyRead === i.samples[h].size && i.samples[h + 1];) h++;\n\treturn a = i.samples[h].offset + i.samples[h].alreadyRead,\n\tLog.info("ISOFile", "Seeking to " + (e ? "RAP": "") + " sample #" + i.nextSample + " on track " + i.tkhd.track_id + ", time " + Log.getDurationString(t, n) + " and offset: " + a),\n\t{\n\t\toffset: a,\n\t\ttime: t / n\n\t}\n},\nISOFile.prototype.getTrackDuration = function(t) {\n\treturn t.samples ? ((t = t.samples[t.samples.length - 1]).cts + t.duration) / t.timescale: 1 / 0\n},\nISOFile.prototype.seek = function(t, e) {\n\tvar i, r, s = this.moov,\n\ta = {\n\t\toffset: 1 / 0,\n\t\ttime: 1 / 0\n\t};\n\tif (this.moov) {\n\t\tfor (r = 0; r < s.traks.length; r++) i = s.traks[r],\n\t\tt > this.getTrackDuration(i) || ((i = this.seekTrack(t, e, i)).offset < a.offset && (a.offset = i.offset), i.time < a.time && (a.time = i.time));\n\t\treturn Log.info("ISOFile", "Seeking at time " + Log.getDurationString(a.time, 1) + " needs a buffer with a fileStart position of " + a.offset),\n\t\ta.offset === 1 / 0 ? a = {\n\t\t\toffset: this.nextParsePosition,\n\t\t\ttime: 0\n\t\t}: a.offset = this.stream.getEndFilePositionAfter(a.offset),\n\t\tLog.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + a.offset),\n\t\ta\n\t}\n\tthrow "Cannot seek: moov not received!"\n},\nISOFile.prototype.equal = function(t) {\n\tfor (var e = 0; e < this.boxes.length && e < t.boxes.length;) {\n\t\tvar i = this.boxes[e],\n\t\tr = t.boxes[e];\n\t\tif (!BoxParser.boxEqual(i, r)) return ! 1;\n\t\te++\n\t}\n\treturn ! 0\n},\n"undefined" != typeof exports && (exports.ISOFile = ISOFile),\nISOFile.prototype.lastBoxStartPosition = 0,\nISOFile.prototype.parsingMdat = null,\nISOFile.prototype.nextParsePosition = 0,\nISOFile.prototype.discardMdatData = !1,\nISOFile.prototype.processIncompleteBox = function(t) {\n\tvar e;\n\treturn "mdat" === t.type ? (e = new BoxParser[t.type + "Box"](t.size), this.parsingMdat = e, this.boxes.push(e), this.mdats.push(e), e.start = t.start, e.hdr_size = t.hdr_size, this.stream.addUsedBytes(e.hdr_size), this.lastBoxStartPosition = e.start + e.size, this.stream.seek(e.start + e.size, !1, this.discardMdatData) ? !(this.parsingMdat = null) : (this.moovStartFound ? this.nextParsePosition = this.stream.findEndContiguousBuf() : this.nextParsePosition = e.start + e.size, !1)) : ("moov" === t.type && (this.moovStartFound = !0, 0 === this.mdats.length && (this.isProgressive = !0)), !!this.stream.mergeNextBuffer && this.stream.mergeNextBuffer() ? (this.nextParsePosition = this.stream.getEndPosition(), !0) : (!t.type || this.moovStartFound ? this.nextParsePosition = this.stream.getEndPosition() : this.nextParsePosition = this.stream.getPosition() + t.size, !1))\n},\nISOFile.prototype.hasIncompleteMdat = function() {\n\treturn null !== this.parsingMdat\n},\nISOFile.prototype.processIncompleteMdat = function() {\n\tvar t = this.parsingMdat;\n\treturn this.stream.seek(t.start + t.size, !1, this.discardMdatData) ? (Log.debug("ISOFile", "Found \'mdat\' end in buffered data"), !(this.parsingMdat = null)) : (this.nextParsePosition = this.stream.findEndContiguousBuf(), !1)\n},\nISOFile.prototype.restoreParsePosition = function() {\n\treturn this.stream.seek(this.lastBoxStartPosition, !0, this.discardMdatData)\n},\nISOFile.prototype.saveParsePosition = function() {\n\tthis.lastBoxStartPosition = this.stream.getPosition()\n},\nISOFile.prototype.updateUsedBytes = function(t, e) {\n\tthis.stream.addUsedBytes && ("mdat" === t.type ? (this.stream.addUsedBytes(t.hdr_size), this.discardMdatData && this.stream.addUsedBytes(t.size - t.hdr_size)) : this.stream.addUsedBytes(t.size))\n},\nISOFile.prototype.add = BoxParser.Box.prototype.add,\nISOFile.prototype.addBox = BoxParser.Box.prototype.addBox,\nISOFile.prototype.init = function(t) {\n\tvar e = t || {},\n\tt = (this.add("ftyp").set("major_brand", e.brands && e.brands[0] || "iso4").set("minor_version", 0).set("compatible_brands", e.brands || ["iso4"]), this.add("moov"));\n\treturn t.add("mvhd").set("timescale", e.timescale || 600).set("rate", e.rate || 65536).set("creation_time", 0).set("modification_time", 0).set("duration", e.duration || 0).set("volume", e.width ? 0 : 256).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("next_track_id", 1),\n\tt.add("mvex"),\n\tthis\n},\nISOFile.prototype.addTrack = function(t) {\n\tthis.moov || this.init(t);\n\tvar e = t || {};\n\te.width = e.width || 320,\n\te.height = e.height || 320,\n\te.id = e.id || this.moov.mvhd.next_track_id,\n\te.type = e.type || "avc1";\n\tvar i = this.moov.add("trak");\n\tthis.moov.mvhd.next_track_id = e.id + 1,\n\ti.add("tkhd").set("flags", BoxParser.TKHD_FLAG_ENABLED | BoxParser.TKHD_FLAG_IN_MOVIE | BoxParser.TKHD_FLAG_IN_PREVIEW).set("creation_time", 0).set("modification_time", 0).set("track_id", e.id).set("duration", e.duration || 0).set("layer", e.layer || 0).set("alternate_group", 0).set("volume", 1).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("width", e.width << 16).set("height", e.height << 16);\n\tt = i.add("mdia");\n\tt.add("mdhd").set("creation_time", 0).set("modification_time", 0).set("timescale", e.timescale || 1).set("duration", e.media_duration || 0).set("language", e.language || "und"),\n\tt.add("hdlr").set("handler", e.hdlr || "vide").set("name", e.name || "Track created with MP4Box.js"),\n\tt.add("elng").set("extended_language", e.language || "fr-FR");\n\tvar r = t.add("minf");\n\tif (void 0 !== BoxParser[e.type + "SampleEntry"]) {\n\t\tvar s = new BoxParser[e.type + "SampleEntry"];\n\t\ts.data_reference_index = 1;\n\t\tvar a, n, o = "";\n\t\tfor (a in BoxParser.sampleEntryCodes) for (var h = BoxParser.sampleEntryCodes[a], d = 0; d < h.length; d++) if (-1 < h.indexOf(e.type)) {\n\t\t\to = a;\n\t\t\tbreak\n\t\t}\n\t\tswitch (o) {\n\t\tcase "Visual":\n\t\t\tr.add("vmhd").set("graphicsmode", 0).set("opcolor", [0, 0, 0]),\n\t\t\ts.set("width", e.width).set("height", e.height).set("horizresolution", 72 << 16).set("vertresolution", 72 << 16).set("frame_count", 1).set("compressorname", e.type + " Compressor").set("depth", 24),\n\t\t\te.avcDecoderConfigRecord ? ((n = new BoxParser.avcCBox).parse(new MP4BoxStream(e.avcDecoderConfigRecord)), s.addBox(n)) : e.hevcDecoderConfigRecord && ((n = new BoxParser.hvcCBox).parse(new MP4BoxStream(e.hevcDecoderConfigRecord)), s.addBox(n));\n\t\t\tbreak;\n\t\tcase "Audio":\n\t\t\tr.add("smhd").set("balance", e.balance || 0),\n\t\t\ts.set("channel_count", e.channel_count || 2).set("samplesize", e.samplesize || 16).set("samplerate", e.samplerate || 65536);\n\t\t\tbreak;\n\t\tcase "Hint":\n\t\t\tr.add("hmhd");\n\t\t\tbreak;\n\t\tcase "Subtitle":\n\t\t\tr.add("sthd"),\n\t\t\t"stpp" === e.type && s.set("namespace", e.namespace || "nonamespace").set("schema_location", e.schema_location || "").set("auxiliary_mime_types", e.auxiliary_mime_types || "");\n\t\t\tbreak;\n\t\tcase "Metadata":\n\t\tcase "System":\n\t\tdefault:\n\t\t\tr.add("nmhd")\n\t\t}\n\t\te.description && s.addBox(e.description),\n\t\te.description_boxes && e.description_boxes.forEach(function(t) {\n\t\t\ts.addBox(t)\n\t\t}),\n\t\tr.add("dinf").add("dref").addEntry((new BoxParser["url Box"]).set("flags", 1));\n\t\tt = r.add("stbl");\n\t\treturn t.add("stsd").addEntry(s),\n\t\tt.add("stts").set("sample_counts", []).set("sample_deltas", []),\n\t\tt.add("stsc").set("first_chunk", []).set("samples_per_chunk", []).set("sample_description_index", []),\n\t\tt.add("stco").set("chunk_offsets", []),\n\t\tt.add("stsz").set("sample_sizes", []),\n\t\tthis.moov.mvex.add("trex").set("track_id", e.id).set("default_sample_description_index", e.default_sample_description_index || 1).set("default_sample_duration", e.default_sample_duration || 0).set("default_sample_size", e.default_sample_size || 0).set("default_sample_flags", e.default_sample_flags || 0),\n\t\tthis.buildTrakSampleLists(i),\n\t\te.id\n\t}\n},\nBoxParser.Box.prototype.computeSize = function(t) {\n\tt = t || new DataStream;\n\tt.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t)\n},\nISOFile.prototype.addSample = function(t, e, i) {\n\tvar r = i || {},\n\ti = {},\n\tt = this.getTrackById(t);\n\tif (null !== t) {\n\t\ti.number = t.samples.length,\n\t\ti.track_id = t.tkhd.track_id,\n\t\ti.timescale = t.mdia.mdhd.timescale,\n\t\ti.description_index = r.sample_description_index ? r.sample_description_index - 1 : 0,\n\t\ti.description = t.mdia.minf.stbl.stsd.entries[i.description_index],\n\t\ti.data = e,\n\t\ti.size = e.byteLength,\n\t\ti.alreadyRead = i.size,\n\t\ti.duration = r.duration || 1,\n\t\ti.cts = r.cts || 0,\n\t\ti.dts = r.dts || 0,\n\t\ti.is_sync = r.is_sync || !1,\n\t\ti.is_leading = r.is_leading || 0,\n\t\ti.depends_on = r.depends_on || 0,\n\t\ti.is_depended_on = r.is_depended_on || 0,\n\t\ti.has_redundancy = r.has_redundancy || 0,\n\t\ti.degradation_priority = r.degradation_priority || 0,\n\t\ti.offset = 0,\n\t\ti.subsamples = r.subsamples,\n\t\tt.samples.push(i),\n\t\tt.samples_size += i.size,\n\t\tt.samples_duration += i.duration,\n\t\tvoid 0 === t.first_dts && (t.first_dts = r.dts),\n\t\tthis.processSamples();\n\t\tr = this.createSingleSampleMoof(i);\n\t\treturn this.addBox(r),\n\t\tr.computeSize(),\n\t\tr.trafs[0].truns[0].data_offset = r.size + 8,\n\t\tthis.add("mdat").data = new Uint8Array(e),\n\t\ti\n\t}\n},\nISOFile.prototype.createSingleSampleMoof = function(t) {\n\tvar e = 0,\n\te = t.is_sync ? 1 << 25 : 65536,\n\ti = new BoxParser.moofBox;\n\ti.add("mfhd").set("sequence_number", this.nextMoofNumber),\n\tthis.nextMoofNumber++;\n\tvar r = i.add("traf"),\n\ts = this.getTrackById(t.track_id);\n\treturn r.add("tfhd").set("track_id", t.track_id).set("flags", BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\tr.add("tfdt").set("baseMediaDecodeTime", t.dts - (s.first_dts || 0)),\n\tr.add("trun").set("flags", BoxParser.TRUN_FLAGS_DATA_OFFSET | BoxParser.TRUN_FLAGS_DURATION | BoxParser.TRUN_FLAGS_SIZE | BoxParser.TRUN_FLAGS_FLAGS | BoxParser.TRUN_FLAGS_CTS_OFFSET).set("data_offset", 0).set("first_sample_flags", 0).set("sample_count", 1).set("sample_duration", [t.duration]).set("sample_size", [t.size]).set("sample_flags", [e]).set("sample_composition_time_offset", [t.cts - t.dts]),\n\ti\n},\nISOFile.prototype.lastMoofIndex = 0,\nISOFile.prototype.samplesDataSize = 0,\nISOFile.prototype.resetTables = function() {\n\tvar t, e;\n\tfor (this.initial_duration = this.moov.mvhd.duration, t = this.moov.mvhd.duration = 0; t < this.moov.traks.length; t++) { (e = this.moov.traks[t]).tkhd.duration = 0,\n\t\te.mdia.mdhd.duration = 0,\n\t\t(e.mdia.minf.stbl.stco || e.mdia.minf.stbl.co64).chunk_offsets = [],\n\t\t(i = e.mdia.minf.stbl.stsc).first_chunk = [],\n\t\ti.samples_per_chunk = [],\n\t\ti.sample_description_index = [],\n\t\t(e.mdia.minf.stbl.stsz || e.mdia.minf.stbl.stz2).sample_sizes = [],\n\t\t(i = e.mdia.minf.stbl.stts).sample_counts = [],\n\t\ti.sample_deltas = [],\n\t\t(i = e.mdia.minf.stbl.ctts) && (i.sample_counts = [], i.sample_offsets = []),\n\t\ti = e.mdia.minf.stbl.stss;\n\t\tvar i = e.mdia.minf.stbl.boxes.indexOf(i); - 1 != i && (e.mdia.minf.stbl.boxes[i] = null)\n\t}\n},\nISOFile.initSampleGroups = function(t, e, i, r, s) {\n\tvar a, n, o, h;\n\tfunction d(t, e, i) {\n\t\tthis.grouping_type = t,\n\t\tthis.grouping_type_parameter = e,\n\t\tthis.sbgp = i,\n\t\tthis.last_sample_in_run = -1,\n\t\tthis.entry_index = -1\n\t}\n\tfor (e && (e.sample_groups_info = []), t.sample_groups_info || (t.sample_groups_info = []), n = 0; n < i.length; n++) {\n\t\tfor (h = i[n].grouping_type + "/" + i[n].grouping_type_parameter, o = new d(i[n].grouping_type, i[n].grouping_type_parameter, i[n]), e && (e.sample_groups_info[h] = o), t.sample_groups_info[h] || (t.sample_groups_info[h] = o), a = 0; a < r.length; a++) r[a].grouping_type === i[n].grouping_type && (o.description = r[a], o.description.used = !0);\n\t\tif (s) for (a = 0; a < s.length; a++) s[a].grouping_type === i[n].grouping_type && (o.fragment_description = s[a], o.fragment_description.used = !0, o.is_fragment = !0)\n\t}\n\tif (e) {\n\t\tif (s) for (n = 0; n < s.length; n++) ! s[n].used && 2 <= s[n].version && (h = s[n].grouping_type + "/0", (o = new d(s[n].grouping_type, 0)).is_fragment = !0, e.sample_groups_info[h] || (e.sample_groups_info[h] = o))\n\t} else for (n = 0; n < r.length; n++) ! r[n].used && 2 <= r[n].version && (h = r[n].grouping_type + "/0", o = new d(r[n].grouping_type, 0), t.sample_groups_info[h] || (t.sample_groups_info[h] = o))\n},\nISOFile.setSampleGroupProperties = function(t, e, i, r) {\n\tvar s, a, n;\n\tfor (s in e.sample_groups = [], r) e.sample_groups[s] = {},\n\te.sample_groups[s].grouping_type = r[s].grouping_type,\n\te.sample_groups[s].grouping_type_parameter = r[s].grouping_type_parameter,\n\ti >= r[s].last_sample_in_run && (r[s].last_sample_in_run < 0 && (r[s].last_sample_in_run = 0), r[s].entry_index++, r[s].entry_index <= r[s].sbgp.entries.length - 1 && (r[s].last_sample_in_run += r[s].sbgp.entries[r[s].entry_index].sample_count)),\n\tr[s].entry_index <= r[s].sbgp.entries.length - 1 ? e.sample_groups[s].group_description_index = r[s].sbgp.entries[r[s].entry_index].group_description_index: e.sample_groups[s].group_description_index = -1,\n\t0 !== e.sample_groups[s].group_description_index && (n = r[s].fragment_description || r[s].description, 0 < e.sample_groups[s].group_description_index ? (a = 65535 < e.sample_groups[s].group_description_index ? (e.sample_groups[s].group_description_index >> 16) - 1 : e.sample_groups[s].group_description_index - 1, n && 0 <= a && (e.sample_groups[s].description = n.entries[a])) : n && 2 <= n.version && 0 < n.default_group_description_index && (e.sample_groups[s].description = n.entries[n.default_group_description_index - 1]))\n},\nISOFile.process_sdtp = function(t, e, i) {\n\te && (t ? (e.is_leading = t.is_leading[i], e.depends_on = t.sample_depends_on[i], e.is_depended_on = t.sample_is_depended_on[i], e.has_redundancy = t.sample_has_redundancy[i]) : (e.is_leading = 0, e.depends_on = 0, e.is_depended_on = 0, e.has_redundancy = 0))\n},\nISOFile.prototype.buildSampleLists = function() {\n\tfor (var t, e = 0; e < this.moov.traks.length; e++) t = this.moov.traks[e],\n\tthis.buildTrakSampleLists(t)\n},\nISOFile.prototype.buildTrakSampleLists = function(t) {\n\tvar e, i, r, s, a, n, o, h, d, l, p, f, u, _, c, m, x, g, y, B, S, P, U, b;\n\tif (t.samples = [], t.samples_duration = 0, t.samples_size = 0, i = t.mdia.minf.stbl.stco || t.mdia.minf.stbl.co64, r = t.mdia.minf.stbl.stsc, s = t.mdia.minf.stbl.stsz || t.mdia.minf.stbl.stz2, a = t.mdia.minf.stbl.stts, n = t.mdia.minf.stbl.ctts, o = t.mdia.minf.stbl.stss, h = t.mdia.minf.stbl.stsd, d = t.mdia.minf.stbl.subs, f = t.mdia.minf.stbl.stdp, l = t.mdia.minf.stbl.sbgps, p = t.mdia.minf.stbl.sgpds, S = B = y = g = -1, b = U = P = 0, ISOFile.initSampleGroups(t, null, l, p), void 0 !== s) {\n\t\tfor (e = 0; e < s.sample_sizes.length; e++) {\n\t\t\tvar v = {};\n\t\t\tv.number = e,\n\t\t\tv.track_id = t.tkhd.track_id,\n\t\t\tv.timescale = t.mdia.mdhd.timescale,\n\t\t\tv.alreadyRead = 0,\n\t\t\t(t.samples[e] = v).size = s.sample_sizes[e],\n\t\t\tt.samples_size += v.size,\n\t\t\t0 === e ? (_ = 1, u = 0, v.chunk_index = _, v.chunk_run_index = u, x = r.samples_per_chunk[u], m = 0, c = u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0) : e < x ? (v.chunk_index = _, v.chunk_run_index = u) : (_++, m = 0, (v.chunk_index = _) <= c || (c = ++u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0), v.chunk_run_index = u, x += r.samples_per_chunk[u]),\n\t\t\tv.description_index = r.sample_description_index[v.chunk_run_index] - 1,\n\t\t\tv.description = h.entries[v.description_index],\n\t\t\tv.offset = i.chunk_offsets[v.chunk_index - 1] + m,\n\t\t\tm += v.size,\n\t\t\tg < e && (y++, g < 0 && (g = 0), g += a.sample_counts[y]),\n\t\t\t0 < e ? (t.samples[e - 1].duration = a.sample_deltas[y], t.samples_duration += t.samples[e - 1].duration, v.dts = t.samples[e - 1].dts + t.samples[e - 1].duration) : v.dts = 0,\n\t\t\tn ? (B <= e && (S++, B < 0 && (B = 0), B += n.sample_counts[S]), v.cts = t.samples[e].dts + n.sample_offsets[S]) : v.cts = v.dts,\n\t\t\to ? (e == o.sample_numbers[P] - 1 ? (v.is_sync = !0, P++) : (v.is_sync = !1, v.degradation_priority = 0), d && d.entries[U].sample_delta + b == e + 1 && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta, U++)) : v.is_sync = !0,\n\t\t\tISOFile.process_sdtp(t.mdia.minf.stbl.sdtp, v, v.number),\n\t\t\tv.degradation_priority = f ? f.priority[e] : 0,\n\t\t\td && d.entries[U].sample_delta + b == e && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta),\n\t\t\t(0 < l.length || 0 < p.length) && ISOFile.setSampleGroupProperties(t, v, e, t.sample_groups_info)\n\t\t}\n\t\t0 < e && (t.samples[e - 1].duration = Math.max(t.mdia.mdhd.duration - t.samples[e - 1].dts, 0), t.samples_duration += t.samples[e - 1].duration)\n\t}\n},\nISOFile.prototype.updateSampleLists = function() {\n\tvar t, e, i, r, s, a, n, o, h, d, l, p;\n\tif (void 0 !== this.moov) for (; this.lastMoofIndex < this.moofs.length;) if (n = this.moofs[this.lastMoofIndex], this.lastMoofIndex++, "moof" == n.type) for (o = n, t = 0; t < o.trafs.length; t++) {\n\t\tfor (h = o.trafs[t], d = this.getTrackById(h.tfhd.track_id), l = this.getTrexById(h.tfhd.track_id), e = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? h.tfhd.default_sample_description_index: l ? l.default_sample_description_index: 1, i = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? h.tfhd.default_sample_duration: l ? l.default_sample_duration: 0, r = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? h.tfhd.default_sample_size: l ? l.default_sample_size: 0, s = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? h.tfhd.default_sample_flags: l ? l.default_sample_flags: 0, (h.sample_number = 0) < h.sbgps.length && ISOFile.initSampleGroups(d, h, h.sbgps, d.mdia.minf.stbl.sgpds, h.sgpds), y = 0; y < h.truns.length; y++) for (var f = h.truns[y], u = 0; u < f.sample_count; u++) { (p = {}).moof_number = this.lastMoofIndex,\n\t\t\tp.number_in_traf = h.sample_number,\n\t\t\th.sample_number++,\n\t\t\tp.number = d.samples.length,\n\t\t\th.first_sample_index = d.samples.length,\n\t\t\td.samples.push(p),\n\t\t\tp.track_id = d.tkhd.track_id,\n\t\t\tp.timescale = d.mdia.mdhd.timescale,\n\t\t\tp.description_index = e - 1,\n\t\t\tp.description = d.mdia.minf.stbl.stsd.entries[p.description_index],\n\t\t\tp.size = r,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_SIZE && (p.size = f.sample_size[u]),\n\t\t\td.samples_size += p.size,\n\t\t\tp.duration = i,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_DURATION && (p.duration = f.sample_duration[u]),\n\t\t\td.samples_duration += p.duration,\n\t\t\td.first_traf_merged || 0 < u ? p.dts = d.samples[d.samples.length - 2].dts + d.samples[d.samples.length - 2].duration: (h.tfdt ? p.dts = h.tfdt.baseMediaDecodeTime: p.dts = 0, d.first_traf_merged = !0),\n\t\t\tp.cts = p.dts,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (p.cts = p.dts + f.sample_composition_time_offset[u]),\n\t\t\tx = s,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_FLAGS ? x = f.sample_flags[u] : 0 === u && f.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (x = f.first_sample_flags),\n\t\t\tp.is_sync = !(x >> 16 & 1),\n\t\t\tp.is_leading = x >> 26 & 3,\n\t\t\tp.depends_on = x >> 24 & 3,\n\t\t\tp.is_depended_on = x >> 22 & 3,\n\t\t\tp.has_redundancy = x >> 20 & 3,\n\t\t\tp.degradation_priority = 65535 & x;\n\t\t\tvar _ = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET),\n\t\t\tc = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\t\t\tm = !!(f.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET),\n\t\t\tx = 0,\n\t\t\tx = _ ? h.tfhd.base_data_offset: c || 0 === y ? o.start: a;\n\t\t\tp.offset = 0 === y && 0 === u ? m ? x + f.data_offset: x: a,\n\t\t\ta = p.offset + p.size,\n\t\t\t(0 < h.sbgps.length || 0 < h.sgpds.length || 0 < d.mdia.minf.stbl.sbgps.length || 0 < d.mdia.minf.stbl.sgpds.length) && ISOFile.setSampleGroupProperties(d, p, p.number_in_traf, h.sample_groups_info)\n\t\t}\n\t\tif (h.subs) {\n\t\t\td.has_fragment_subsamples = !0;\n\t\t\tfor (var g = h.first_sample_index,\n\t\t\ty = 0; y < h.subs.entries.length; y++) g += h.subs.entries[y].sample_delta,\n\t\t\t(p = d.samples[g - 1]).subsamples = h.subs.entries[y].subsamples\n\t\t}\n\t}\n},\nISOFile.prototype.getSample = function(t, e) {\n\tvar i, r = t.samples[e];\n\tif (!this.moov) return null;\n\tif (r.data) {\n\t\tif (r.alreadyRead == r.size) return r\n\t} else r.data = new Uint8Array(r.size),\n\tr.alreadyRead = 0,\n\tthis.samplesDataSize += r.size,\n\tLog.debug("ISOFile", "Allocating sample #" + e + " on track #" + t.tkhd.track_id + " of size " + r.size + " (total: " + this.samplesDataSize + ")");\n\tfor (;;) {\n\t\tvar s = this.stream.findPosition(!0, r.offset + r.alreadyRead, !1);\n\t\tif (! (-1 < s)) return null;\n\t\ts = (i = this.stream.buffers[s]).byteLength - (r.offset + r.alreadyRead - i.fileStart);\n\t\tif (r.size - r.alreadyRead <= s) return Log.debug("ISOFile", "Getting sample #" + e + " data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + (r.size - r.alreadyRead) + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, r.size - r.alreadyRead),\n\t\ti.usedBytes += r.size - r.alreadyRead,\n\t\tthis.stream.logBufferLevel(),\n\t\tr.alreadyRead = r.size,\n\t\tr;\n\t\tif (0 == s) return null;\n\t\tLog.debug("ISOFile", "Getting sample #" + e + " partial data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + s + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, s),\n\t\tr.alreadyRead += s,\n\t\ti.usedBytes += s,\n\t\tthis.stream.logBufferLevel()\n\t}\n},\nISOFile.prototype.releaseSample = function(t, e) {\n\te = t.samples[e];\n\treturn e.data ? (this.samplesDataSize -= e.size, e.data = null, e.alreadyRead = 0, e.size) : 0\n},\nISOFile.prototype.getAllocatedSampleDataSize = function() {\n\treturn this.samplesDataSize\n},\nISOFile.prototype.getCodecs = function() {\n\tfor (var t = "",\n\te = 0; e < this.moov.traks.length; e++) 0 < e && (t += ","),\n\tt += this.moov.traks[e].mdia.minf.stbl.stsd.entries[0].getCodec();\n\treturn t\n},\nISOFile.prototype.getTrexById = function(t) {\n\tvar e;\n\tif (!this.moov || !this.moov.mvex) return null;\n\tfor (e = 0; e < this.moov.mvex.trexs.length; e++) {\n\t\tvar i = this.moov.mvex.trexs[e];\n\t\tif (i.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.getTrackById = function(t) {\n\tif (void 0 === this.moov) return null;\n\tfor (var e = 0; e < this.moov.traks.length; e++) {\n\t\tvar i = this.moov.traks[e];\n\t\tif (i.tkhd.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.itemsDataSize = 0,\nISOFile.prototype.flattenItemInfo = function() {\n\tvar t = this.items,\n\te = this.entity_groups,\n\ti = this.meta;\n\tif (null != i && void 0 !== i.hdlr && void 0 !== i.iinf) {\n\t\tfor (d = 0; d < i.iinf.item_infos.length; d++)(s = {}).id = i.iinf.item_infos[d].item_ID,\n\t\t(t[s.id] = s).ref_to = [],\n\t\ts.name = i.iinf.item_infos[d].item_name,\n\t\t0 < i.iinf.item_infos[d].protection_index && (s.protection = i.ipro.protections[i.iinf.item_infos[d].protection_index - 1]),\n\t\ti.iinf.item_infos[d].item_type ? s.type = i.iinf.item_infos[d].item_type: s.type = "mime",\n\t\ts.content_type = i.iinf.item_infos[d].content_type,\n\t\ts.content_encoding = i.iinf.item_infos[d].content_encoding,\n\t\ts.item_uri_type = i.iinf.item_infos[d].item_uri_type;\n\t\tif (i.grpl) for (d = 0; d < i.grpl.boxes.length; d++) entity_group = {},\n\t\tentity_group.id = i.grpl.boxes[d].group_id,\n\t\tentity_group.entity_ids = i.grpl.boxes[d].entity_ids,\n\t\tentity_group.type = i.grpl.boxes[d].type,\n\t\te[entity_group.id] = entity_group;\n\t\tif (i.iloc) for (d = 0; d < i.iloc.items.length; d++) {\n\t\t\tvar r = i.iloc.items[d],\n\t\t\ts = t[r.item_ID];\n\t\t\tswitch (0 !== r.data_reference_index && (Log.warn("Item storage with reference to other files: not supported"), s.source = i.dinf.boxes[r.data_reference_index - 1]), r.construction_method) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tLog.warn("Item storage with construction_method : not supported")\n\t\t\t}\n\t\t\tfor (s.extents = [], n = s.size = 0; n < r.extents.length; n++) s.extents[n] = {},\n\t\t\ts.extents[n].offset = r.extents[n].extent_offset + r.base_offset,\n\t\t\t1 == r.construction_method && (s.extents[n].offset += i.idat.start + i.idat.hdr_size),\n\t\t\ts.extents[n].length = r.extents[n].extent_length,\n\t\t\ts.extents[n].alreadyRead = 0,\n\t\t\ts.size += s.extents[n].length\n\t\t}\n\t\tif (i.pitm && (t[i.pitm.item_id].primary = !0), i.iref) for (d = 0; d < i.iref.references.length; d++) for (var a = i.iref.references[d], n = 0; n < a.references.length; n++) t[a.from_item_ID].ref_to.push({\n\t\t\ttype: a.type,\n\t\t\tid: a.references[n]\n\t\t});\n\t\tif (i.iprp) for (var o = 0; o < i.iprp.ipmas.length; o++) for (var h = i.iprp.ipmas[o], d = 0; d < h.associations.length; d++) {\n\t\t\tvar l = h.associations[d];\n\t\t\tif (s = (s = t[l.id]) || e[l.id]) for (void 0 === s.properties && (s.properties = {},\n\t\t\ts.properties.boxes = []), n = 0; n < l.props.length; n++) {\n\t\t\t\tvar p = l.props[n];\n\t\t\t\t0 < p.property_index && p.property_index - 1 < i.iprp.ipco.boxes.length && (p = i.iprp.ipco.boxes[p.property_index - 1], s.properties[p.type] = p, s.properties.boxes.push(p))\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getItem = function(t) {\n\tvar e, i;\n\tif (!this.meta) return null;\n\tif (! (i = this.items[t]).data && i.size) i.data = new Uint8Array(i.size),\n\ti.alreadyRead = 0,\n\tthis.itemsDataSize += i.size,\n\tLog.debug("ISOFile", "Allocating item #" + t + " of size " + i.size + " (total: " + this.itemsDataSize + ")");\n\telse if (i.alreadyRead === i.size) return i;\n\tfor (var r = 0; r < i.extents.length; r++) {\n\t\tvar s = i.extents[r];\n\t\tif (s.alreadyRead !== s.length) {\n\t\t\tvar a = this.stream.findPosition(!0, s.offset + s.alreadyRead, !1);\n\t\t\tif (! (-1 < a)) return null;\n\t\t\ta = (e = this.stream.buffers[a]).byteLength - (s.offset + s.alreadyRead - e.fileStart);\n\t\t\tif (! (s.length - s.alreadyRead <= a)) return Log.debug("ISOFile", "Getting item #" + t + " extent #" + r + " partial data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + a + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, a),\n\t\t\ts.alreadyRead += a,\n\t\t\ti.alreadyRead += a,\n\t\t\te.usedBytes += a,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\tnull;\n\t\t\tLog.debug("ISOFile", "Getting item #" + t + " extent #" + r + " data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + (s.length - s.alreadyRead) + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, s.length - s.alreadyRead),\n\t\t\te.usedBytes += s.length - s.alreadyRead,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\ti.alreadyRead += s.length - s.alreadyRead,\n\t\t\ts.alreadyRead = s.length\n\t\t}\n\t}\n\treturn i.alreadyRead === i.size ? i: null\n},\nISOFile.prototype.releaseItem = function(t) {\n\tvar e = this.items[t];\n\tif (e.data) {\n\t\tthis.itemsDataSize -= e.size,\n\t\te.data = null;\n\t\tfor (var i = e.alreadyRead = 0; i < e.extents.length; i++) e.extents[i].alreadyRead = 0;\n\t\treturn e.size\n\t}\n\treturn 0\n},\nISOFile.prototype.processItems = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tthis.getItem(i.id),\n\t\tt && !i.sent && (t(i), i.sent = !0, i.data = null)\n\t}\n},\nISOFile.prototype.hasItem = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tif (i.name === t) return i.id\n\t}\n\treturn - 1\n},\nISOFile.prototype.getMetaHandler = function() {\n\treturn this.meta ? this.meta.hdlr.handler: null\n},\nISOFile.prototype.getPrimaryItem = function() {\n\treturn this.meta && this.meta.pitm ? this.getItem(this.meta.pitm.item_id) : null\n},\nISOFile.prototype.itemToFragmentedTrackFile = function(t) {\n\tvar e = t || {},\n\ti = null;\n\tif (null == (i = e.itemId ? this.getItem(e.itemId) : this.getPrimaryItem())) return null;\n\tt = new ISOFile;\n\tt.discardMdatData = !1;\n\te = {\n\t\ttype: i.type,\n\t\tdescription_boxes: i.properties.boxes\n\t};\n\ti.properties.ispe && (e.width = i.properties.ispe.image_width, e.height = i.properties.ispe.image_height);\n\te = t.addTrack(e);\n\treturn e ? (t.addSample(e, i.data), t) : null\n},\nISOFile.prototype.write = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t)\n},\nISOFile.prototype.createFragment = function(t, e, i) {\n\tvar r = this.getTrackById(t),\n\tt = this.getSample(r, e);\n\tif (null == t) return this.setNextSeekPositionFromSample(r.samples[e]),\n\tnull;\n\te = i || new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN;\n\ti = this.createSingleSampleMoof(t);\n\ti.write(e),\n\ti.trafs[0].truns[0].data_offset = i.size + 8,\n\tLog.debug("MP4Box", "Adjusting data_offset with new value " + i.trafs[0].truns[0].data_offset),\n\te.adjustUint32(i.trafs[0].truns[0].data_offset_position, i.trafs[0].truns[0].data_offset);\n\ti = new BoxParser.mdatBox;\n\treturn i.data = t.data,\n\ti.write(e),\n\te\n},\nISOFile.writeInitializationSegment = function(t, e, i, r) {\n\tvar s;\n\tLog.debug("ISOFile", "Generating initialization segment");\n\tvar a = new DataStream;\n\ta.endianness = DataStream.BIG_ENDIAN,\n\tt.write(a);\n\tvar n = e.add("mvex");\n\tfor (i && n.add("mehd").set("fragment_duration", i), s = 0; s < e.traks.length; s++) n.add("trex").set("track_id", e.traks[s].tkhd.track_id).set("default_sample_description_index", 1).set("default_sample_duration", r).set("default_sample_size", 0).set("default_sample_flags", 65536);\n\treturn e.write(a),\n\ta.buffer\n},\nISOFile.prototype.save = function(t) {\n\tvar e = new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(e),\n\te.save(t)\n},\nISOFile.prototype.getBuffer = function() {\n\tvar t = new DataStream;\n\treturn t.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t),\n\tt.buffer\n},\nISOFile.prototype.initializeSegmentation = function() {\n\tvar t, e, i, r;\n\tfor (null === this.onSegment && Log.warn("MP4Box", "No segmentation callback set!"), this.isFragmentationInitialized || (this.isFragmentationInitialized = !0, this.nextMoofNumber = 0, this.resetTables()), e = [], t = 0; t < this.fragmentedTracks.length; t++) {\n\t\tvar s = new BoxParser.moovBox;\n\t\ts.mvhd = this.moov.mvhd,\n\t\ts.boxes.push(s.mvhd),\n\t\ti = this.getTrackById(this.fragmentedTracks[t].id),\n\t\ts.boxes.push(i),\n\t\ts.traks.push(i),\n\t\t(r = {}).id = i.tkhd.track_id,\n\t\tr.user = this.fragmentedTracks[t].user,\n\t\tr.buffer = ISOFile.writeInitializationSegment(this.ftyp, s, this.moov.mvex && this.moov.mvex.mehd ? this.moov.mvex.mehd.fragment_duration: void 0, 0 < this.moov.traks[t].samples.length ? this.moov.traks[t].samples[0].duration: 0),\n\t\te.push(r)\n\t}\n\treturn e\n},\nBoxParser.Box.prototype.printHeader = function(t) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tt.log(t.indent + "size:" + this.size),\n\tt.log(t.indent + "type:" + this.type)\n},\nBoxParser.FullBox.prototype.printHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "version:" + this.version),\n\tt.log(t.indent + "flags:" + this.flags)\n},\nBoxParser.Box.prototype.print = function(t) {\n\tthis.printHeader(t)\n},\nBoxParser.ContainerBox.prototype.print = function(t) {\n\tthis.printHeader(t);\n\tfor (var e, i = 0; i < this.boxes.length; i++) this.boxes[i] && (e = t.indent, t.indent += " ", this.boxes[i].print(t), t.indent = e)\n},\nISOFile.prototype.print = function(t) {\n\tt.indent = "";\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && this.boxes[e].print(t)\n},\nBoxParser.mvhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "timescale: " + this.timescale),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "rate: " + this.rate),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "next_track_id: " + this.next_track_id)\n},\nBoxParser.tkhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "track_id: " + this.track_id),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "layer: " + this.layer),\n\tt.log(t.indent + "alternate_group: " + this.alternate_group),\n\tt.log(t.indent + "width: " + this.width),\n\tt.log(t.indent + "height: " + this.height)\n};\nvar MP4Box = {\n\tcreateFile: function(t, e) {\n\t\tt = void 0 === t || t,\n\t\te = new ISOFile(e);\n\t\treturn e.discardMdatData = !t,\n\t\te\n\t}\n};\n"undefined" != typeof exports && (exports.createFile = MP4Box.createFile);\n',workerLogic="\n// 显式将变量绑定到self上,确保全局可访问\nself.abortFlag = false;\nself.mp4boxfile = null;\nself.videoDecoder = null;\nself.samplesInRange = [];\nself.videoTrack = null;\nself.arrayBuffer = null;\n\nonmessage = function(e) {\n if (e.data.type === 'decode') {\n self.abortFlag = false;\n decodeFile(e.data.file, e.data.start, e.data.end, e.data.hardwareAcceleration);\n } else if (e.data.type === 'abort') {\n self.abortFlag = true;\n // 主动销毁所有大对象和引用\n if (self.videoDecoder) {\n try {\n self.videoDecoder.flush();\n self.videoDecoder.reset();\n self.videoDecoder.close();\n } catch (err) {}\n self.videoDecoder = null;\n }\n if (self.mp4boxfile) {\n try { self.mp4boxfile.flush(); } catch (err) {}\n self.mp4boxfile = null;\n }\n self.samplesInRange = [];\n self.videoTrack = null;\n self.arrayBuffer = null;\n // 关闭worker\n self.close();\n }\n};\n\nfunction decodeFile(file, startFrame, endFrame, hardwareAcceleration) {\n self.arrayBuffer = file.data;\n self.mp4boxfile = MP4Box.createFile();\n self.videoTrack = null;\n let nbSampleTotal = 0;\n self.samplesInRange = [];\n self.videoDecoder = null;\n let frameIndex = 0;\n let totalFrames = 0;\n self.mp4boxfile.onReady = function(info) {\n self.videoTrack = info.videoTracks[0];\n nbSampleTotal = self.videoTrack.nb_samples;\n self.mp4boxfile.setExtractionOptions(self.videoTrack.id, null, {\n nbSamples: nbSampleTotal,\n rapAlignement: true\n });\n self.mp4boxfile.start();\n };\n self.mp4boxfile.onSamples = async function(trackId, ref, samples) {\n if (self.abortFlag) return; // 确保使用self访问\n // 自动对齐到区间内第一个关键帧\n let startIdx = Math.min(0, startFrame); // 修复Math.min, 因为仅有第一帧是关键帧\n let endIdx = Math.min(samples.length - 1, endFrame);\n while (startIdx <= endIdx && !samples[startIdx].is_sync) {\n startIdx++;\n }\n if (startIdx > endIdx) {\n // 区间内没有关键帧,直接done\n postMessage({ type: 'done' });\n return;\n }\n self.samplesInRange = samples.slice(0, endIdx + 1);\n totalFrames = self.samplesInRange.length;\n if (!self.videoDecoder) {\n self.videoDecoder = new VideoDecoder({\n output: handleFrame,\n error: err => {\n postMessage({ type: 'error', error: err.message })\n }\n });\n const entry = self.mp4boxfile.moov.traks[0].mdia.minf.stbl.stsd.entries[0];\n const box = entry.avcC ?? entry.hvcC ?? entry.vpcC;\n let description = undefined;\n if (box) {\n const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);\n box.write(stream);\n description = new Uint8Array(stream.buffer.slice(8));\n }\n\t\tconst isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);\n \tconst userAgent = (navigator.userAgent || \"\").toLowerCase();\n\t const isAndroid = /android/.test(userAgent) || /openharmony|arkweb/.test(userAgent);\n\t\tconst defaultConfig = {\n\t\t\tcodec: self.videoTrack.codec,\n\t\t\tcodedWidth: self.videoTrack.track_width,\n\t\t\tcodedHeight: self.videoTrack.track_height,\n\t\t\tdescription,\n\t\t}\n\t\t// Android 系统下,默认配置为 prefer-software 以避免硬件解码问题\n\t\tlet config = isAndroid ? { ...defaultConfig, hardwareAcceleration: 'prefer-software' } : hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t\t...defaultConfig,\n\t\t\thardwareAcceleration: hardwareAcceleration,\n\t\t}\n\t\t// let config = hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t// \t...defaultConfig,\n\t\t// \thardwareAcceleration: hardwareAcceleration,\n\t\t// }\n\t\tconst configSupport = (await VideoDecoder.isConfigSupported(config));\n\t\tconst isConfigSupported = configSupport.supported;\n\t\tpostMessage({ type: 'configSupport', configSupport: { config, configSupport}});\n\t\tlet isDefaultConfigSupported = false;\n\t\tif(!isConfigSupported) {\n\t\t\tconst defaultConfigSupport = await VideoDecoder.isConfigSupported(defaultConfig);\n\t\t\tpostMessage({ type: 'configSupport', configSupport: { defaultConfig, configSupport: defaultConfigSupport}});\n\t\t\tisDefaultConfigSupported = defaultConfigSupport.supported;\n\t\t}\n\t\tif(isConfigSupported) {\n\t\t\tself.videoDecoder.configure(config);\n\t\t} else if(isDefaultConfigSupported) {\n\t\t\tself.videoDecoder.configure(defaultConfig);\n\t\t} else {\n\t\t\tpostMessage({ type: 'error', error: '不支持的视频解码配置' });\n\t\t}\n }\n for (let i = 0; i < self.samplesInRange.length; i++) {\n if (self.abortFlag) break; // 确保使用self访问\n \n const sample = self.samplesInRange[i];\n const chunk = new EncodedVideoChunk({\n type: sample.is_sync ? 'key' : 'delta',\n timestamp: sample.cts,\n duration: sample.duration,\n data: sample.data\n });\n self.videoDecoder.decode(chunk);\n }\n self.videoDecoder.flush().then(() => {\n postMessage({ type: 'done' });\n });\n };\n function handleFrame(videoFrame) {\n if (self.abortFlag) { // 确保使用self访问\n videoFrame.close();\n return;\n }\n postMessage({ type: 'frame', frame: videoFrame, index: frameIndex++, total: totalFrames }, [videoFrame]);\n }\n self.arrayBuffer.fileStart = 0;\n self.mp4boxfile.appendBuffer(self.arrayBuffer);\n self.mp4boxfile.flush();\n}\n",fullWorkerScript=`\ntry {\n ${mp4boxSource}\n self.MP4Box = MP4Box;\n ${workerLogic}\n} catch (error) {\n console.error('Worker初始化失败:', error);\n throw error;\n}\n`,blob=new Blob([fullWorkerScript],{type:"application/javascript"}),workerURL=URL.createObjectURL(blob);function base64ToUint8Array(t){if(!t||""===t.trim())return new Uint8Array(0);const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function twoByteToInt16(t,e){const n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){const e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];const n=e.length/2,i=new ArrayBuffer(4*n),r=new Float32Array(i);for(let t=0;t<n;t++){const n=2*t,i=twoByteToInt16(e[n],e[n+1]);r[t]=i/32767}return Array.from(r)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=new Float32Array(e);return Array.from(n)}class ParallelDecoder{constructor(t){this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.currentDecodedFrameIndex=null,this.abortAfterFrame=null,this.cacheVideoCount=5,this.maxVideoCount=2,this.hardwareAcceleration="default",this.MAX_LOAD_VIDEO_TIMEOUT_MS=2e3,this._offlineLastFrame=0,this._offlineIdle=[],this._offlineIdleIndex=0,this.firstDecodeFrame=!0,this.tasks=new Map,this.queue=[],this.maxParallel=1,this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.resourceManager=t.resourceManager,this.onFrame=()=>{},this.onDone=()=>{},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}getRandomTaskId(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)}decode(t,e){if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=(t,n,i)=>{this.currentDecodedFrameIndex=t.startFrameIndex+i,this._handlePendingAbort(t,i),e(t,n,i)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)}clearOldQueue(t){this.queue=this.queue.filter(e=>e.sf>=t)}updateQueue(t){if(this.abortAfterFrame=null,0===this.queue.length)return void this.queue.push(...t);const e=this.queue[0].sf,n=t[0].sf;if(n>=this.queue[this.queue.length-1].ef)this.queue.push(...t);else if(n<e){if(null!==this.currentDecodedFrameIndex&&n>this.currentDecodedFrameIndex+1){this.abortAfterFrame=n-1;const e=this.queue.filter(t=>t.ef<n);return void(this.queue=e.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(n===e)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{const e=this.queue.findIndex(t=>t.sf>=n);-1!==e&&(this.queue.length=e),this.abortAfterFrame=n-1,this.queue.push(...t)}}_isIOS(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)}getQueue(){return this.queue.map(t=>_extends({},t,{x_offset:[]}))}timeoutPromise(t,e="请求超时"){return new Promise((e,n)=>{setTimeout(()=>{n()},t)})}async loadVideoWithTimeout(t){try{return await Promise.race([this.resourceManager.loadVideo(t),this.timeoutPromise(this.MAX_LOAD_VIDEO_TIMEOUT_MS,`视频 ${t} 加载超时(${this.MAX_LOAD_VIDEO_TIMEOUT_MS}ms)`)])}catch(t){return null}}async _tryStartNext(){var t;let e;if(e=(null==(t=this.queue)?void 0:t.some(t=>null!==this.currentDecodedFrameIndex&&t.sf<this.currentDecodedFrameIndex))?this._isIOS()?this.maxVideoCount:this.maxVideoCount+1:this._isIOS()?1:this.maxVideoCount,!(this.dataCacheQueue.getBodyVideoNameListLength()>=e)&&this.currentParallel<this.maxParallel&&this.queue.length>0){var n,i;const t=this.queue.shift();if(this.saveAndDownload.appendMultipleToArray("videoData",[_extends({},t,{x_offset:parseUint8ToFloat32(t.x_offset)||[]})]),this._cleanupOldWorkers(null!=(n=null!=(i=t.body_id)?i:t.id)?n:0),this.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,t),!t.n)return this.currentParallel--,this._tryStartNext(),void this.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:`body数据无Name: ${JSON.stringify(t)}`});const e=await this.loadVideoWithTimeout(t.n);if(!e)return this.currentParallel--,void this._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,t),window.performanceTracker.markStart(performanceConstant.decode_video,t),window.performanceTracker.markStart(performanceConstant.first_decode_video,t),this._startWorker({name:t.n,id:t.id,frameState:t.s,start:t.asf,end:t.aef,hfd:t.hfd,data:e,startFrameIndex:t.sf,endFrameIndex:t.ef,body_id:t.body_id,x_offset:parseUint8ToFloat32(t.x_offset)||[]})}}_startWorker(t){var e,n;const i=this.currentTaskId;let r;try{r=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}const s=`${null!=(e=null!=(n=t.body_id)?n:t.id)?e:0}_${t.name}`,a=t.data,o=new ArrayBuffer(a.byteLength);new Uint8Array(o).set(new Uint8Array(a)),r.addEventListener("error",t=>{i===this.currentTaskId&&this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});const l=e=>{if(i===this.currentTaskId)if("frame"===e.data.type)if(this.firstDecodeFrame&&(this.firstDecodeFrame=!1,window.performanceTracker.markEnd(performanceConstant.first_decode_video,t)),e.data.index<t.start||e.data.index>t.end)e.data.frame.close();else{var n;this.cacheVideo(),this.onFrame(t,e.data.frame,e.data.index);const i=null!=(n=this.bodyFrameCountMap.get(t.name))?n:0;this.bodyFrameCountMap.set(t.name,i+1),this.abortAfterFrame&&e.data.index+t.startFrameIndex>=this.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",this.abortAfterFrame,t),this.abortOne(s),this.abortAfterFrame=null,this._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var a;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(a=this.bodyFrameCountMap.get(t.name))?a:0)<t.end-t.start-1&&this.bodyFrameCountMap.delete(t.name);const e=this.tasks.get(s);e&&(e.status="done",e.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),r.removeEventListener("message",l),r.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1),this._tryStartNext()}else if("error"===e.data.type){var o;const n=null!=(o=e.data.error)?o:"",i=n.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;this.reportMessage({code:i,message:n||"视频解码错误",e:{fileName:t.name,error:n}});const a=this.tasks.get(s);a&&(a.status="error",a.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),r.removeEventListener("message",l),r.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1)}};r.addEventListener("message",l),this.tasks.set(s,{worker:r,status:"decoding",onMessage:l,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),r.postMessage({type:"decode",file:{data:o},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:i},[o])}cacheVideo(){const t=this.queue.slice(0,this.cacheVideoCount);for(const e of t)this.resourceManager.preloadVideo(e.n)}abort(){this.tasks.forEach(({worker:t,status:e,onMessage:n})=>{"decoding"===e&&(t.postMessage({type:"abort"}),n&&t.removeEventListener("message",n),t.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null}abortOne(t){const e=this.tasks.get(t);e&&"decoding"===e.status&&(null==e||e.worker.postMessage({type:"abort"}),null!=e&&e.onMessage&&e.worker.removeEventListener("message",e.onMessage),null==e||e.worker.terminate(),this.tasks.delete(t),this.currentParallel--,0===this.currentParallel&&0===this.queue.length&&(this._locked=!1))}destroy(){this.abort(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.abortAfterFrame=null,this.currentDecodedFrameIndex=null,this.firstDecodeFrame=!0}_handlePendingAbort(t,e){this.pendingAbort&&null!==this.abortAfterEf&&t.startFrameIndex+e>=this.abortAfterEf&&(this.abort(),this.queue=this.pendingNewQueue,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null)}_cleanupOldWorkers(t){for(const[e,n]of this.tasks){const[i]=e.split("_"),r=parseInt(i,10);!isNaN(r)&&r<t&&(n.worker.postMessage({type:"abort"}),n.onMessage&&n.worker.removeEventListener("message",n.onMessage),n.worker.terminate(),this.tasks.delete(e))}}syncDecode(t){const e=this.queue.filter(e=>e.ef>t);0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())}_reload(){this._offlineLastFrame=0,this.queue=[]}_offLineMode(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()}_offlineRun(){const t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0}_putOfflineBodyData(t){const e={id:-1,n:t.n,s:"idle",hfd:!1,body_id:-1,asf:t.asf,aef:t.aef,sf:this._offlineLastFrame,ef:this._offlineLastFrame+(t.aef-t.asf),x_offset:new Uint8Array};this.queue.push(e),this._offlineLastFrame=e.ef}}class FrameAnimationController{constructor({defaultSpeed:t=1,frameRate:e=24,frameCallback:n}={}){this.startTime=null,this.currentFrame=1,this.speed=t,this.frameCallback=n||null,this.frameRate=e,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}get playing(){return this.isPlaying}play(){this.isPlaying||(this.isPlaying=!0,window.avatarSDKLogger.log("开始时间",this.startTime),null===this.startTime&&(window.avatarSDKLogger.log("当前时间",performance.now()),this.startTime=performance.now(),this.startTimeFromDate=Date.now()),this.animationId=requestAnimationFrame(this._animate.bind(this)))}pause(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)}reset(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null}setSpeed(t){this.speed=t}gotoFrame(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()}nextFrame(){this.currentFrame++,this._updateFrame()}prevFrame(){this.gotoFrame(this.currentFrame-1)}destroy(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1}_animate(t){let e=performance.now();if(Math.abs(t-e)<100&&(e=t),this.currentFrame<50&&window.avatarSDKLogger.log("animate时间",t,"开始时间",this.startTime,"performance",performance.now()),this.isPlaying){if(null!==this.startTime){const t=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;t!==this.currentFrame&&(this.currentFrame=t,this._updateFrame());const n=Date.now()-this.startTimeFromDate,i=Math.floor(Math.floor(n/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=i}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}}_updateFrame(){let t=null;this.frameCallback&&(this.currentFrameFromDate!==this.currentFrame&&null!==this.currentFrameFromDate&&(t={key:"frame_number_error",Date帧号:this.currentFrameFromDate,performance帧号:this.currentFrame,开始时间:this.startTime,开始时间日期:this.startTimeFromDate,当前时间:Date.now(),"performance.now()":performance.now()}),this.frameCallback(this.currentFrame,t))}getCurrentFrame(){if(null!==this.startTime){const t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame}updateStartTime(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)}}const captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t=navigator){const e=getAudioSession(t);if(!e)return!1;const n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e=navigator){const n=getAudioSession(e);if(!n)return()=>{};let i=playbackSessionRestoredListeners.get(n);return i||(i=new Set,playbackSessionRestoredListeners.set(n,i)),i.add(t),()=>{var e,r;null==(e=i)||e.delete(t),0===(null==(r=i)?void 0:r.size)&&playbackSessionRestoredListeners.delete(n)}}function getAudioSession(t){return t.audioSession}function setAudioSessionType(t,e){try{return t.type=e,t.type===e}catch(t){return!1}}const pcm_audio_script="// pcm-audio-processor.js - 运行在音频线程的Worklet处理器\nclass PCMAudioProcessor extends AudioWorkletProcessor {\n // 音量配置(与主线程保持一致)\n static get parameterDescriptors() {\n return [\n {\n name: 'volume',\n defaultValue: 1.0,\n minValue: 0.0,\n maxValue: 1.0,\n automationRate: 'a-rate' // 支持音频速率自动化\n }\n ];\n }\n\n constructor() {\n super();\n this.config = {\n sampleRate: 24000, // 固定24kHz采样率\n bytesPerSample: 2, // S16LE=2字节/采样点\n };\n this.pcmCache = new Uint8Array(0); // Worklet内的PCM缓存\n this.isActive = false; // 播放音频状态(控制是否生成声音)\n this.isDestroyed = false;\n this.fadeState = {\n // 淡入淡出状态(避免片段切换爆音)\n phase: 'idle', // idle/fadeIn/fadeOut/steady\n currentGain: 0,\n fadeTime: 0.01, // 淡入淡出时间(秒,建议最小0.01s避免爆音)\n fadeSamples: Math.floor(0.01 * 24000), // 淡入淡出样本数(24000Hz下为240样本)\n };\n this.currentSegment = null; // 当前处理的音频段(float32数组)\n this.segmentOffset = 0; // 当前音频段的播放偏移量\n \n // 监听主线程消息(接收PCM数据、状态控制等)\n this.port.onmessage = (e) => this.handleMainThreadMessage(e.data);\n \n // 初始化淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n\n /**\n * 处理主线程发来的消息(PCM数据/状态控制等)\n * @param {Object} data - 消息数据\n * @param {string} data.type - 消息类型:'pcm'/'start'/'pause'/'stop'/'config'/'destroy'/'volume'\n * @param {Uint8Array} [data.pcmData] - PCM数据(仅type='pcm'时存在)\n * @param {Object} [data.config] - 配置更新(仅type='config'时存在)\n * @param {number} [data.volume] - 音量值(仅type='volume'时存在)\n */\n handleMainThreadMessage(data) {\n switch (data.type) {\n // 接收主线程下发的PCM流数据\n case 'pcm':\n if (data.pcmData instanceof Uint8Array && data.pcmData.length > 0) {\n // 确保PCM数据字节数为2的整数倍(S16LE要求)\n const validLength = data.pcmData.length - (data.pcmData.length % this.config.bytesPerSample);\n if (validLength <= 0) break;\n \n // 合并到Worklet缓存\n const newCache = new Uint8Array(this.pcmCache.length + validLength);\n newCache.set(this.pcmCache, 0);\n newCache.set(data.pcmData.subarray(0, validLength), this.pcmCache.length);\n this.pcmCache = newCache;\n \n // 向主线程发送缓存状态\n this.port.postMessage({\n type: 'cacheStatus',\n size: this.pcmCache.length,\n sampleCount: this.pcmCache.length / this.config.bytesPerSample\n });\n }\n break;\n\n // 启动播放(继续音频生成)\n case 'start':\n this.isActive = true;\n break;\n\n // 暂停播放(停止音频生成,保留缓存)\n case 'pause':\n this.isActive = false;\n this.resetSegmentState();\n break;\n\n // 停止播放(清空缓存+重置状态)\n case 'stop':\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n break;\n\n // 更新配置(如采样率/淡入淡出时间)\n case 'config':\n if (data.config.sampleRate) {\n this.config.sampleRate = data.config.sampleRate;\n // 重新计算淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n if (data.config.fadeTime) {\n this.fadeState.fadeTime = data.config.fadeTime;\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n break;\n\n // 单独更新音量(可选,也可通过参数自动化控制)\n case 'volume':\n this.volume = Number(data.volume);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncVolume',\n volume: this.volume\n });\n break;\n\n // 单独更新播放速率(可选,也可通过参数自动化控制)\n case 'speed':\n this.speed = Number(data.speed);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncSpeed',\n speed: this.speed\n });\n break;\n\n // 销毁处理器\n case 'destroy':\n this.isDestroyed = true;\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n this.port.postMessage({ type: 'destroyConfirmed' });\n break;\n \n default:\n console.warn('[PCMAudioProcessor] 未知消息类型:', data.type);\n }\n }\n\n /**\n * 重置当前音频段状态(暂停/停止时调用)\n */\n resetSegmentState() {\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n this.fadeState.currentGain = 0;\n }\n\n /**\n * S16LE Uint8Array 转 Float32Array(-1~1范围)\n * @param {Uint8Array} pcmData - PCM数据\n * @returns {Float32Array} 转换后的音频样本\n */\n pcmToFloat32(pcmData) {\n const sampleCount = pcmData.length / this.config.bytesPerSample;\n const floatData = new Float32Array(sampleCount);\n const dataView = new DataView(pcmData.buffer);\n\n for (let i = 0; i < sampleCount; i++) {\n // S16LE格式:小端序解析,范围-32768~32767 归一化到-1~1\n floatData[i] = dataView.getInt16(i * this.config.bytesPerSample, true) / 32768;\n }\n return floatData;\n }\n\n /**\n * 计算当前样本的增益(淡入淡出)\n * @param {number} segmentLength - 当前音频段的总样本数\n * @returns {number} 增益值(0~1)\n */\n calculateGain(segmentLength) {\n const { phase, fadeSamples } = this.fadeState;\n const { segmentOffset } = this;\n\n // 边界保护:防止无效值导致的NaN\n if (typeof segmentOffset !== 'number' || typeof segmentLength !== 'number' || segmentLength <= 0) {\n return 0;\n }\n\n switch (phase) {\n // 淡入阶段:从0线性增加到1\n case 'fadeIn':\n if (segmentOffset >= fadeSamples) {\n this.fadeState.phase = 'steady';\n return 1;\n }\n return segmentOffset / fadeSamples;\n\n // 稳定阶段:增益保持1\n case 'steady':\n // 检测是否进入淡出阶段(接近段尾)\n if (segmentOffset >= segmentLength - fadeSamples) {\n this.fadeState.phase = 'fadeOut';\n }\n return 1;\n\n // 淡出阶段:从1线性降低到0.0001(避免分音)\n case 'fadeOut':\n const fadeStart = Math.max(segmentLength - fadeSamples, 0);\n const fadeProgress = (segmentOffset - fadeStart) / fadeSamples;\n return Math.max(1 - fadeProgress, 0.0001);\n\n // 空闲阶段:增益0\n case 'idle':\n default:\n return 0;\n }\n }\n\n /**\n * AudioWorklet核心方法:实时生成音频样本(音频线程调用)\n * @param {Float32Array[][]} inputs - 输入样本\n * @param {Float32Array[][]} outputs - 输出样本(单声道)\n * @param {Object} parameters - 音频参数\n * @returns {boolean} 是否继续运行\n */\n process(inputs, outputs, parameters) {\n // 销毁状态:终止处理\n if (this.isDestroyed) {\n if (outputs.length > 0 && outputs[0].length > 0) {\n outputs[0][0].fill(0);\n }\n return false;\n }\n\n // 未激活或无输出:返回静音\n if (!this.isActive || outputs.length === 0 || outputs[0].length === 0) {\n outputs[0][0].fill(0);\n return true;\n }\n\n const outputBuffer = outputs[0][0];\n const bufferLength = outputBuffer.length;\n // 获取音量参数(支持自动化)\n const volume = parameters.volume.length > 1 \n ? parameters.volume // 自动化模式:每个样本点可能有不同值\n : parameters.volume[0]; // 控制模式:整个缓冲区使用相同值\n\n // 生成输出样本\n for (let i = 0; i < bufferLength; i++) {\n // 如当前无音频段且缓存有数据,创建新段\n if (!this.currentSegment && this.pcmCache.length > 0) {\n // 使用缓存中的所有数据创建新段\n this.currentSegment = this.pcmToFloat32(this.pcmCache);\n // 清空缓存(已处理)\n this.pcmCache = new Uint8Array(0);\n this.segmentOffset = 0;\n // 根据前一段状态决定是否淡入\n this.fadeState.phase = this.fadeState.phase === 'fadeOut' ? 'steady' : 'fadeIn';\n }\n\n // 生成当前样本\n let sample = 0;\n if (this.currentSegment) {\n const segmentLength = this.currentSegment.length;\n // 确保偏移量有效\n if (this.segmentOffset < segmentLength) {\n const gain = this.calculateGain(segmentLength);\n // 应用淡入淡出增益和音量控制\n sample = this.currentSegment[this.segmentOffset] * gain * volume;\n this.segmentOffset++;\n } else {\n // 当前段处理完毕,重置\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n }\n }\n\n outputBuffer[i] = sample;\n }\n\n return true;\n }\n}\n\n// 注册Worklet处理器\nregisterProcessor('pcm-audio-processor', PCMAudioProcessor);\n",pcm_capture_script="// pcm-capture-processor.js - 运行在音频线程的捕获处理器\nclass PCMCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.inputSampleRate = 24000; // PCM 播放器采样率\n this.outputSampleRate = 16000; // Opus 编码要求采样率\n this.bufferSize = 2400; // 100ms @ 24kHz\n this.buffer = new Float32Array(this.bufferSize);\n this.bufferIndex = 0;\n\n // 监听主线程的 reset 消息,清空内部缓冲区(打断/会话切换时使用)\n this.port.onmessage = (e) => {\n if (e.data && e.data.type === 'reset') {\n this.bufferIndex = 0;\n this.buffer.fill(0);\n }\n };\n }\n\n process(inputs) {\n const input = inputs[0];\n if (!input || !input[0] || input[0].length === 0) return true;\n\n const chunk = input[0];\n for (let i = 0; i < chunk.length; i++) {\n this.buffer[this.bufferIndex++] = chunk[i];\n\n if (this.bufferIndex >= this.bufferSize) {\n // 重采样 24kHz → 16kHz\n const resampled = this.resample(this.buffer);\n // Float32 → S16LE\n const pcmBuffer = this.float32ToS16LE(resampled);\n // 静音检测\n const hasAudio = this.detectAudio(this.buffer);\n // 回传主线程(Transferable,避免拷贝)\n this.port.postMessage(\n { pcmData: pcmBuffer.buffer, hasAudio: hasAudio },\n [pcmBuffer.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n\n // 线性插值重采样 24kHz → 16kHz (3:2 比率)\n resample(input) {\n const ratio = this.outputSampleRate / this.inputSampleRate; // 2/3\n const outputLength = Math.floor(input.length * ratio); // 1600\n const output = new Float32Array(outputLength);\n for (let i = 0; i < outputLength; i++) {\n const srcIndex = i / ratio;\n const srcIndexFloor = Math.floor(srcIndex);\n const frac = srcIndex - srcIndexFloor;\n const s1 = input[srcIndexFloor] || 0;\n const s2 = input[srcIndexFloor + 1] || 0;\n output[i] = s1 + (s2 - s1) * frac;\n }\n return output;\n }\n\n // Float32 → S16LE Int16Array\n float32ToS16LE(float32) {\n const int16 = new Int16Array(float32.length);\n for (let i = 0; i < float32.length; i++) {\n let s = Math.max(-1, Math.min(1, float32[i]));\n int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n return int16;\n }\n\n // 静音检测\n detectAudio(buffer) {\n for (let i = 0; i < buffer.length; i++) {\n if (Math.abs(buffer[i]) > 0.0001) return true;\n }\n return false;\n }\n}\nregisterProcessor('pcm-capture-processor', PCMCaptureProcessor);\n",workletBlob=new Blob([pcm_audio_script],{type:"application/javascript"}),workletUrl=URL.createObjectURL(workletBlob),captureWorkletBlob=new Blob([pcm_capture_script],{type:"application/javascript"}),captureWorkletUrl=URL.createObjectURL(captureWorkletBlob);class PCMAudioPlayer{constructor(){this.SAMPLE_RATE=24e3,this.FRAME_ALIGNMENT=2e3,this.WORKLET_SCRIPT_URL=workletUrl,this.audioCtx=null,this.audioWorkletNode=null,this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,this.unsubscribePlaybackSessionRestored=null,this.captureWorklet=null,this.captureCallback=null}async init(){if(this.isInitialized)return;configureWebAudioPlaybackSession();const t=window.AudioContext||window.webkitAudioContext;if(!t||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");this.audioCtx=new t({sampleRate:this.SAMPLE_RATE});const e=window.avatarSDKLogger||console;try{await this.audioCtx.audioWorklet.addModule(this.WORKLET_SCRIPT_URL),e.log(`[PCMAudioPlayer] Worklet脚本加载完成: ${this.WORKLET_SCRIPT_URL}`),this.audioWorkletNode=new AudioWorkletNode(this.audioCtx,"pcm-audio-processor"),this.audioWorkletNode.connect(this.audioCtx.destination),e.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),this.audioWorkletNode.port.onmessage=t=>{var n,i,r;switch(t.data.type){case"cacheStatus":e.log(`[PCMAudioPlayer] Worklet缓存状态: ${t.data.size}字节`);break;case"error":e.error("[PCMAudioPlayer] Worklet错误:",t.data.detail);break;case"destroyConfirmed":e.log("[PCMAudioPlayer] Worklet已确认销毁"),null==(n=this.destroyResolve)||n.call(this);break;case"syncVolume":void 0!==(null==(i=this.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("volume"))?void 0:i.value)&&(this.audioWorkletNode.parameters.get("volume").value=t.data.volume);break;case"syncSpeed":void 0!==(null==(r=this.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("speed"))?void 0:r.value)&&(this.audioWorkletNode.parameters.get("speed").value=t.data.speed);break;default:e.log("[PCMAudioPlayer] Worklet消息:",t.data)}},this.isInitialized=!0,this.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(()=>{this.refreshPlaybackRoute()}),e.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")}catch(t){throw e.error("[PCMAudioPlayer] 初始化失败:",t),t}}refreshPlaybackRoute(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;const t=window.avatarSDKLogger||console;try{return this.audioWorkletNode.disconnect(),this.audioWorkletNode.connect(this.audioCtx.destination),this.captureWorklet&&this.audioWorkletNode.connect(this.captureWorklet),"running"!==this.audioCtx.state&&this.audioCtx.resume().catch(e=>{t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}}receivePCMStream(t){const e=window.avatarSDKLogger||console;if(this.isInitialized&&this.audioWorkletNode)if(t instanceof Uint8Array){e.log(`[PCMAudioPlayer] 已下发PCM数据: ${t.length}字节`);try{this.audioWorkletNode.port.postMessage({type:"pcm",pcmData:t},[t.buffer])}catch(t){e.error("[PCMAudioPlayer] 下发PCM数据到Worklet失败:",t)}}else e.error("[PCMAudioPlayer] 输入PCM数据必须是非空的Uint8Array");else e.error("[PCMAudioPlayer] 播放器未初始化,无法接收PCM数据")}async start(){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");const t=window.avatarSDKLogger||console;"running"!==this.audioCtx.state&&(await this.audioCtx.resume(),t.log("[PCMAudioPlayer] AudioContext已恢复运行")),this.audioWorkletNode.port.postMessage({type:"start"}),this.isPlaying=!0,t.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")}pause(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}stop(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}async destroy(){var t;const e=window.avatarSDKLogger||console;null==(t=this.unsubscribePlaybackSessionRestored)||t.call(this),this.unsubscribePlaybackSessionRestored=null,this.detachCapture(),this.isInitialized&&this.audioCtx&&this.audioWorkletNode?(await new Promise(t=>{var n;this.destroyResolve=t,null==(n=this.audioWorkletNode)||n.port.postMessage({type:"destroy"});const i=setTimeout(()=>{var t;e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==(t=this.destroyResolve)||t.call(this)},300);this.audioWorkletNode&&(this.audioWorkletNode.port.onmessage=t=>{var e;"destroyConfirmed"===t.data.type&&(clearTimeout(i),null==(e=this.destroyResolve)||e.call(this))})}),this.audioWorkletNode.disconnect(),this.audioWorkletNode.port.close(),this.audioWorkletNode=null,"closed"!==this.audioCtx.state&&await this.audioCtx.close(),this.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")):e.log("[PCMAudioPlayer] 播放器未初始化或已销毁")}async attachCapture(t){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");if(!this.captureWorklet){this.captureCallback=t;try{var e;await this.audioCtx.audioWorklet.addModule(captureWorkletUrl),this.captureWorklet=new AudioWorkletNode(this.audioCtx,"pcm-capture-processor"),this.audioWorkletNode.connect(this.captureWorklet),this.captureWorklet.port.onmessage=t=>{this.captureCallback&&t.data.pcmData&&this.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(e=window.avatarSDKLogger)||e.log("[PCMAudioPlayer] 捕获节点已挂载")}catch(t){var n;throw null==(n=window.avatarSDKLogger)||n.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t}}}detachCapture(){if(this.captureWorklet){try{var t;this.captureWorklet.port.onmessage=null,null==(t=this.audioWorkletNode)||t.disconnect(this.captureWorklet),this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}this.captureCallback=null}resetCaptureBuffer(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})}getStatus(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}}setVolume(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})}setSpeed(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})}async resume(){const t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(()=>{window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(t=>{window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}}}class MediaSourceAudioPlayer{static getInstance(t){return MediaSourceAudioPlayer.instance||(MediaSourceAudioPlayer.instance=new MediaSourceAudioPlayer(t)),MediaSourceAudioPlayer.instance}constructor(t){this.mediaSource=null,this.audioElement=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.volume=1,this.MIME_TYPE="audio/webm;codecs=opus",this.queue=[],this.isUpdating=!1,this.currentObjectURL=null,this.isDestroyed=!1,this.playbackRate=1,this.firstFrameIndex=-1,this.createAudioElement(t),this.createNewMediaSource()}createAudioElement(t){if(this.audioElement)return;const e=document.getElementById("xmov-avatar-audio");if(e)return void(this.audioElement=e);const n=document.createElement("audio");n.id="xmov-avatar-audio",n.preload="auto",n.style.position="absolute",n.style.width="1px",n.style.height="1px",n.style.opacity="0",n.style.pointerEvents="none",n.style.zIndex="-9999",t.el.appendChild(n),this.audioElement=n}createNewMediaSource(){return new Promise((t,e)=>{try{if(!this.audioElement)return;this.mediaSource=new MediaSource,this.currentObjectURL=URL.createObjectURL(this.mediaSource),this.audioElement.src=this.currentObjectURL,this.mediaSource.addEventListener("sourceopen",()=>{try{if(!this.mediaSource)return;this.sourceBuffer=this.mediaSource.addSourceBuffer(this.MIME_TYPE),this.sourceBuffer.mode="sequence",this.sourceBuffer.addEventListener("updateend",()=>{this.isUpdating=!1,this.processQueue()}),this.isInitialized=!0,t()}catch(t){e(t)}}),this.mediaSource.addEventListener("sourceclose",()=>{this.isInitialized=!1})}catch(t){e(t)}})}async destroyCurrentMediaSource(t){try{this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load())}catch(t){}try{this.currentObjectURL&&(URL.revokeObjectURL(this.currentObjectURL),this.currentObjectURL=null)}catch(t){}this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,await this.createNewMediaSource(),t()}stop(t){this.destroyCurrentMediaSource(t)}async addAudioSegment(t){this.isDestroyed||(this.queue.push({data:t}),this.processQueue())}processQueue(){if(this.isDestroyed)return;if(!this.sourceBuffer||!this.mediaSource)return;if(this.isUpdating||0===this.queue.length)return;if(this.sourceBuffer.updating||"open"!==this.mediaSource.readyState)return;this.isUpdating=!0;const t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}async start(){if(!this.isDestroyed&&this.audioElement&&!this.isPlaying)try{this.audioElement.currentTime=0,this.isPlaying=!0,await this.audioElement.play(),window.avatarSDKLogger.log("mseAudioPlayer开始播放",this.getStats(),Date.now())}catch(t){}}getStats(){var t;return{isPlaying:this.isPlaying,isInitialized:this.isInitialized,queueLength:this.queue.length,bufferedRanges:this.getBufferedRanges(),mediaSourceReadyState:(null==(t=this.mediaSource)?void 0:t.readyState)||"null"}}setSpeed(t){this.setPlaybackRate(t)}getBufferedRanges(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const n=this.sourceBuffer.buffered.start(e).toFixed(2),i=this.sourceBuffer.buffered.end(e).toFixed(2);t.push(`[${n}-${i}]`)}return t.join(", ")}}catch(t){return"-"}return"-"}setVolume(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)}setPlaybackRate(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)}destroy(){if(this.isDestroyed=!0,this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load()),this.currentObjectURL){try{URL.revokeObjectURL(this.currentObjectURL)}catch(t){}this.currentObjectURL=null}this.audioElement&&(this.audioElement.remove(),this.audioElement=null),this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,MediaSourceAudioPlayer.instance=null}}class AudioRender{constructor(t){this.TAG="[AudioRenderer]",this.isPlaying=!1,this.lastFrameIndex=-1,this.audio=null,this.firstFrameIndex=-1,this.valume=1,this.speech_id=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.oldSpeechId=-1,this.mseCacheAudioData=[],this.mseAudioPlayer=null,this.options=t,this.resourceManager=t.resourceManager,this.resourceManager.config.raw_audio?(this.audio=new PCMAudioPlayer,this.audio.init()):this.mseAudioPlayer=MediaSourceAudioPlayer.getInstance(t.sdk)}updateAudioData(t){if(!this.resourceManager.config.raw_audio||t[0].sid===this.oldSpeechId)return;-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);let e=0;for(const i of t){var n;e+=(null==(n=i.ad)?void 0:n.length)||0}const i=new Uint8Array(e);let r=0;for(const e of t)e.ad&&(i.set(new Uint8Array(e.ad),r),r+=e.ad.length);var s,a;-1===this.speech_id?(this.speech_id=t[0].sid,null==(s=this.audio)||s.receivePCMStream(i)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(i)):null==(a=this.audio)||a.receivePCMStream(i)}_updateAudio(t){if(!this.mseAudioPlayer||0===t.length)return;const e=t[0];if(e.sid!==this.oldSpeechId)if(-1!==this.speech_id&&e.sid!==this.speech_id){var n;null==(n=window.avatarSDKLogger)||n.log(this.TAG,`检测到新的 speech_id: ${e.sid}, 当前 WebM 播放 (旧: ${this.speech_id}), 新: ${e.sid}, 缓存数据长度: ${this.mseCacheAudioData.length}`),-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=e.sf);for(const e of t)this.mseCacheAudioData.push({data:e.ad,frameIndex:e.sf,speechId:e.sid})}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(const e of t)if(e.ad){const t=e.ad instanceof ArrayBuffer?e.ad:e.ad.buffer.slice(e.ad.byteOffset,e.ad.byteOffset+e.ad.byteLength);this.mseAudioPlayer.addAudioSegment(t)}}}async render(t){if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",this.firstFrameIndex),-1===this.lastFrameIndex&&(this.lastFrameIndex=t),this.options.sdk.getStatus()!==AvatarStatus.offline){var e;if(t>=this.firstFrameIndex&&-1!=this.firstFrameIndex&&!this.isPlaying&&this.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),this.isPlaying=!0,void(null==(e=this.audio)||e.start());if(this.resourceManager.config.raw_audio||!this.mseAudioPlayer);else if(-1!==this.firstFrameIndex&&t>=this.firstFrameIndex&&!this.mseAudioPlayer.isPlaying&&!this.isPlaying){const e=this.mseAudioPlayer.getStats();if(e.queueLength>0||"-"!==e.bufferedRanges)try{window.avatarSDKLogger.log("开始播放",t),this.isPlaying=!0,await this.mseAudioPlayer.start(),window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")}catch(n){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:n,frameIndex:t,firstFrameIndex:this.firstFrameIndex,queueLength:e.queueLength})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]",`等待更多 WebM 音频数据 (frameIndex: ${t}, queueLength: ${e.queueLength})`)}}}resume(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())}pause(){var t,e;this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(this.speech_id),this.lastFrameIndex=-1,this.firstFrameIndex=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[],this.oldSpeechId=-1,null==(t=this.audio)||t.stop(),null==(e=this.mseAudioPlayer)||e.stop(this.addNewAudioSegment.bind(this)),this.speech_id=-1}stop(t){var e,n,i;if(!(-1!==t&&this.oldSpeechId>=t))if(this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(t),this.firstFrameIndex=-1,null==(e=window.avatarSDKLogger)||e.log(this.TAG,`清除缓存数据 (speech_id: ${this.speech_id}, PCM缓存数据长度: ${this.cacheAudioData.length}, WebM缓存数据长度: ${this.mseCacheAudioData.length})`),this.resourceManager.config.raw_audio?null==(n=this.audio)||n.stop():null==(i=this.mseAudioPlayer)||i.stop(this.addNewAudioSegment.bind(this)),this.oldSpeechId=t,this.speech_id=-1,-1===t)this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[];else if(this.cacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const t of this.cacheAudioData){var r;null==(r=this.audio)||r.receivePCMStream(t)}this.cacheAudioData=[]}}addNewAudioSegment(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const e of this.mseCacheAudioData){var t;e.data&&(null==(t=this.mseAudioPlayer)||t.addAudioSegment(e.data))}this.mseCacheAudioData=[]}}setVolume(t){var e,n;this.valume=t,this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setVolume(t):null==(n=this.mseAudioPlayer)||n.setVolume(t)}setSpeed(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)}getAudioPlayer(){return this.audio}destroy(){var t,e;this.stop(-1),this.cacheAudioData=[],this.mseCacheAudioData=[],null==(t=this.audio)||t.destroy(),null==(e=this.mseAudioPlayer)||e.destroy(),this.mseAudioPlayer=null}}class SaveAndDownload{constructor(t="avatarData.json",e=!1){this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}initDownloadButton(){this.enabled&&(this.downloadButton=document.createElement("a"),this.downloadButton.style.position="absolute",this.downloadButton.style.left="0",this.downloadButton.style.bottom="30px",this.downloadButton.style.background="#4CAF50",this.downloadButton.style.color="white",this.downloadButton.style.fontSize="12px",this.downloadButton.style.padding="10px",this.downloadButton.style.borderRadius="4px",this.downloadButton.style.textDecoration="none",this.downloadButton.style.zIndex="1000",this.downloadButton.style.cursor="pointer",this.downloadButton.innerHTML="下载数据提交开发回放",this.downloadButton.addEventListener("click",()=>{this.download()}),document.body.appendChild(this.downloadButton))}writeFields(t){this.enabled&&Object.assign(this.data,t)}appendMultipleToArray(t,e){this.enabled&&(this.data[t]||(this.data[t]=[]),this.data[t].push(...e))}download(){if(!this.enabled)return;const t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}generateJSONContent(){return JSON.stringify(this.data,null,2)}downloadFile(t,e,n){if(!this.enabled)return;const i=new Blob([t],{type:n}),r=URL.createObjectURL(i);this.downloadButton.href=r,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=r}}class RenderScheduler{constructor(t){this.TAG="[RenderScheduler]",this.currentSpeechId=-1,this.isStartPlay=!1,this.renderState=RenderState.init,this.lastSpeechId=-1,this.enableClientInterrupt=!1,this.audioOnlyMode=!1,this._speedResetTimer=null,this.offsetFrame=0,this.hasSendTimeJson=!1,this.config=t,this.setAudioInfo=t.setAudioInfo,this.setEventData=t.setEventData,this.reportMessage=t.reportMessage,this.sendSdkPoint=t.sendSdkPoint,this.onRenderChange=t.onRenderChange,this.sendMessage=t.sendMessage,this.enableClientInterrupt=t.enableClientInterrupt||!1,this.audioOnlyMode=t.audioOnlyMode||!1,this.saveAndDownload=new SaveAndDownload("avatarData.js",t.enableDebugger),this.resourceManager=t.resourceManager,this.sdk=t.sdkInstance,this.onDownloadProgress=t.onDownloadProgress,this.onFPSUpdate=t.onFPSUpdate,this.dataCacheQueue=new DataCacheQueue,this.decoder=new ParallelDecoder({hardwareAcceleration:t.hardwareAcceleration,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,dataCacheQueue:this.dataCacheQueue,reportMessage:this.reportMessage}),this.avatarRenderer=new AvatarRender({dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,forceSyncDecoder:this.forceSyncDecoder.bind(this),reportMessage:this.reportMessage,sendSdkPoint:this.sendSdkPoint,onDownloadProgress:t=>{this.onDownloadProgress(t)},onStateChange:e=>{t.onStateChange(e)},onRenderChange:e=>{t.onRenderChange(e,this.renderState),this.renderState=e},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:e=>{t.onWalkStateChange(e)},onVoiceStart:(e,n)=>{t.onVoiceStateChange("start",e,n)},onVoiceEnd:(e,n)=>{this.stopAudio(n),t.onVoiceStateChange("end",void 0,e)},onSpeakStateChange:(e,n,i)=>{"speak_start"===e?(this.currentSpeechId=i,this.avatarRenderer.setInterrupt(!1)):"speak_end"===e&&(this.dataCacheQueue.clearSubtitleOn(i),i>=this.currentSpeechId&&this.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(e,n)},sendSdkPoint:(e,n,i)=>{t.sendSdkPoint(e,n,i)}}),this.audioRenderer=new AudioRender({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager}),this.composition=new Composition({container:t.container,avatarRenderer:this.avatarRenderer,restRenderers:[this.uiRenderer],audioRenderer:this.audioRenderer,audioOnlyMode:this.audioOnlyMode,onFPSUpdate:t=>{this.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:(e,n)=>{if(!this.hasSendTimeJson&&n&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",n),this.sendMessage("client_error",n),this.hasSendTimeJson=!0),t.renderFrameCallback(e+=this.offsetFrame),this.isStartPlay&&(this.composition.compose(e),this.decoder._tryStartNext(),t.onFrameDataUpdate)){const n=this.avatarRenderer._getCurrentFrameData(e);t.onFrameDataUpdate({frameIndex:e,body:n.body,face:n.face})}}})}init(){if(this.audioOnlyMode)return;const t=this.resourceManager.getMouthShapeLib();this.saveAndDownload.writeFields({resource_pack:this.resourceManager.resource_pack}),this.avatarRenderer.init({char:t.char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4})}async handleData(t,e){var n,i,r;if(this.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return;const s=this.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:{this.decoder.clearOldQueue(s);const t=s;let n=[...e].filter(e=>e.ef>t);window.avatarSDKLogger.log(n,"mp4List"),n.length>0&&(this.renderState!==RenderState.paused&&s&&s>e[0].sf&&s>10&&this.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:`Error: 身体数据过期 cur:${s}-sf:${e[0].sf}`,e}),this.decoder.decode(n,(t,e,n)=>{var i,r;t.start<=n&&t.end>=n&&(this.dataCacheQueue._updateBodyImageBitmap({frame:e,frameIndex:t.startFrameIndex+n,frameState:t.frameState,id:t.id,body_id:t.body_id,name:t.name,hfd:t.hfd,sf:t.startFrameIndex,offset:(null==t?void 0:t.x_offset[n])||0}),t.endFrameIndex<=t.startFrameIndex+n&&this.decoder.abortOne(`${null!=(i=null!=(r=t.body_id)?r:t.id)?i:0}_${t.name}`))}));break}case EFrameDataType.FACE:this.dataCacheQueue.clearOldFaceData(s);const m=this.handleFaceData(e);m.length>0&&this.saveAndDownload.appendMultipleToArray("faceData",m),this.dataCacheQueue.checkValidData(m,t);let g=[],y=[];for(let t=0;t<m.length;t++){var a;null!=(a=m[t])&&a.face_frame_type?y.push(m[t]):g.push(m[t])}y.length&&this.dataCacheQueue._updateFacial(y),g.length&&this.dataCacheQueue._updateRealFacial(g);break;case EFrameDataType.AUDIO:if(this.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),this.renderState!==RenderState.paused&&s>e[0].sf){const t=s?s-e[0].sf:0;this.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:`Error: 音频数据过期 cur:${s}-sf:${e[0].sf}`,e:{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()}}),this.sendSdkPoint("audio_data_expired",{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()})}const v=1e3/24,{sf:b,ef:S}=e[0],E=S-b;if(E<=0)return;const w=(s||0)-b;if(w>E)return;let x=1;if(w>0&&(x=E/Math.max(E-w,.1)),this._speedResetTimer&&clearTimeout(this._speedResetTimer),x>4)return;this.audioRenderer.setSpeed(x),this._speedResetTimer=setTimeout(()=>{this.audioRenderer.setSpeed(1),this._speedResetTimer=null},E*v/x),this.dataCacheQueue.checkValidData(e,t);const T=e.map(t=>this.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)}));if(T[0].sid<=this.lastSpeechId)return;var o;this.resourceManager.config.raw_audio?(null==(o=window.avatarSDKLogger)||o.log(this.TAG,"processedAudioData[0].sid",T[0].sid,this.currentSpeechId,this.renderState),this.audioRenderer.updateAudioData(T)):this.audioRenderer._updateAudio(T);break;case EFrameDataType.EVENT:this.dataCacheQueue.clearOldEvent(s);const A=e;this.setEventData({sf:A[0].sf,ef:A[0].ef,event:A[0].e});let R=!1,B=null,C=null;for(const t of A){var l;const e=null!=(l=t.e)?l:[];if(e.some(t=>"speak_start"===t.type)&&(R=!0),t.sf<s&&(B||(B=e.find(t=>"speak_start"===t.type)||null),C||(C=e.find(t=>"voice_start"===t.type)||null),B&&C))break}if(R&&this.audioRenderer.isPlaying){var h;this.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});const t=A.flatMap(t=>{var e;return null!=(e=t.e)?e:[]}).find(t=>"speak_start"===t.type),e=null!=(h=null==t?void 0:t.speech_id)?h:0,n=this.audioRenderer.speech_id;var d,c;-1!==n&&n<e&&(this.interrupt("new_speak_start",n),-1!==this.audioRenderer.speech_id&&this.audioRenderer.pause()),t&&(this.currentSpeechId=null!=(d=t.speech_id)?d:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=(c=t.speech_id)?c:0)}if(B){const{speech_id:t,client_speak_id:e}=B;this.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),this.currentSpeechId=null!=t?t:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=t?t:0,this.config.onSpeakStateChange("speak_start",null!=e?e:0)}if(C){var u,f;this.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});const t=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.config.onVoiceStateChange("start",t,null!=(u=null==(f=C)?void 0:f.client_speak_id)?u:"")}const k=A.filter(t=>-1===t.sf&&-1===t.ef);for(const t of k)for(let e=0;e<t.e.length;e++){const n=t.e[e];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(n);else if(WidgetDefaultRenderer.PROXY_WIDGET){var p,_;null==(p=WidgetDefaultRenderer.PROXY_WIDGET)||null==(_=p[n.type])||_.call(p,n)}}const I=A.filter(t=>-1!==t.sf);this.dataCacheQueue._updateUiEvent(I);break;case EFrameDataType.SYNC_FRAME:const P=e;if(null!=(n=this.sdk.getOptions().config)&&n.replay||(null==P?void 0:P.source)!==FRAME_SOURCE_SOURCE)return;const D=Date.now()/1e3,U=null!=(i=P.client_time)?i:0,O=((null!=(r=P.server_client_frame)?r:0)+(D-U)/2*24).toFixed(0);this.offsetFrame+=Number(O)-Number(null!=s?s:0);break;default:this.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}}setOffsetFrame(t){this.offsetFrame+=t}setVolume(t){this.audioRenderer.setVolume(t)}runStartFrameIndex(){var t;null==(t=this.frameAnimationController)||t.play()}stateChangeHandle(t){this.dataCacheQueue.currentPlayState=t}stopAudio(t){this.audioRenderer.stop(t)}render(){if(this.audioOnlyMode)return this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState),void this.onDownloadProgress(100);this.avatarRenderer.createPipeline(),this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState)}stop(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()}pauseRender(){var t,e;this.renderState!==RenderState.paused&&(null==(t=this.frameAnimationController)||t.pause(),this.decoder.abort(),this.audioRenderer.stop(-1),this.dataCacheQueue.clearAllFaceData(),this.renderState=RenderState.paused,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG,`渲染已暂停(已清空表情数据,等待恢复): ${this.renderState}`))}resumeRender(){var t,e;this.renderState===RenderState.paused&&(this.avatarRenderer.createPipeline(),this.avatarRenderer.resetFaceFrameState(),null==(t=this.frameAnimationController)||t.play(),this.isStartPlay=!0,this.forceSyncDecoder(),this.renderState=RenderState.resumed,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG," 渲染已恢复,状态: this.currentSpeechId==="))}switchInvisibleMode(){var t;if(this.renderState===RenderState.rendering||this.renderState===RenderState.resumed)null==(t=window.avatarSDKLogger)||t.log(this.TAG,"switchInvisibleMode: rendering to paused"),this.pauseRender();else if(this.renderState===RenderState.paused){var e;null==(e=window.avatarSDKLogger)||e.log(this.TAG,"switchInvisibleMode: paused to rendering"),this.resumeRender()}else{var n;null==(n=window.avatarSDKLogger)||n.warn(this.TAG,`渲染状态为 ${this.renderState},无法切换隐身模式`)}}getRenderState(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,`getRenderState: ${this.renderState}`),this.renderState}destroy(){var t;this.isStartPlay=!1,this.hasSendTimeJson=!1,this.offsetFrame=0,this._speedResetTimer=null,null==(t=this.frameAnimationController)||t.destroy(),this.frameAnimationController=void 0,this.dataCacheQueue.destroy(),this.composition.destroy(),this.decoder.destroy()}handleFaceData(t){try{var e;const n=this.resourceManager.resource_pack,i=this.resourceManager.getConfig().framedata_proto_version,r=[...null!=(e=n.blendshape_map)?e:[]];return t.map(t=>{let e=[];const{body_id:n,sf:s,ef:a,s:o,id:l,js:h,bsw:d,ms:c,face_frame_type:u,asf:f,aef:p,n:_,cs:m}=t;let g=[];if((null==r?void 0:r.length)>0){for(let t=0;t<r.length;t++){const n=r[t];if((null==n?void 0:n.length)>0)for(let i=0;i<n.length;i++)e[t]||(e[t]=[]),e[t][i]=d[n[i]]}g=Array.from({length:c.length},i?(t,n)=>{var i,r,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(i=null==(r=c[n])?void 0:r.index)?i:0,texturePCAWeights:null!=(s=null==(a=c[n])?void 0:a.weights)?s:[]}}:(t,n)=>{var i,r,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(i=null==(r=c[n])?void 0:r[0])?i:0,texturePCAWeights:null!=(s=null==(a=c[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:c.length},i?(t,e)=>{var n,i,r,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(i=c[e])?void 0:i.index)?n:0,texturePCAWeights:null!=(r=null==(s=c[e])?void 0:s.weights)?r:[]}}:(t,e)=>{var n,i,r,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(i=c[e])?void 0:i[0])?n:0,texturePCAWeights:null!=(r=null==(s=c[e])?void 0:s[1])?r:[]}});let y=[];return y=h.map(i?t=>formatMJT(t.translate,t.rotate):t=>formatMJT(t[0],t[1])),{body_id:n,frameIndex:s,sf:s,ef:a,asf:f,aef:p,n:_,cs:m,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:y,blendshapeWeights:d}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}}forceSyncDecoder(){const t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)}_reload(){this.decoder._reload()}_getResumeInfo(){const t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)}sendVoiceEnd(){var t,e,n;const i=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:i,ef:i+1,e:[{type:"speak_end",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1},{type:"voice_end",speech_id:null!=(n=this.uiRenderer.lastSpeechId)?n:-1}]}])}markReconnectRecover(){this.audioRenderer.resume(),this.decoder._reload()}_offlineMode(){var t,e;this.dataCacheQueue._clearEvent();const n=null!=(t=this.getCurrentFrameIndex())?t:0;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:n+1,ef:n+2,e:[{type:"subtitle_off",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1}]}]),this.audioRenderer.pause();const i=this.getCurrentFrameIndex();i&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),i),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1}_offlineRun(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()}ttsaStateChangeHandle(t){this.dataCacheQueue.currentTtsaState=t}resume(){this.audioRenderer.resume()}pauseForBackground(){this.audioRenderer.pause()}setAvatarCanvasVisible(t){this.avatarRenderer.setCanvasVisibility(t)}setCharacterCanvasLayout(t){this.avatarRenderer.setCharacterCanvasAnchor(t)}setWalkConfig(t){this.avatarRenderer.setWalkConfig(t)}interrupt(t,e){var n;const i=Date.now(),r=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:r,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(r),this.dataCacheQueue.clearSubtitleOn(r);const s=null!=(n=this.getCurrentFrameIndex())?n:0;return this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:s+1,ef:s+2,e:[{type:"subtitle_off",speech_id:null!=r?r:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(r),this.uiRenderer.setInterrupt(r),Date.now()-i}seekToFrame(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)}getCurrentFrameIndex(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame}getSpeechId(){return this.audioRenderer.speech_id}getAudioRenderer(){return this.audioRenderer}simulateContextLoss(t=5e3,e=!1){this.avatarRenderer.simulateContextLoss(t,e)}getRecoveryStatus(){return this.avatarRenderer.getRecoveryStatus()}async testStagedRecovery(){return this.avatarRenderer.testStagedRecovery()}restartWebGL(){return this.avatarRenderer.restartWebGL()}}const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(t){let e=t.length;for(;--e>=0;)t[e]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);const static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);function StaticTreeDesc(t,e,n,i,r){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=t&&t.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}zero$1(base_dist);const d_code=t=>t<256?_dist_code[t]:_dist_code[256+(t>>>7)],put_short=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},send_bits=(t,e,n)=>{t.bi_valid>Buf_size-n?(t.bi_buf|=e<<t.bi_valid&65535,put_short(t,t.bi_buf),t.bi_buf=e>>Buf_size-t.bi_valid,t.bi_valid+=n-Buf_size):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=n)},send_code=(t,e,n)=>{send_bits(t,n[2*e],n[2*e+1])},bi_reverse=(t,e)=>{let n=0;do{n|=1&t,t>>>=1,n<<=1}while(--e>0);return n>>>1},bi_flush=t=>{16===t.bi_valid?(put_short(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)},gen_bitlen=(t,e)=>{const n=e.dyn_tree,i=e.max_code,r=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,c,u,f,p,_=0;for(u=0;u<=MAX_BITS$1;u++)t.bl_count[u]=0;for(n[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<HEAP_SIZE$1;h++)d=t.heap[h],u=n[2*n[2*d+1]+1]+1,u>l&&(u=l,_++),n[2*d+1]=u,d>i||(t.bl_count[u]++,f=0,d>=o&&(f=a[d-o]),p=n[2*d],t.opt_len+=p*(u+f),s&&(t.static_len+=p*(r[2*d+1]+f)));if(0!==_){do{for(u=l-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[l]--,_-=2}while(_>0);for(u=l;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--h],c>i||(n[2*c+1]!==u&&(t.opt_len+=(u-n[2*c+1])*n[2*c],n[2*c+1]=u),d--)}},gen_codes=(t,e,n)=>{const i=new Array(MAX_BITS$1+1);let r,s,a=0;for(r=1;r<=MAX_BITS$1;r++)a=a+n[r-1]<<1,i[r]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(i[e]++,e))}},tr_static_init=()=>{let t,e,n,i,r;const s=new Array(MAX_BITS$1+1);for(n=0,i=0;i<LENGTH_CODES$1-1;i++)for(base_length[i]=n,t=0;t<1<<extra_lbits[i];t++)_length_code[n++]=i;for(_length_code[n-1]=i,r=0,i=0;i<16;i++)for(base_dist[i]=r,t=0;t<1<<extra_dbits[i];t++)_dist_code[r++]=i;for(r>>=7;i<D_CODES$1;i++)for(base_dist[i]=r<<7,t=0;t<1<<extra_dbits[i]-7;t++)_dist_code[256+r++]=i;for(e=0;e<=MAX_BITS$1;e++)s[e]=0;for(t=0;t<=143;)static_ltree[2*t+1]=8,t++,s[8]++;for(;t<=255;)static_ltree[2*t+1]=9,t++,s[9]++;for(;t<=279;)static_ltree[2*t+1]=7,t++,s[7]++;for(;t<=287;)static_ltree[2*t+1]=8,t++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),t=0;t<D_CODES$1;t++)static_dtree[2*t+1]=5,static_dtree[2*t]=bi_reverse(t,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=t=>{let e;for(e=0;e<L_CODES$1;e++)t.dyn_ltree[2*e]=0;for(e=0;e<D_CODES$1;e++)t.dyn_dtree[2*e]=0;for(e=0;e<BL_CODES$1;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*END_BLOCK]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},bi_windup=t=>{t.bi_valid>8?put_short(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},smaller=(t,e,n,i)=>{const r=2*e,s=2*n;return t[r]<t[s]||t[r]===t[s]&&i[e]<=i[n]},pqdownheap=(t,e,n)=>{const i=t.heap[n];let r=n<<1;for(;r<=t.heap_len&&(r<t.heap_len&&smaller(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!smaller(e,i,t.heap[r],t.depth));)t.heap[n]=t.heap[r],n=r,r<<=1;t.heap[n]=i},compress_block=(t,e,n)=>{let i,r,s,a,o=0;if(0!==t.sym_next)do{i=255&t.pending_buf[t.sym_buf+o++],i+=(255&t.pending_buf[t.sym_buf+o++])<<8,r=t.pending_buf[t.sym_buf+o++],0===i?send_code(t,r,e):(s=_length_code[r],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(r-=base_length[s],send_bits(t,r,a)),i--,s=d_code(i),send_code(t,s,n),a=extra_dbits[s],0!==a&&(i-=base_dist[s],send_bits(t,i,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,i=e.stat_desc.static_tree,r=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,l,h=-1;for(t.heap_len=0,t.heap_max=HEAP_SIZE$1,a=0;a<s;a++)0!==n[2*a]?(t.heap[++t.heap_len]=h=a,t.depth[a]=0):n[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=h<2?++h:0,n[2*l]=1,t.depth[l]=0,t.opt_len--,r&&(t.static_len-=i[2*l+1]);for(e.max_code=h,a=t.heap_len>>1;a>=1;a--)pqdownheap(t,n,a);l=s;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],pqdownheap(t,n,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,n[2*l]=n[2*a]+n[2*o],t.depth[l]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,n[2*a+1]=n[2*o+1]=l,t.heap[1]=l++,pqdownheap(t,n,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],gen_bitlen(t,e),gen_codes(n,h,t.bl_count)},scan_tree=(t,e,n)=>{let i,r,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),e[2*(n+1)+1]=65535,i=0;i<=n;i++)r=a,a=e[2*(i+1)+1],++o<l&&r===a||(o<h?t.bl_tree[2*r]+=o:0!==r?(r!==s&&t.bl_tree[2*r]++,t.bl_tree[2*REP_3_6]++):o<=10?t.bl_tree[2*REPZ_3_10]++:t.bl_tree[2*REPZ_11_138]++,o=0,s=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4))},send_tree=(t,e,n)=>{let i,r,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),i=0;i<=n;i++)if(r=a,a=e[2*(i+1)+1],!(++o<l&&r===a)){if(o<h)do{send_code(t,r,t.bl_tree)}while(0!==--o);else 0!==r?(r!==s&&(send_code(t,r,t.bl_tree),o--),send_code(t,REP_3_6,t.bl_tree),send_bits(t,o-3,2)):o<=10?(send_code(t,REPZ_3_10,t.bl_tree),send_bits(t,o-3,3)):(send_code(t,REPZ_11_138,t.bl_tree),send_bits(t,o-11,7));o=0,s=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4)}},build_bl_tree=t=>{let e;for(scan_tree(t,t.dyn_ltree,t.l_desc.max_code),scan_tree(t,t.dyn_dtree,t.d_desc.max_code),build_tree(t,t.bl_desc),e=BL_CODES$1-1;e>=3&&0===t.bl_tree[2*bl_order[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e},send_all_trees=(t,e,n,i)=>{let r;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,i-4,4),r=0;r<i;r++)send_bits(t,t.bl_tree[2*bl_order[r]+1],3);send_tree(t,t.dyn_ltree,e-1),send_tree(t,t.dyn_dtree,n-1)},detect_data_type=t=>{let e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return Z_BINARY;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return Z_TEXT;for(e=32;e<LITERALS$1;e++)if(0!==t.dyn_ltree[2*e])return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=t=>{static_init_done||(tr_static_init(),static_init_done=!0),t.l_desc=new TreeDesc(t.dyn_ltree,static_l_desc),t.d_desc=new TreeDesc(t.dyn_dtree,static_d_desc),t.bl_desc=new TreeDesc(t.bl_tree,static_bl_desc),t.bi_buf=0,t.bi_valid=0,init_block(t)},_tr_stored_block$1=(t,e,n,i)=>{send_bits(t,(STORED_BLOCK<<1)+(i?1:0),3),bi_windup(t),put_short(t,n),put_short(t,~n),n&&t.pending_buf.set(t.window.subarray(e,e+n),t.pending),t.pending+=n},_tr_align$1=t=>{send_bits(t,STATIC_TREES<<1,3),send_code(t,END_BLOCK,static_ltree),bi_flush(t)},_tr_flush_block$1=(t,e,n,i)=>{let r,s,a=0;t.level>0?(t.strm.data_type===Z_UNKNOWN$1&&(t.strm.data_type=detect_data_type(t)),build_tree(t,t.l_desc),build_tree(t,t.d_desc),a=build_bl_tree(t),r=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=r&&(r=s)):r=s=n+5,n+4<=r&&-1!==e?_tr_stored_block$1(t,e,n,i):t.strategy===Z_FIXED$1||s===r?(send_bits(t,(STATIC_TREES<<1)+(i?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(i?1:0),3),send_all_trees(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),compress_block(t,t.dyn_ltree,t.dyn_dtree)),init_block(t),i&&bi_windup(t)},_tr_tally$1=(t,e,n)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=n,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(_length_code[n]+LITERALS$1+1)]++,t.dyn_dtree[2*d_code(e)]++),t.sym_next===t.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(t,e,n,i)=>{let r=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{r=r+e[i++]|0,s=s+r|0}while(--a);r%=65521,s%=65521}return r|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,i)=>{const r=crcTable,s=i+n;t^=-1;for(let n=i;n<s;n++)t=t>>>8^r[255&(t^e[n])];return-1^t};var crc32_1=crc32,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(t,e)=>(t.msg=messages[e],e),rank=t=>2*t-(t>4?9:0),zero=t=>{let e=t.length;for(;--e>=0;)t[e]=0},slide_hash=t=>{let e,n,i,r=t.w_size;e=t.hash_size,i=e;do{n=t.head[--i],t.head[i]=n>=r?n-r:0}while(--e);e=r,i=e;do{n=t.prev[--i],t.prev[i]=n>=r?n-r:0}while(--e)};let HASH_ZLIB=(t,e,n)=>(e<<t.hash_shift^n)&t.hash_mask,HASH=HASH_ZLIB;const flush_pending=t=>{const e=t.state;let n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+n),t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))},flush_block_only=(t,e)=>{_tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,flush_pending(t.strm)},put_byte=(t,e)=>{t.pending_buf[t.pending++]=e},putShortMSB=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},read_buf=(t,e,n,i)=>{let r=t.avail_in;return r>i&&(r=i),0===r?0:(t.avail_in-=r,e.set(t.input.subarray(t.next_in,t.next_in+r),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,r,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,r,n)),t.next_in+=r,t.total_in+=r,r)},longest_match=(t,e)=>{let n,i,r=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-MIN_LOOKAHEAD?t.strstart-(t.w_size-MIN_LOOKAHEAD):0,h=t.window,d=t.w_mask,c=t.prev,u=t.strstart+MAX_MATCH;let f=h[s+a-1],p=h[s+a];t.prev_length>=t.good_match&&(r>>=2),o>t.lookahead&&(o=t.lookahead);do{if(n=e,h[n+a]===p&&h[n+a-1]===f&&h[n]===h[s]&&h[++n]===h[s+1]){s+=2,n++;do{}while(h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&s<u);if(i=MAX_MATCH-(u-s),s=u-MAX_MATCH,i>a){if(t.match_start=e,a=i,i>=o)break;f=h[s+a-1],p=h[s+a]}}}while((e=c[e&d])>l&&0!==--r);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,i,r;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),i+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=HASH(t,t.ins_h,t.window[r+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[r+MIN_MATCH-1]),t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,i,r,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,a=0,o=t.strm.avail_in;do{if(n=65535,r=t.bi_valid+42>>3,t.strm.avail_out<r)break;if(r=t.strm.avail_out-r,i=t.strstart-t.block_start,n>i+t.strm.avail_in&&(n=i+t.strm.avail_in),n>r&&(n=r),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==i+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===i+t.strm.avail_in?1:0,_tr_stored_block(t,0,0,a),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,flush_pending(t.strm),i&&(i>n&&(i=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,n-=i),n&&(read_buf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(0===a);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),a?BS_FINISH_DONE:e!==Z_NO_FLUSH$2&&e!==Z_FINISH$3&&0===t.strm.avail_in&&t.strstart===t.block_start?BS_BLOCK_DONE:(r=t.window_size-t.strstart,t.strm.avail_in>r&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,r+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),r>t.strm.avail_in&&(r=t.strm.avail_in),r&&(read_buf(t.strm,t.window,t.strstart,r),t.strstart+=r,t.insert+=r>t.w_size-t.insert?t.w_size-t.insert:r),t.high_water<t.strstart&&(t.high_water=t.strstart),r=t.bi_valid+42>>3,r=t.pending_buf_size-r>65535?65535:t.pending_buf_size-r,s=r>t.w_size?t.w_size:r,i=t.strstart-t.block_start,(i>=s||(i||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&i<=r)&&(n=i>r?r:i,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===i?1:0,_tr_stored_block(t,t.block_start,n,a),t.block_start+=n,flush_pending(t.strm)),a?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(t,e)=>{let n,i;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(i=_tr_tally(t,t.strstart-t.match_start,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=MIN_MATCH){t.match_length--;do{t.strstart++,t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+1]);else i=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(t,e)=>{let n,i,r;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=MIN_MATCH-1,0!==n&&t.prev_length<t.max_lazy_match&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n),t.match_length<=5&&(t.strategy===Z_FILTERED||t.match_length===MIN_MATCH&&t.strstart-t.match_start>4096)&&(t.match_length=MIN_MATCH-1)),t.prev_length>=MIN_MATCH&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-MIN_MATCH,i=_tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-MIN_MATCH),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=MIN_MATCH-1,t.strstart++,i&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(i=_tr_tally(t,0,t.window[t.strstart-1]),i&&flush_block_only(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return BS_NEED_MORE}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=_tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(t,e)=>{let n,i,r,s;const a=t.window;for(;;){if(t.lookahead<=MAX_MATCH){if(fill_window(t),t.lookahead<=MAX_MATCH&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=MIN_MATCH&&t.strstart>0&&(r=t.strstart-1,i=a[r],i===a[++r]&&i===a[++r]&&i===a[++r])){s=t.strstart+MAX_MATCH;do{}while(i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&r<s);t.match_length=MAX_MATCH-(s-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=MIN_MATCH?(n=_tr_tally(t,1,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(t,e)=>{let n;for(;;){if(0===t.lookahead&&(fill_window(t),0===t.lookahead)){if(e===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(t.match_length=0,n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(t,e,n,i,r){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=i,this.func=r}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=t=>{t.window_size=2*t.w_size,zero(t.head),t.max_lazy_match=configuration_table[t.level].max_lazy,t.good_match=configuration_table[t.level].good_length,t.nice_match=configuration_table[t.level].nice_length,t.max_chain_length=configuration_table[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=MIN_MATCH-1,t.match_available=0,t.ins_h=0};function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*HEAP_SIZE),this.dyn_dtree=new Uint16Array(2*(2*D_CODES+1)),this.bl_tree=new Uint16Array(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==INIT_STATE&&e.status!==GZIP_STATE&&e.status!==EXTRA_STATE&&e.status!==NAME_STATE&&e.status!==COMMENT_STATE&&e.status!==HCRC_STATE&&e.status!==BUSY_STATE&&e.status!==FINISH_STATE?1:0},deflateResetKeep=t=>{if(deflateStateCheck(t))return err(t,Z_STREAM_ERROR$2);t.total_in=t.total_out=0,t.data_type=Z_UNKNOWN;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?GZIP_STATE:e.wrap?INIT_STATE:BUSY_STATE,t.adler=2===e.wrap?0:1,e.last_flush=-2,_tr_init(e),Z_OK$3},deflateReset=t=>{const e=deflateResetKeep(t);return e===Z_OK$3&&lm_init(t.state),e},deflateSetHeader=(t,e)=>deflateStateCheck(t)||2!==t.state.wrap?Z_STREAM_ERROR$2:(t.state.gzhead=e,Z_OK$3),deflateInit2=(t,e,n,i,r,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),r<1||r>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||i<8||i>15||e<0||e>9||s<0||s>Z_FIXED||8===i&&1!==a)return err(t,Z_STREAM_ERROR$2);8===i&&(i=9);const o=new DeflateState;return t.state=o,o.strm=t,o.status=INIT_STATE,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=n,deflateReset(t)},deflateInit=(t,e)=>deflateInit2(t,e,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(t,e)=>{if(deflateStateCheck(t)||e>Z_BLOCK$1||e<0)return t?err(t,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=t.state;if(!t.output||0!==t.avail_in&&!t.input||n.status===FINISH_STATE&&e!==Z_FINISH$3)return err(t,0===t.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const i=n.last_flush;if(n.last_flush=e,0!==n.pending){if(flush_pending(t),0===t.avail_out)return n.last_flush=-1,Z_OK$3}else if(0===t.avail_in&&rank(e)<=rank(i)&&e!==Z_FINISH$3)return err(t,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&0!==t.avail_in)return err(t,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&0===n.wrap&&(n.status=BUSY_STATE),n.status===INIT_STATE){let e=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=i<<6,0!==n.strstart&&(e|=PRESET_DICT),e+=31-e%31,putShortMSB(n,e),0!==n.strstart&&(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),t.adler=1,n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE)if(t.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,255&n.gzhead.time),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,255&n.gzhead.extra.length),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;if(n.status===EXTRA_STATE){if(n.gzhead.extra){let e=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex+=r,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let e,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;i=0}e=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;i=0}e=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(t),0!==n.pending))return n.last_flush=-1,Z_OK$3;put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),t.adler=0}if(n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(0!==t.avail_in||0!==n.lookahead||e!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let i=0===n.level?deflate_stored(n,e):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,e):n.strategy===Z_RLE?deflate_rle(n,e):configuration_table[n.level].func(n,e);if(i!==BS_FINISH_STARTED&&i!==BS_FINISH_DONE||(n.status=FINISH_STATE),i===BS_NEED_MORE||i===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(i===BS_BLOCK_DONE&&(e===Z_PARTIAL_FLUSH?_tr_align(n):e!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),e===Z_FULL_FLUSH$1&&(zero(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(t),0===t.avail_out))return n.last_flush=-1,Z_OK$3}return e!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(2===n.wrap?(put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),put_byte(n,t.adler>>16&255),put_byte(n,t.adler>>24&255),put_byte(n,255&t.total_in),put_byte(n,t.total_in>>8&255),put_byte(n,t.total_in>>16&255),put_byte(n,t.total_in>>24&255)):(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),flush_pending(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd=t=>{if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const e=t.state.status;return t.state=null,e===BUSY_STATE?err(t,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(t,e)=>{let n=e.length;if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const i=t.state,r=i.wrap;if(2===r||1===r&&i.status!==INIT_STATE||i.lookahead)return Z_STREAM_ERROR$2;if(1===r&&(t.adler=adler32_1(t.adler,e,n,0)),i.wrap=0,n>=i.w_size){0===r&&(zero(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(n-i.w_size,n),0),e=t,n=i.w_size}const s=t.avail_in,a=t.next_in,o=t.input;for(t.avail_in=n,t.next_in=0,t.input=e,fill_window(i);i.lookahead>=MIN_MATCH;){let t=i.strstart,e=i.lookahead-(MIN_MATCH-1);do{i.ins_h=HASH(i,i.ins_h,i.window[t+MIN_MATCH-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=MIN_MATCH-1,fill_window(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=MIN_MATCH-1,i.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,i.wrap=r,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var assign=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const e in n)_has(n,e)&&(t[e]=n[e])}}return t},flattenChunks=t=>{let e=0;for(let n=0,i=t.length;n<i;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,i=0,r=t.length;e<r;e++){let r=t[e];n.set(r,i),i+=r.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let t=0;t<256;t++)_utf8len[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,n,i,r,s,a=t.length,o=0;for(r=0;r<a;r++)n=t.charCodeAt(r),55296==(64512&n)&&r+1<a&&(i=t.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,r=0;s<o;r++)n=t.charCodeAt(r),55296==(64512&n)&&r+1<a&&(i=t.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?e[s++]=n:n<2048?(e[s++]=192|n>>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e};const buf2binstring=(t,e)=>{if(e<65534&&t.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let n="";for(let i=0;i<e;i++)n+=String.fromCharCode(t[i]);return n};var buf2string=(t,e)=>{const n=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,r;const s=new Array(2*n);for(r=0,i=0;i<n;){let e=t[i++];if(e<128){s[r++]=e;continue}let a=_utf8len[e];if(a>4)s[r++]=65533,i+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&i<n;)e=e<<6|63&t[i++],a--;a>1?s[r++]=65533:e<65536?s[r++]=e:(e-=65536,s[r++]=55296|e>>10&1023,s[r++]=56320|1023&e)}}return buf2binstring(s,r)},utf8border=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let n=e-1;for(;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+_utf8len[t[n]]>e?n:e},strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(t){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(e.header&&deflate_1$2.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$1.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,t),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}function deflate$1(t,e){const n=new Deflate$1(e);if(n.push(t,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(t,e){return(e=e||{}).raw=!0,deflate$1(t,e)}function gzip$1(t,e){return(e=e||{}).gzip=!0,deflate$1(t,e)}Deflate$1.prototype.push=function(t,e){const n=this.strm,i=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Z_FINISH$2:Z_NO_FLUSH$1,n.input="string"==typeof t?strings.string2buf(t):"[object ArrayBuffer]"===toString$1.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=deflate_1$2.deflate(n,s),r===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=deflate_1$2.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===Z_OK$2;if(0!==n.avail_out){if(s>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},Deflate$1.prototype.onData=function(t){this.chunks.push(t)},Deflate$1.prototype.onEnd=function(t){t===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function(t,e){let n,i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x,T;const A=t.state;n=t.next_in,x=t.input,i=n+(t.avail_in-5),r=t.next_out,T=t.output,s=r-(e-t.avail_out),a=r+(t.avail_out-257),o=A.dmax,l=A.wsize,h=A.whave,d=A.wnext,c=A.window,u=A.hold,f=A.bits,p=A.lencode,_=A.distcode,m=(1<<A.lenbits)-1,g=(1<<A.distbits)-1;t:do{f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),y=p[u&m];e:for(;;){if(v=y>>>24,u>>>=v,f-=v,v=y>>>16&255,0===v)T[r++]=65535&y;else{if(!(16&v)){if(64&v){if(32&v){A.mode=TYPE$1;break t}t.msg="invalid literal/length code",A.mode=BAD$1;break t}y=p[(65535&y)+(u&(1<<v)-1)];continue e}for(b=65535&y,v&=15,v&&(f<v&&(u+=x[n++]<<f,f+=8),b+=u&(1<<v)-1,u>>>=v,f-=v),f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),y=_[u&g];;){if(v=y>>>24,u>>>=v,f-=v,v=y>>>16&255,16&v){if(S=65535&y,v&=15,f<v&&(u+=x[n++]<<f,f+=8,f<v&&(u+=x[n++]<<f,f+=8)),S+=u&(1<<v)-1,S>o){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(u>>>=v,f-=v,v=r-s,S>v){if(v=S-v,v>h&&A.sane){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(E=0,w=c,0===d){if(E+=l-v,v<b){b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}}else if(d<v){if(E+=l+d-v,v-=d,v<b){b-=v;do{T[r++]=c[E++]}while(--v);if(E=0,d<b){v=d,b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}}}else if(E+=d-v,v<b){b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}for(;b>2;)T[r++]=w[E++],T[r++]=w[E++],T[r++]=w[E++],b-=3;b&&(T[r++]=w[E++],b>1&&(T[r++]=w[E++]))}else{E=r-S;do{T[r++]=T[E++],T[r++]=T[E++],T[r++]=T[E++],b-=3}while(b>2);b&&(T[r++]=T[E++],b>1&&(T[r++]=T[E++]))}break}if(64&v){t.msg="invalid distance code",A.mode=BAD$1;break t}y=_[(65535&y)+(u&(1<<v)-1)]}}break}}while(n<i&&r<a);b=f>>3,n-=b,f-=b<<3,u&=(1<<f)-1,t.next_in=n,t.next_out=r,t.avail_in=n<i?i-n+5:5-(n-i),t.avail_out=r<a?a-r+257:257-(r-a),A.hold=u,A.bits=f};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table=(t,e,n,i,r,s,a,o)=>{const l=o.bits;let h,d,c,u,f,p,_=0,m=0,g=0,y=0,v=0,b=0,S=0,E=0,w=0,x=0,T=null;const A=new Uint16Array(MAXBITS+1),R=new Uint16Array(MAXBITS+1);let B,C,k,I=null;for(_=0;_<=MAXBITS;_++)A[_]=0;for(m=0;m<i;m++)A[e[n+m]]++;for(v=l,y=MAXBITS;y>=1&&0===A[y];y--);if(v>y&&(v=y),0===y)return r[s++]=20971520,r[s++]=20971520,o.bits=1,0;for(g=1;g<y&&0===A[g];g++);for(v<g&&(v=g),E=1,_=1;_<=MAXBITS;_++)if(E<<=1,E-=A[_],E<0)return-1;if(E>0&&(t===CODES$1||1!==y))return-1;for(R[1]=0,_=1;_<MAXBITS;_++)R[_+1]=R[_]+A[_];for(m=0;m<i;m++)0!==e[n+m]&&(a[R[e[n+m]]++]=m);if(t===CODES$1?(T=I=a,p=20):t===LENS$1?(T=lbase,I=lext,p=257):(T=dbase,I=dext,p=0),x=0,m=0,_=g,f=s,b=v,S=0,c=-1,w=1<<v,u=w-1,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;for(;;){B=_-S,a[m]+1<p?(C=0,k=a[m]):a[m]>=p?(C=I[a[m]-p],k=T[a[m]-p]):(C=96,k=0),h=1<<_-S,d=1<<b,g=d;do{d-=h,r[f+(x>>S)+d]=B<<24|C<<16|k}while(0!==d);for(h=1<<_-1;x&h;)h>>=1;if(0!==h?(x&=h-1,x+=h):x=0,m++,0===--A[_]){if(_===y)break;_=e[n+a[m]]}if(_>v&&(x&u)!==c){for(0===S&&(S=v),f+=g,b=_-S,E=1<<b;b+S<y&&(E-=A[b+S],!(E<=0));)b++,E<<=1;if(w+=1<<b,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;c=x&u,r[c]=v<<24|b<<16|f-s}}return 0!==x&&(r[f+x]=_-S<<24|64<<16),o.bits=v,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<HEAD||e.mode>SYNC?1:0},inflateResetKeep=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=HEAD,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(ENOUGH_LENS),e.distcode=e.distdyn=new Int32Array(ENOUGH_DISTS),e.sane=1,e.back=-1,Z_OK$1},inflateReset=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,inflateResetKeep(t)},inflateReset2=(t,e)=>{let n;if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const i=t.state;return e<0?(n=0,e=-e):(n=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Z_STREAM_ERROR$1:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=n,i.wbits=e,inflateReset(t))},inflateInit2=(t,e)=>{if(!t)return Z_STREAM_ERROR$1;const n=new InflateState;t.state=n,n.strm=t,n.window=null,n.mode=HEAD;const i=inflateReset2(t,e);return i!==Z_OK$1&&(t.state=null),i},inflateInit=t=>inflateInit2(t,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=t=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(inftrees(LENS,t.lens,0,288,lenfix,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;inftrees(DISTS,t.lens,0,32,distfix,0,t.work,{bits:5}),virgin=!1}t.lencode=lenfix,t.lenbits=9,t.distcode=distfix,t.distbits=5},updatewindow=(t,e,n,i)=>{let r;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>i&&(r=i),s.window.set(e.subarray(n-i,n-i+r),s.wnext),(i-=r)?(s.window.set(e.subarray(n-i,n),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0},inflate$2=(t,e)=>{let n,i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x=0;const T=new Uint8Array(4);let A,R;const B=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(t)||!t.output||!t.input&&0!==t.avail_in)return Z_STREAM_ERROR$1;n=t.state,n.mode===TYPE&&(n.mode=TYPEDO),a=t.next_out,r=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=n.hold,d=n.bits,c=o,u=l,w=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&n.wrap&&35615===h){0===n.wbits&&(n.wbits=15),n.check=0,T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0),h=0,d=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",n.mode=BAD;break}if((15&h)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(h>>>=4,d-=4,E=8+(15&h),0===n.wbits&&(n.wbits=E),E>15||E>n.wbits){t.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,t.adler=n.check=1,n.mode=512&h?DICTID:TYPE,h=0,d=0;break;case FLAGS:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(n.flags=h,(255&n.flags)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(57344&n.flags){t.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=h>>8&1),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.head&&(n.head.time=h),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,T[2]=h>>>16&255,T[3]=h>>>24&255,n.check=crc32_1(n.check,T,4,0)),h=0,d=0,n.mode=OS;case OS:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.head&&(n.head.xflags=255&h,n.head.os=h>>8),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.length=h,n.head&&(n.head.extra_len=h),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(1024&n.flags&&(f=n.length,f>o&&(f=o),f&&(n.head&&(E=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(s,s+f),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,n.length-=f),n.length))break t;n.length=0,n.mode=NAME;case NAME:if(2048&n.flags){if(0===o)break t;f=0;do{E=i[s+f++],n.head&&E&&n.length<65536&&(n.head.name+=String.fromCharCode(E))}while(E&&f<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,E)break t}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(4096&n.flags){if(0===o)break t;f=0;do{E=i[s+f++],n.head&&E&&n.length<65536&&(n.head.comment+=String.fromCharCode(E))}while(E&&f<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,E)break t}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(512&n.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&n.wrap&&h!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}h=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=n.check=zswap32(h),h=0,d=0,n.mode=DICT;case DICT:if(0===n.havedict)return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,Z_NEED_DICT$1;t.adler=n.check=1,n.mode=TYPE;case TYPE:if(e===Z_BLOCK||e===Z_TREES)break t;case TYPEDO:if(n.last){h>>>=7&d,d-=7&d,n.mode=CHECK;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(n.last=1&h,h>>>=1,d-=1,3&h){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){h>>>=2,d-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}h>>>=2,d-=2;break;case STORED:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&h,h=0,d=0,n.mode=COPY_,e===Z_TREES)break t;case COPY_:n.mode=COPY;case COPY:if(f=n.length,f){if(f>o&&(f=o),f>l&&(f=l),0===f)break t;r.set(i.subarray(s,s+f),a),o-=f,s+=f,l-=f,a+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(n.nlen=257+(31&h),h>>>=5,d-=5,n.ndist=1+(31&h),h>>>=5,d-=5,n.ncode=4+(15&h),h>>>=4,d-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.lens[B[n.have++]]=7&h,h>>>=3,d-=3}for(;n.have<19;)n.lens[B[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,A={bits:n.lenbits},w=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,A),n.lenbits=A.bits,w){t.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;x=n.lencode[h&(1<<n.lenbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(y<16)h>>>=m,d-=m,n.lens[n.have++]=y;else{if(16===y){for(R=m+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=m,d-=m,0===n.have){t.msg="invalid bit length repeat",n.mode=BAD;break}E=n.lens[n.have-1],f=3+(3&h),h>>>=2,d-=2}else if(17===y){for(R=m+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,E=0,f=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,E=0,f=11+(127&h),h>>>=7,d-=7}if(n.have+f>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=BAD;break}for(;f--;)n.lens[n.have++]=E}}if(n.mode===BAD)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,A={bits:n.lenbits},w=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,A),n.lenbits=A.bits,w){t.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,A={bits:n.distbits},w=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,A),n.distbits=A.bits,w){t.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,e===Z_TREES)break t;case LEN_:n.mode=LEN;case LEN:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,inffast(t,u),a=t.next_out,r=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;x=n.lencode[h&(1<<n.lenbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g&&!(240&g)){for(v=m,b=g,S=y;x=n.lencode[S+((h&(1<<v+b)-1)>>v)],m=x>>>24,g=x>>>16&255,y=65535&x,!(v+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=v,d-=v,n.back+=v}if(h>>>=m,d-=m,n.back+=m,n.length=y,0===g){n.mode=LIT;break}if(32&g){n.back=-1,n.mode=TYPE;break}if(64&g){t.msg="invalid literal/length code",n.mode=BAD;break}n.extra=15&g,n.mode=LENEXT;case LENEXT:if(n.extra){for(R=n.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.length+=h&(1<<n.extra)-1,h>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;x=n.distcode[h&(1<<n.distbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(!(240&g)){for(v=m,b=g,S=y;x=n.distcode[S+((h&(1<<v+b)-1)>>v)],m=x>>>24,g=x>>>16&255,y=65535&x,!(v+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=v,d-=v,n.back+=v}if(h>>>=m,d-=m,n.back+=m,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(R=n.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.offset+=h&(1<<n.extra)-1,h>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(0===l)break t;if(f=u-l,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=BAD;break}f>n.wnext?(f-=n.wnext,p=n.wsize-f):p=n.wnext-f,f>n.length&&(f=n.length),_=n.window}else _=r,p=a-n.offset,f=n.length;f>l&&(f=l),l-=f,n.length-=f;do{r[a++]=_[p++]}while(--f);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;r[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(u-=l,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,r,u,a-u):adler32_1(n.check,r,u,a-u)),u=l,4&n.wrap&&(n.flags?h:zswap32(h))!==n.check){t.msg="incorrect data check",n.mode=BAD;break}h=0,d=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&n.wrap&&h!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}h=0,d=0}n.mode=DONE;case DONE:w=Z_STREAM_END$1;break t;case BAD:w=Z_DATA_ERROR$1;break t;case MEM:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,(n.wsize||u!==t.avail_out&&n.mode<BAD&&(n.mode<CHECK||e!==Z_FINISH$1))&&updatewindow(t,t.output,t.next_out,u-t.avail_out),c-=t.avail_in,u-=t.avail_out,t.total_in+=c,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,r,u,t.next_out-u):adler32_1(n.check,r,u,t.next_out-u)),t.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(0===c&&0===u||e===Z_FINISH$1)&&w===Z_OK$1&&(w=Z_BUF_ERROR),w},inflateEnd=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;let e=t.state;return e.window&&(e.window=null),t.state=null,Z_OK$1},inflateGetHeader=(t,e)=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const n=t.state;return 2&n.wrap?(n.head=e,e.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(t,e)=>{const n=e.length;let i,r,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(i=t.state,0!==i.wrap&&i.mode!==DICT?Z_STREAM_ERROR$1:i.mode===DICT&&(r=1,r=adler32_1(r,e,n,0),r!==i.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(i.mode=MEM,Z_MEM_ERROR$1):(i.havedict=1,Z_OK$1)))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString$2=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(t){this.options=common.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(15&e.windowBits||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,e.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$2.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,e.dictionary),n!==Z_OK)))throw new Error(messages[n])}function inflate$1(t,e){const n=new Inflate$1(e);if(n.push(t),n.err)throw n.msg||messages[n.err];return n.result}function inflateRaw$1(t,e){return(e=e||{}).raw=!0,inflate$1(t,e)}Inflate$1.prototype.push=function(t,e){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:!0===e?Z_FINISH:Z_NO_FLUSH,n.input="[object ArrayBuffer]"===toString$2.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&r&&(s=inflate_1$2.inflateSetDictionary(n,r),s===Z_OK?s=inflate_1$2.inflate(n,a):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&0!==t[n.next_in];)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,a);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(0===n.avail_out||s===Z_STREAM_END))if("string"===this.options.to){let t=strings.utf8border(n.output,n.next_out),e=n.next_out-t,r=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=i-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(r)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(s!==Z_OK||0!==o){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},Inflate$1.prototype.onData=function(t){this.chunks.push(t)},Inflate$1.prototype.onEnd=function(t){t===Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Inflate_1$1=Inflate$1,inflate_2=inflate$1,inflateRaw_1$1=inflateRaw$1,ungzip$1=inflate$1,constants=constants$2,inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1,{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate,deflate_1=deflate,deflateRaw_1=deflateRaw,gzip_1=gzip,Inflate_1=Inflate,inflate_1=inflate,inflateRaw_1=inflateRaw,ungzip_1=ungzip,constants_1=constants$2,pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};async function request(t,e={}){const{method:n="GET",data:i,headers:r={}}=e,s={method:n,headers:_extends({"Content-Type":"application/json"},r)};if("GET"===n&&i){const e=new URLSearchParams(i).toString();t+=`${t.includes("?")?"&":"?"}${e}`}"GET"!==n&&i&&(s.body=JSON.stringify(i));try{const e=await fetch(t,s);if(!e.ok)throw{status:e.status,statusText:e.statusText,message:`HTTP error! status: ${e.status}`};return e}catch(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}}function XMLRequest(t){return new Promise((e,n)=>{var i;const r=new XMLHttpRequest;r.open("GET",t.url),r.responseType="arraybuffer",r.timeout=null!=(i=t.timeout)?i:6e4,r.onload=function(){4===r.readyState&&200===r.status?e([!1,r.response]):n([!0,`HTTP ${r.status} ${r.statusText}`])},r.onerror=function(){n([!0,"network error"])},r.ontimeout=function(){n([!0,`timeout after ${r.timeout}ms`])},r.onabort=function(){n([!0,"aborted"])},r.onprogress=e=>{if(e.lengthComputable){const n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},r.send()})}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t){var e={exports:{}};return t(e,e.exports),e.exports}var md5=createCommonjsModule(function(t){!function(e){function n(t,e){var n=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(n>>16)<<16|65535&n}function i(t,e,i,r,s,a){return n((o=n(n(e,t),n(r,a)))<<(l=s)|o>>>32-l,i);var o,l}function r(t,e,n,r,s,a,o){return i(e&n|~e&r,t,e,s,a,o)}function s(t,e,n,r,s,a,o){return i(e&r|n&~r,t,e,s,a,o)}function a(t,e,n,r,s,a,o){return i(e^n^r,t,e,s,a,o)}function o(t,e,n,r,s,a,o){return i(n^(e|~r),t,e,s,a,o)}function l(t,e){var i,l,h,d,c;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,f=-271733879,p=-1732584194,_=271733878;for(i=0;i<t.length;i+=16)l=u,h=f,d=p,c=_,u=r(u,f,p,_,t[i],7,-680876936),_=r(_,u,f,p,t[i+1],12,-389564586),p=r(p,_,u,f,t[i+2],17,606105819),f=r(f,p,_,u,t[i+3],22,-1044525330),u=r(u,f,p,_,t[i+4],7,-176418897),_=r(_,u,f,p,t[i+5],12,1200080426),p=r(p,_,u,f,t[i+6],17,-1473231341),f=r(f,p,_,u,t[i+7],22,-45705983),u=r(u,f,p,_,t[i+8],7,1770035416),_=r(_,u,f,p,t[i+9],12,-1958414417),p=r(p,_,u,f,t[i+10],17,-42063),f=r(f,p,_,u,t[i+11],22,-1990404162),u=r(u,f,p,_,t[i+12],7,1804603682),_=r(_,u,f,p,t[i+13],12,-40341101),p=r(p,_,u,f,t[i+14],17,-1502002290),u=s(u,f=r(f,p,_,u,t[i+15],22,1236535329),p,_,t[i+1],5,-165796510),_=s(_,u,f,p,t[i+6],9,-1069501632),p=s(p,_,u,f,t[i+11],14,643717713),f=s(f,p,_,u,t[i],20,-373897302),u=s(u,f,p,_,t[i+5],5,-701558691),_=s(_,u,f,p,t[i+10],9,38016083),p=s(p,_,u,f,t[i+15],14,-660478335),f=s(f,p,_,u,t[i+4],20,-405537848),u=s(u,f,p,_,t[i+9],5,568446438),_=s(_,u,f,p,t[i+14],9,-1019803690),p=s(p,_,u,f,t[i+3],14,-187363961),f=s(f,p,_,u,t[i+8],20,1163531501),u=s(u,f,p,_,t[i+13],5,-1444681467),_=s(_,u,f,p,t[i+2],9,-51403784),p=s(p,_,u,f,t[i+7],14,1735328473),u=a(u,f=s(f,p,_,u,t[i+12],20,-1926607734),p,_,t[i+5],4,-378558),_=a(_,u,f,p,t[i+8],11,-2022574463),p=a(p,_,u,f,t[i+11],16,1839030562),f=a(f,p,_,u,t[i+14],23,-35309556),u=a(u,f,p,_,t[i+1],4,-1530992060),_=a(_,u,f,p,t[i+4],11,1272893353),p=a(p,_,u,f,t[i+7],16,-155497632),f=a(f,p,_,u,t[i+10],23,-1094730640),u=a(u,f,p,_,t[i+13],4,681279174),_=a(_,u,f,p,t[i],11,-358537222),p=a(p,_,u,f,t[i+3],16,-722521979),f=a(f,p,_,u,t[i+6],23,76029189),u=a(u,f,p,_,t[i+9],4,-640364487),_=a(_,u,f,p,t[i+12],11,-421815835),p=a(p,_,u,f,t[i+15],16,530742520),u=o(u,f=a(f,p,_,u,t[i+2],23,-995338651),p,_,t[i],6,-198630844),_=o(_,u,f,p,t[i+7],10,1126891415),p=o(p,_,u,f,t[i+14],15,-1416354905),f=o(f,p,_,u,t[i+5],21,-57434055),u=o(u,f,p,_,t[i+12],6,1700485571),_=o(_,u,f,p,t[i+3],10,-1894986606),p=o(p,_,u,f,t[i+10],15,-1051523),f=o(f,p,_,u,t[i+1],21,-2054922799),u=o(u,f,p,_,t[i+8],6,1873313359),_=o(_,u,f,p,t[i+15],10,-30611744),p=o(p,_,u,f,t[i+6],15,-1560198380),f=o(f,p,_,u,t[i+13],21,1309151649),u=o(u,f,p,_,t[i+4],6,-145523070),_=o(_,u,f,p,t[i+11],10,-1120210379),p=o(p,_,u,f,t[i+2],15,718787259),f=o(f,p,_,u,t[i+9],21,-343485551),u=n(u,l),f=n(f,h),p=n(p,d),_=n(_,c);return[u,f,p,_]}function h(t){var e,n="",i=32*t.length;for(e=0;e<i;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function d(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var i=8*t.length;for(e=0;e<i;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function c(t){var e,n,i="0123456789abcdef",r="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),r+=i.charAt(e>>>4&15)+i.charAt(15&e);return r}function u(t){return unescape(encodeURIComponent(t))}function f(t){return function(t){return h(l(d(t),8*t.length))}(u(t))}function p(t,e){return function(t,e){var n,i,r=d(t),s=[],a=[];for(s[15]=a[15]=void 0,r.length>16&&(r=l(r,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^r[n],a[n]=1549556828^r[n];return i=l(s.concat(d(e)),512+8*e.length),h(l(a.concat(i),640))}(u(t),u(e))}function _(t,e,n){return e?n?p(e,t):c(p(e,t)):n?f(t):c(f(t))}t.exports?t.exports=_:e.md5=_}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function compareUnicodeCodePoints(t,e){const n=Array.from(t,t=>t.codePointAt(0)),i=Array.from(e,t=>t.codePointAt(0)),r=Math.min(n.length,i.length);for(let t=0;t<r;t+=1)if(n[t]!==i[t])return n[t]-i[t];return n.length-i.length}function parseUrlWithoutBase(t){try{const e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){let n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,i,r){const s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(i).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(e=>t(e));if("object"!=typeof e)return e;const n=Object.keys(e).sort(compareUnicodeCodePoints),i={};for(const r of n)i[r]=t(e[r]);return i}(r),h=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),d=encodeWithMd5(`${o.toLowerCase()}${n.toLowerCase()}${h}${e}${a}`);return s["X-APP-ID"]=t,s["X-TOKEN"]=d,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}class CacheManager{constructor(t){this.cacheServer=t}getVideo(t){return`${this.cacheServer}/get_video?url=${encodeURIComponent(t)}`}}class ResourceManager{constructor(t){this.TAG="[ResourceManager]",this.offlineIdle=[],this.offlineCache=new Map,this.networkInfos=[],this.bg=null,this.destroyed=!1,this.progress=0,this.videoCache=new Map,this.maxCacheSize=10485760,this.maxCacheEntries=20,this.cacheCleanupInterval=null,this.isProcessingVideo=!1,this.startSessionTimer=null,this.audioOnlyMode=!1,this.downloadingVideos=new Map,this.first_load=!0,this.options=t,this.audioOnlyMode=t.audioOnlyMode||!1,this.sdk=t.sdkInstance,this.mouthShapeLib={char_info:null},this.config=t.config||{},this.resource_pack={enable_robot_expression:!1,body_data_dir:"",face_ani_char_data:"",face_ani_preload_data:"",interpolate_joints:[[4,3]]},t.cacheServer&&(this.cacheServer=new CacheManager(t.cacheServer)),this.startCacheCleanup()}getAppInfo(){return{appId:this.options.appId}}getBackgroundImage(){return new Promise((t,e)=>{try{var n,i;const e=new Image;if(e.crossOrigin="anonymous",e.src=(null==(n=this.config)?void 0:n.background_img)||"",null==(i=this.config)||!i.background_img)return;e.onload=()=>{this.bg=e,t()},e.onerror=n=>{this.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:e}}),this.bg=null,t()}}catch(t){}})}getIsEnableRobotExpression(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression}getBackgroundImageElement(){return this.bg}getConfig(){return this.config}async load(t){var e;this.destroyed=!1,null==t||t(this.progress),this.startSessionTimer&&(clearInterval(this.startSessionTimer),this.startSessionTimer=null),this.startSessionTimer=setInterval(()=>{if(this.destroyed||this.progress>=14)return clearInterval(this.startSessionTimer),void(this.startSessionTimer=null);this.progress+=1,null==t||t(this.progress)},100);const n=await this.startSession(),i=n;return null!=i&&i.session_id&&(this.session_id=i.session_id),this.destroyed?(window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after startSession"),await this.stopSession("destroy_during_init"),null):n?(clearInterval(this.startSessionTimer),this.startSessionTimer=null,this.progress=15,null==t||t(this.progress),this.resource_pack=i.resource_pack,this.config=i.config,this.offlineIdle=(null==(e=i.resource_pack)?void 0:e.offline_idle)||[],!this.resource_pack||(this.audioOnlyMode||await this.loadMouthShapeLib(t),this.getBackgroundImage(),null!=(r=this.mouthShapeLib)&&r.char_info||null==i||null==(s=i.resource_pack)||!s.face_ani_char_data||this.audioOnlyMode)?i:null):(clearInterval(this.startSessionTimer),this.startSessionTimer=null,null);var r,s}async startSession(){try{const n=await this._startSession();var t,e;return null!=n&&n.verify_res&&(null==(t=(e=this.options).onStartSessionWarning)||t.call(e,n.verify_res)),n}catch(t){return null}}_startSession(){var t;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;const e=`${this.options.gatewayServer}`,n=_extends({tag:this.options.tag,gateway_type:this.options.gateway_type},void 0!==this.options.asr_id?{asr_id:this.options.asr_id}:{},void 0!==this.options.llm_id?{llm_id:this.options.llm_id}:{},void 0!==this.options.session_speak_req_id?{session_speak_req_id:this.options.session_speak_req_id}:{},null!=(t=this.options.sessionRequestData)?t:{},{config:_extends({},this.config,{framedata_proto_version:2,walk_version:3})}),{headers:i,data:r}=headersNeedSign(this.options.appId,this.options.appSecret,"POST",e,n);return request(e,{method:"POST",data:r,headers:_extends({},i,this.options.headers)}).then(t=>t.json()).then(t=>{var e;return null!=t&&null!=(e=t.data)&&e.resource_pack?null==t?void 0:t.data:(this.sdk.onMessage({code:null==t?void 0:t.error_code,message:`Error: ${null==t?void 0:t.error_code}, ${null==t?void 0:t.error_reason}`}),null)}).catch(t=>(this.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null))}async stopSession(t){try{const e=`${this.options.gatewayServer}`;if(!this.session_id)return;const n={session_id:this.session_id,stop_reason:t},{headers:i,data:r}=headersNeedSign(this.options.appId,this.options.appSecret,"DELETE",e,n),s=await request(e,{method:"DELETE",data:r,headers:_extends({},i,this.options.headers)});return await s.json()}catch(t){this.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}}async loadMouthShapeLib(t){try{var e,n;if(!this.resource_pack.face_ani_char_data)return this.progress+=60,void(null==t||t(this.progress));let s=null,a=null,o="",l=0,h=0,d=0,c=0;const u=()=>(e,n)=>{var i,r;if(!n)return;const s=performance.now(),a=s-d,o=n.loaded-c;null==(i=(r=this.options).onNetworkInfo)||i.call(r,{rtt:a,downlink:a>0&&o>0?8*o/(a/1e3)/1e6:0,networkStatus:navigator.onLine}),c=n.loaded,d=s,null==t||t(this.progress+.65*e)};try{const t=`${this.resource_pack.face_ani_char_data}.gz`;o=t,h=performance.now(),d=h,c=0;const[,e]=await XMLRequest({url:t,onProgress:u()}),n=pako.ungzip(new Uint8Array(e)),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n),s=i}catch(t){a=t,s=null}if(!s)try{const t=this.resource_pack.face_ani_char_data;o=t,h=performance.now(),d=h,c=0;const[,e]=await XMLRequest({url:t,onProgress:u()});s=e}catch(t){var i,r;return this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),void(null==(i=(r=this.sdk).onMessage)||i.call(r,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:a,binError:t}}))}const f=performance.now()-h;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:f,downlink:l>0&&f>0?8*l/(f/1e3)/1e6:0,networkStatus:navigator.onLine}),this.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(s,{blendshapeMap:this.resource_pack.blendshape_map||[]})},this.progress+=65,null==t||t(this.progress)}catch(t){var s,a;this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),null==(s=(a=this.sdk).onMessage)||s.call(a,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}}getMouthShapeLib(){return this.mouthShapeLib}getVideoUrl(t){if(!this.resource_pack.body_data_dir)return"";if(!t)return this.first_load&&(this.first_load=!1,this.stopSession("no_video_name_error")),this.sdk.onMessage({code:EErrorCode.INVALID_BODY_NAME,message:"Error: 视频地址获取失败",e:t}),"";const e=`${this.resource_pack.body_data_dir}${t}.mp4`;var n;return this.cacheServer?null==(n=this.cacheServer)?void 0:n.getVideo(e):e}async preloadVideo(t){if(!this.videoCache.has(t))return this.loadVideo(t)}async loadVideo(t){const e=this.videoCache.get(t)||this.offlineCache.get(t);if(e){if(e.data)return this.updateCacheAccess(t),e.data;window.avatarSDKLogger.warn(this.TAG,`发现无效缓存条目: ${t},正在删除`),this.videoCache.delete(t)}if(this.downloadingVideos.has(t))try{return await this.downloadingVideos.get(t)}catch(e){throw this.downloadingVideos.delete(t),window.avatarSDKLogger.warn(this.TAG,`${t} 视频下载失败,从下载列表移除`),e}this.isProcessingVideo=!0;const n=this.downloadVideo(t);this.downloadingVideos.set(t,n);try{return await n}finally{this.downloadingVideos.delete(t),this.isProcessingVideo=!1}}async downloadVideo(t){const e=this.getVideoUrl(t);if(e)try{const{response:n,arrayBuffer:i}=await this._fetchVideo(e);return n.ok?(this.addToCache(t,i),i):(this.first_load&&(this.first_load=!1,this.stopSession("load_video_error")),void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,res:n}}))}catch(n){return void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,error:n}})}}async _fetchVideo(t){if(this.networkInfos.length>=4){var e,n;const t=this.networkInfos.reduce((t,e)=>t+e.rtt,0)/this.networkInfos.length,i=this.networkInfos.reduce((t,e)=>t+e.downlink,0)/this.networkInfos.length;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:t,downlink:i,networkStatus:navigator.onLine}),this.networkInfos.length=0}const i=performance.now(),r=await fetch(t),s=parseFloat(r.headers.get("Content-Length")||"0"),a=performance.now(),o=await r.arrayBuffer(),l=a-i,h={rtt:l,downlink:8*s/(l/1e3*1e6),networkStatus:navigator.onLine};return this.networkInfos.push(h),{response:r,arrayBuffer:o}}addToCache(t,e){const n=Date.now();let i=0;for(const t of this.videoCache.values())i+=t.data.byteLength;if(i+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),i=0;for(const t of this.videoCache.values())i+=t.data.byteLength;if(i+e.byteLength>this.maxCacheSize&&e.byteLength>.5*this.maxCacheSize)return void window.avatarSDKLogger.warn(this.TAG,`视频文件过大(${(e.byteLength/1024/1024).toFixed(2)}MB),跳过缓存: ${t}`);if(i+e.byteLength>this.maxCacheSize){const t=.5*this.maxCacheSize,e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);for(const[n,r]of e){if(i<=t)break;this.videoCache.delete(n),i-=r.data.byteLength}}}this.videoCache.set(t,{data:e,lastAccessTime:n,accessCount:1})}startCacheCleanup(){this.cacheCleanupInterval=setInterval(()=>{this.cleanupCache()},3e5)}cleanupCache(){if(this.isProcessingVideo)return;const t=Date.now(),e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);let n=0;const i=[];for(const[t,e]of this.videoCache.entries())n+=e.data.byteLength;for(const[r,s]of e)t-s.lastAccessTime>6e5&&(i.push(r),n-=s.data.byteLength);if(n>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(const[t,r]of e)if(!i.includes(t)&&(i.push(t),n-=r.data.byteLength,this.videoCache.size-i.length<=2||n<=.8*this.maxCacheSize&&this.videoCache.size-i.length<=.8*this.maxCacheEntries))break;for(const t of i)this.videoCache.delete(t)}updateCacheAccess(t){const e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)}clearAllCache(){this.videoCache.clear()}_getOfflineIdle(){return this.offlineIdle}_getSessionId(){return this.session_id||""}async _reload(){var t;const e=await this.startSession();if(!e)return null;const n=e;return this.session_id=null==n?void 0:n.session_id,this.destroyed?(await this.stopSession("destroy_during_reload"),null):(this.resource_pack=n.resource_pack,this.config=n.config,this.offlineIdle=(null==(t=n.resource_pack)?void 0:t.offline_idle)||[],this.resource_pack&&this.getBackgroundImage(),n)}async _setOfflineCache(){if(!this.offlineIdle||0===this.offlineIdle.length)return;this.offlineCache.clear();const t=this.offlineIdle.map(t=>t.n);for(const e of t)try{await this._runOfflineCache(e)}catch(t){}}async _runOfflineCache(t){const e=this.getVideoUrl(t);if(e)return this._fetchVideo(e).then(({arrayBuffer:e})=>{this.offlineCache.set(t,{data:e})})}destroy(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0}}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){n.r(e),n.d(e,"encode",function(){return B}),n.d(e,"decode",function(){return G}),n.d(e,"decodeAsync",function(){return Y}),n.d(e,"decodeArrayStream",function(){return X}),n.d(e,"decodeStream",function(){return Z}),n.d(e,"Decoder",function(){return N}),n.d(e,"Encoder",function(){return A}),n.d(e,"ExtensionCodec",function(){return w}),n.d(e,"ExtData",function(){return f}),n.d(e,"EXT_TIMESTAMP",function(){return m}),n.d(e,"encodeDateToTimeSpec",function(){return y}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return b}),n.d(e,"encodeTimestampExtension",function(){return v}),n.d(e,"decodeTimestampExtension",function(){return S});var i=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,r,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return a},r=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(i(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,i=0;i<e;){var r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){var s=t.charCodeAt(i);56320==(64512&s)&&(++i,r=((1023&r)<<10)+(1023&s)+65536)}n+=4294901760&r?4:3}else n+=2;else n++}return n}var o=s?new TextEncoder:void 0,l="undefined"!=typeof process?200:0,h=(null==o?void 0:o.encodeInto)?function(t,e,n){o.encodeInto(t,e.subarray(n))}:function(t,e,n){e.set(o.encode(t),n)};function d(t,e,n){for(var i=e,s=i+n,a=[],o="";i<s;){var l=t[i++];if(128&l)if(192==(224&l)){var h=63&t[i++];a.push((31&l)<<6|h)}else if(224==(240&l)){h=63&t[i++];var d=63&t[i++];a.push((31&l)<<12|h<<6|d)}else if(240==(248&l)){var c=(7&l)<<18|(h=63&t[i++])<<12|(d=63&t[i++])<<6|63&t[i++];c>65535&&(a.push((c-=65536)>>>10&1023|55296),c=56320|1023&c),a.push(c)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,r(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,r(a))),o}var c=s?new TextDecoder:null,u="undefined"!=typeof process?200:0,f=function(t,e){this.type=t,this.data=e};function p(t,e,n){var i=Math.floor(n/4294967296),r=n;t.setUint32(e,i),t.setUint32(e+4,r)}function _(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var m=-1;function g(t){var e,n=t.sec,i=t.nsec;if(n>=0&&i>=0&&n<=17179869183){if(0===i&&n<=4294967295){var r=new Uint8Array(4);return(e=new DataView(r.buffer)).setUint32(0,n),r}var s=n/4294967296,a=4294967295&n;return r=new Uint8Array(8),(e=new DataView(r.buffer)).setUint32(0,i<<2|3&s),e.setUint32(4,a),r}return r=new Uint8Array(12),(e=new DataView(r.buffer)).setUint32(0,i),p(e,4,n),r}function y(t){var e=t.getTime(),n=Math.floor(e/1e3),i=1e6*(e-1e3*n),r=Math.floor(i/1e9);return{sec:n+r,nsec:i-1e9*r}}function v(t){return t instanceof Date?g(y(t)):null}function b(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:var n=e.getUint32(0);return{sec:4294967296*(3&n)+e.getUint32(4),nsec:n>>>2};case 12:return{sec:_(e,4),nsec:e.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+t.length)}}function S(t){var e=b(t);return new Date(1e3*e.sec+e.nsec/1e6)}var E={type:m,encode:v,decode:S},w=function(){function t(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(E)}return t.prototype.register=function(t){var e=t.type,n=t.encode,i=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{var r=1+e;this.builtInEncoders[r]=n,this.builtInDecoders[r]=i}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(i=this.builtInEncoders[n])&&null!=(r=i(t,e)))return new f(-1-n,r);for(n=0;n<this.encoders.length;n++){var i,r;if(null!=(i=this.encoders[n])&&null!=(r=i(t,e)))return new f(n,r)}return t instanceof f?t:null},t.prototype.decode=function(t,e,n){var i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,n):new f(e,t)},t.defaultCodec=new t,t}();function x(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer?new Uint8Array(t):Uint8Array.from(t)}var T=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A=function(){function t(t,e,n,i,r,s,a){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=100),void 0===i&&(i=2048),void 0===r&&(r=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=i,this.sortKeys=r,this.forceFloat32=s,this.ignoreUndefined=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return t.prototype.encode=function(t,e){if(e>this.maxDepth)throw new Error("Too deep objects in depth "+e);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.encodeObject(t,e)},t.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},t.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)},t.prototype.resizeBuffer=function(t){var e=new ArrayBuffer(t),n=new Uint8Array(e),i=new DataView(e);n.set(this.bytes),this.view=i,this.bytes=n},t.prototype.encodeNil=function(){this.writeU8(192)},t.prototype.encodeBoolean=function(t){this.writeU8(!1===t?194:195)},t.prototype.encodeNumber=function(t){Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},t.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too long string: "+t+" bytes in UTF-8");this.writeU8(219),this.writeU32(t)}},t.prototype.encodeString=function(t){if(s&&t.length>l){var e=a(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),h(t,this.bytes,this.pos),this.pos+=e}else e=a(t),this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),function(t,e,n){for(var i=t.length,r=n,s=0;s<i;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<i){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[r++]=a>>18&7|240,e[r++]=a>>12&63|128,e[r++]=a>>6&63|128):(e[r++]=a>>12&15|224,e[r++]=a>>6&63|128)}else e[r++]=a>>6&31|192;e[r++]=63&a|128}else e[r++]=a}}(t,this.bytes,this.pos),this.pos+=e},t.prototype.encodeObject=function(t,e){var n=this.extensionCodec.tryToEncode(t,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(t));this.encodeMap(t,e)}},t.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large binary: "+e);this.writeU8(198),this.writeU32(e)}var n=x(t);this.writeU8a(n)},t.prototype.encodeArray=function(t,e){var n,i,r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: "+r);this.writeU8(221),this.writeU32(r)}try{for(var s=T(t),a=s.next();!a.done;a=s.next())this.encode(a.value,e+1)}catch(t){n={error:t}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,i,r=0;try{for(var s=T(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&r++}catch(t){n={error:t}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return r},t.prototype.encodeMap=function(t,e){var n,i,r=Object.keys(t);this.sortKeys&&r.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error("Too large map object: "+s);this.writeU8(223),this.writeU32(s)}try{for(var a=T(r),o=a.next();!o.done;o=a.next()){var l=o.value,h=t[l];this.ignoreUndefined&&void 0===h||(this.encodeString(l),this.encode(h,e+1))}}catch(t){n={error:t}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}},t.prototype.encodeExtension=function(t){var e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large extension object: "+e);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)},t.prototype.writeU8=function(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++},t.prototype.writeU8a=function(t){var e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e},t.prototype.writeI8=function(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++},t.prototype.writeU16=function(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2},t.prototype.writeI16=function(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2},t.prototype.writeU32=function(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4},t.prototype.writeI32=function(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4},t.prototype.writeF32=function(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4},t.prototype.writeF64=function(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8},t.prototype.writeU64=function(t){this.ensureBufferSizeToWrite(8),function(t,e,n){var i=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,i)}(this.view,this.pos,t),this.pos+=8},t.prototype.writeI64=function(t){this.ensureBufferSizeToWrite(8),p(this.view,this.pos,t),this.pos+=8},t}(),R={};function B(t,e){void 0===e&&(e=R);var n=new A(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined);return n.encode(t,1),n.getUint8Array()}function C(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var k=function(){function t(t,e){void 0===t&&(t=16),void 0===e&&(e=16),this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return t.prototype.canBeCached=function(t){return t>0&&t<=this.maxKeyLength},t.prototype.get=function(t,e,n){var i=this.caches[n-1],r=i.length;t:for(var s=0;s<r;s++){for(var a=i[s],o=a.bytes,l=0;l<n;l++)if(o[l]!==t[e+l])continue t;return a.value}return null},t.prototype.store=function(t,e){var n=this.caches[t.length-1],i={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)},t.prototype.decode=function(t,e,n){var i=this.get(t,e,n);if(null!=i)return i;var r=d(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,r),r},t}(),I=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},P=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(n){e[n]=t[n]&&function(e){return new Promise(function(i,r){!function(t,e,n,i){Promise.resolve(i).then(function(e){t({value:e,done:n})},e)}(i,r,(e=t[n](e)).done,e.value)})}}},D=function(t){return this instanceof D?(this.v=t,this):new D(t)},U=new DataView(new ArrayBuffer(0)),O=new Uint8Array(U.buffer),F=function(){try{U.getInt8(0)}catch(t){return t.constructor}throw new Error("never reached")}(),L=new F("Insufficient data"),M=new k,N=function(){function t(t,e,n,i,r,s,a,o){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=4294967295),void 0===i&&(i=4294967295),void 0===r&&(r=4294967295),void 0===s&&(s=4294967295),void 0===a&&(a=4294967295),void 0===o&&(o=M),this.extensionCodec=t,this.context=e,this.maxStrLength=n,this.maxBinLength=i,this.maxArrayLength=r,this.maxMapLength=s,this.maxExtLength=a,this.cachedKeyDecoder=o,this.totalPos=0,this.pos=0,this.view=U,this.bytes=O,this.headByte=-1,this.stack=[]}return t.prototype.setBuffer=function(t){this.bytes=x(t),this.view=function(t){if(t instanceof ArrayBuffer)return new DataView(t);var e=x(t);return new DataView(e.buffer,e.byteOffset,e.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(t){if(-1!==this.headByte||this.hasRemaining()){var e=this.bytes.subarray(this.pos),n=x(t),i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),this.setBuffer(i)}else this.setBuffer(t)},t.prototype.hasRemaining=function(t){return void 0===t&&(t=1),this.view.byteLength-this.pos>=t},t.prototype.createNoExtraBytesError=function(t){return new RangeError("Extra "+(this.view.byteLength-this.pos)+" byte(s) found at buffer["+t+"]")},t.prototype.decodeSingleSync=function(){var t=this.decodeSync();if(this.hasRemaining())throw this.createNoExtraBytesError(this.pos);return t},t.prototype.decodeSingleAsync=function(t){var e,n,i,r;return function(t,e,n,i){return new(n||(n=Promise))(function(e,r){function s(t){try{o(i.next(t))}catch(t){r(t)}}function a(t){try{o(i.throw(t))}catch(t){r(t)}}function o(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(t){t(i)})).then(s,a)}o((i=i.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,h,d,c,u;return I(this,function(f){switch(f.label){case 0:s=!1,f.label=1;case 1:f.trys.push([1,6,7,12]),e=P(t),f.label=2;case 2:return[4,e.next()];case 3:if((n=f.sent()).done)return[3,5];if(o=n.value,s)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(o);try{a=this.decodeSync(),s=!0}catch(t){if(!(t instanceof F))throw t}this.totalPos+=this.pos,f.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=f.sent(),i={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),n&&!n.done&&(r=e.return)?[4,r.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw d=(h=this).headByte,c=h.pos,u=h.totalPos,new RangeError("Insufficient data in parcing "+C(d)+" at "+u+" ("+c+" in the current buffer)")}})})},t.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},t.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},t.prototype.decodeMultiAsync=function(t,e){return function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(t,e||[]),s=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(t){r[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||o(t,e)})})}function o(t,e){try{(n=r[t](e)).value instanceof D?Promise.resolve(n.value.v).then(l,h):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,i,r,s,a,o,l,h,d;return I(this,function(c){switch(c.label){case 0:n=e,i=-1,c.label=1;case 1:c.trys.push([1,13,14,19]),r=P(t),c.label=2;case 2:return[4,D(r.next())];case 3:if((s=c.sent()).done)return[3,12];if(a=s.value,e&&0===i)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(i=this.readArraySize(),n=!1,this.complete()),c.label=4;case 4:c.trys.push([4,9,,10]),c.label=5;case 5:return[4,D(this.decodeSync())];case 6:return[4,c.sent()];case 7:return c.sent(),0==--i?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=c.sent())instanceof F))throw o;return[3,10];case 10:this.totalPos+=this.pos,c.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=c.sent(),h={error:l},[3,19];case 14:return c.trys.push([14,,17,18]),s&&!s.done&&(d=r.return)?[4,D(d.call(r))]:[3,16];case 15:c.sent(),c.label=16;case 16:return[3,18];case 17:if(h)throw h.error;return[7];case 18:return[7];case 19:return[2]}})})},t.prototype.decodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){if(0!=(i=t-128)){this.pushMapState(i),this.complete();continue t}e={}}else if(t<160){if(0!=(i=t-144)){this.pushArrayState(i),this.complete();continue t}e=[]}else{var n=t-160;e=this.decodeUtf8String(n,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.readI64();else if(217===t)n=this.lookU8(),e=this.decodeUtf8String(n,1);else if(218===t)n=this.lookU16(),e=this.decodeUtf8String(n,2);else if(219===t)n=this.lookU32(),e=this.decodeUtf8String(n,4);else if(220===t){if(0!==(i=this.readU16())){this.pushArrayState(i),this.complete();continue t}e=[]}else if(221===t){if(0!==(i=this.readU32())){this.pushArrayState(i),this.complete();continue t}e=[]}else if(222===t){if(0!==(i=this.readU16())){this.pushMapState(i),this.complete();continue t}e={}}else if(223===t){if(0!==(i=this.readU32())){this.pushMapState(i),this.complete();continue t}e={}}else if(196===t){var i=this.lookU8();e=this.decodeBinary(i,1)}else if(197===t)i=this.lookU16(),e=this.decodeBinary(i,2);else if(198===t)i=this.lookU32(),e=this.decodeBinary(i,4);else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t)i=this.lookU8(),e=this.decodeExtension(i,1);else if(200===t)i=this.lookU16(),e=this.decodeExtension(i,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+C(t));i=this.lookU32(),e=this.decodeExtension(i,4)}this.complete();for(var r=this.stack;r.length>0;){var s=r[r.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;r.pop(),e=s.array}else{if(1===s.type){if("string"!=(a=typeof e)&&"number"!==a)throw new Error("The type of key must be string or number but "+typeof e);s.key=e,s.type=2;continue t}if(s.map[s.key]=e,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue t}r.pop(),e=s.map}}return e}var a},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new Error("Unrecognized array type byte: "+C(t))}},t.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new Error("Max length exceeded: map length ("+t+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new Error("Max length exceeded: array length ("+t+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:t,array:new Array(t),position:0})},t.prototype.decodeUtf8String=function(t,e){var n;if(t>this.maxStrLength)throw new Error("Max length exceeded: UTF-8 byte length ("+t+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+e+t)throw L;var i,r=this.pos+e;return i=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,r,t):s&&t>u?function(t,e,n){var i=t.subarray(e,e+n);return c.decode(i)}(this.bytes,r,t):d(this.bytes,r,t),this.pos+=e+t,i},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new Error("Max length exceeded: bin length ("+t+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(t+e))throw L;var n=this.pos+e,i=this.bytes.subarray(n,n+t);return this.pos+=e+t,i},t.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new Error("Max length exceeded: ext length ("+t+") > maxExtLength ("+this.maxExtLength+")");var n=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,n,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},t.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},t.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},t.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},t.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},t.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},t.prototype.readU64=function(){var t,e,n=4294967296*(t=this.view).getUint32(e=this.pos)+t.getUint32(e+4);return this.pos+=8,n},t.prototype.readI64=function(){var t=_(this.view,this.pos);return this.pos+=8,t},t.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},t.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},t}(),z={};function G(t,e){void 0===e&&(e=z);var n=new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.setBuffer(t),n.decodeSingleSync()}var $=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},W=function(t){return this instanceof W?(this.v=t,this):new W(t)},j=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(t,e||[]),s=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(t){r[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||o(t,e)})})}function o(t,e){try{(n=r[t](e)).value instanceof W?Promise.resolve(n.value.v).then(l,h):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function H(t){return null!=t[Symbol.asyncIterator]?t:function(t){return j(this,arguments,function(){var e,n,i;return $(this,function(r){switch(r.label){case 0:e=t.getReader(),r.label=1;case 1:r.trys.push([1,,9,10]),r.label=2;case 2:return[4,W(e.read())];case 3:return n=r.sent(),i=n.value,n.done?[4,W(void 0)]:[3,5];case 4:return[2,r.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(i),[4,W(i)];case 6:return[4,r.sent()];case 7:return r.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var V=function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function a(t){try{l(i.next(t))}catch(t){s(t)}}function o(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((i=i.apply(t,e||[])).next())})},K=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}};function Y(t,e){return void 0===e&&(e=z),V(this,void 0,void 0,function(){var n;return K(this,function(i){return n=H(t),[2,new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeSingleAsync(n)]})})}function X(t,e){void 0===e&&(e=z);var n=H(t);return new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeArrayStream(n)}function Z(t,e){void 0===e&&(e=z);var n=H(t);return new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeStream(n)}}])});const PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(t=>{PACKET_TYPES_REVERSE[PACKET_TYPES[t]]=t});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),withNativeArrayBuffer$2="function"==typeof ArrayBuffer,isView$1=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,encodePacket=({type:t,data:e},n,i)=>withNativeBlob$1&&e instanceof Blob?n?i(e):encodeBlobAsBase64(e,i):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?i(e):encodeBlobAsBase64(new Blob([e]),i):i(PACKET_TYPES[t]+(e||"")),encodeBlobAsBase64=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function toArray(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(t,e){return withNativeBlob$1&&t.data instanceof Blob?t.data.arrayBuffer().then(toArray).then(e):withNativeArrayBuffer$2&&(t.data instanceof ArrayBuffer||isView$1(t.data))?e(toArray(t.data)):void encodePacket(t,!1,t=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),e(TEXT_ENCODER.encode(t))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<chars.length;t++)lookup$1[chars.charCodeAt(t)]=t;const decode$1=t=>{let e,n,i,r,s,a=.75*t.length,o=t.length,l=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],i=lookup$1[t.charCodeAt(e+1)],r=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],d[l++]=n<<2|i>>4,d[l++]=(15&i)<<4|r>>2,d[l++]=(3&r)<<6|63&s;return h},withNativeArrayBuffer$1="function"==typeof ArrayBuffer,decodePacket=(t,e)=>{if("string"!=typeof t)return{type:"message",data:mapBinary(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:decodeBase64Packet(t.substring(1),e)}:PACKET_TYPES_REVERSE[n]?t.length>1?{type:PACKET_TYPES_REVERSE[n],data:t.substring(1)}:{type:PACKET_TYPES_REVERSE[n]}:ERROR_PACKET},decodeBase64Packet=(t,e)=>{if(withNativeArrayBuffer$1){const n=decode$1(t);return mapBinary(n,e)}return{base64:!0,data:t}},mapBinary=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,SEPARATOR=String.fromCharCode(30),encodePayload=(t,e)=>{const n=t.length,i=new Array(n);let r=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{i[s]=t,++r===n&&e(i.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),i=[];for(let t=0;t<n.length;t++){const r=decodePacket(n[t],e);if(i.push(r),"error"===r.type)break}return i};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const i=n.length;let r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);const t=new DataView(r.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{r=new Uint8Array(9);const t=new DataView(r.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(n)})}})}let TEXT_DECODER;function totalLength(t){return t.reduce((t,e)=>t+e.length,0)}function concatChunks(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let r=0;r<e;r++)n[r]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let i=0,r=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===i){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(totalLength(n)<2)break;const t=concatChunks(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(totalLength(n)<8)break;const t=concatChunks(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(ERROR_PACKET);break}r=s*Math.pow(2,32)+e.getUint32(4),i=3}else{if(totalLength(n)<r)break;const t=concatChunks(n,r);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),i=0}if(0===r||r>t){o.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(t){if(t)return mixin(t)}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r=0;r<i.length;r++)if((n=i[r])===e||n.fn===e){i.splice(r,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var r=(n=n.slice(0)).length;i<r;++i)n[i].apply(this,e)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};const nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),defaultBinaryType="arraybuffer";function createCookieJar(){}function pick(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(t,e){e.useNativeTimers?(t.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),t.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(t.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),t.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(t){return"string"==typeof t?utf8Length(t):Math.ceil((t.byteLength||t.size)*BASE64_OVERHEAD)}function utf8Length(t){let e=0,n=0;for(let i=0,r=t.length;i<r;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}function randomString(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function encode(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function decode(t){let e={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class TransportError extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Transport extends Emitter{constructor(t){super(),this.writable=!1,installTimerFunctions(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new TransportError(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=decodePacket(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=encode(t);return e.length?"?"+e:""}}class Polling extends Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){decodePayload(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,encodePayload(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let value=!1;try{value="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(err){}const hasCORS=value;function empty(){}class BaseXHR extends Polling{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class Request extends Emitter{constructor(t,e,n){super(),this.createRequest=t,installTimerFunctions(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=pick(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=Request.requestsCount++,Request.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(null!=this._xhr){if(this._xhr.onreadystatechange=empty,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Request.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Request.requestsCount=0,Request.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",unloadHandler);else if("function"==typeof addEventListener){const t="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(t,unloadHandler,!1)}function unloadHandler(){for(let t in Request.requests)Request.requests.hasOwnProperty(t)&&Request.requests[t].abort()}const hasXHR2=function(){const t=newRequest({xdomain:!1});return t&&null!==t.responseType}();class XHR extends BaseXHR{constructor(t){super(t),this.supportsBinary=hasXHR2&&!(t&&t.forceBase64)}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Request(newRequest,this.uri(),t)}}function newRequest(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||hasCORS))return new XMLHttpRequest}catch(t){}if(!e)try{return new(globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class BaseWS extends Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const WebSocketCtor=globalThisShim.WebSocket||globalThisShim.MozWebSocket;class WS extends BaseWS{createSocket(t,e,n){return isReactNative?new WebSocketCtor(t,e,n):e?new WebSocketCtor(t,e):new WebSocketCtor(t)}doWrite(t,e){this.ws.send(e)}}class WT extends Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=createPacketEncoderStream();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const r=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=e===t.length-1;this._writer.write(t[e]).then(()=>{n&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}}const transports={websocket:WS,webtransport:WT,polling:XHR},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let r=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=r[a]||"";return-1!=n&&-1!=i&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=pathNames(s,s.path),s.queryKey=queryKey(s,s.query),s}function pathNames(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}function queryKey(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}const withEventListeners="function"==typeof addEventListener&&"function"==typeof removeEventListener,OFFLINE_EVENT_LISTENERS=[];withEventListeners&&addEventListener("offline",()=>{OFFLINE_EVENT_LISTENERS.forEach(t=>t())},!1);class SocketWithoutUpgrade extends Emitter{constructor(t,e){if(super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=Infinity,t&&"object"==typeof t&&(e=t,t=null),t){const n=parse(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=parse(e.host).host);installTimerFunctions(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=decode(this.opts.query)),withEventListeners&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=createCookieJar()),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=protocol$1,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&SocketWithoutUpgrade.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=byteLength(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,nextTick(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(SocketWithoutUpgrade.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),withEventListeners&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);-1!==t&&OFFLINE_EVENT_LISTENERS.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}SocketWithoutUpgrade.protocol=protocol$1;class SocketWithUpgrade extends SocketWithoutUpgrade{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;SocketWithoutUpgrade.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function r(){n||(n=!0,h(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&r()}const h=()=>{e.removeListener("open",i),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",i),e.once("error",s),e.once("close",a),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}class Socket$1 extends SocketWithUpgrade{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>transports[t]).filter(t=>!!t)),super(t,n)}}function url(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=parse(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+e,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}const withNativeArrayBuffer="function"==typeof ArrayBuffer,isView=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function isBinary(t){return withNativeArrayBuffer&&(t instanceof ArrayBuffer||isView(t))||withNativeBlob&&t instanceof Blob||withNativeFile&&t instanceof File}function hasBinary(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(hasBinary(t[e]))return!0;return!1}if(isBinary(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return hasBinary(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&hasBinary(t[e]))return!0;return!1}function deconstructPacket(t){const e=[],n=t;return n.data=_deconstructPacket(t.data,e),n.attachments=e.length,{packet:n,buffers:e}}function _deconstructPacket(t,e){if(!t)return t;if(isBinary(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=_deconstructPacket(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=_deconstructPacket(t[i],e));return n}return t}function reconstructPacket(t,e){return t.data=_reconstructPacket(t.data,e),delete t.attachments,t}function _reconstructPacket(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=_reconstructPacket(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=_reconstructPacket(t[n],e));return t}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(PacketType||(PacketType={}));class Encoder{constructor(t){this.replacer=t}encode(t){return t.type!==PacketType.EVENT&&t.type!==PacketType.ACK||!hasBinary(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==PacketType.BINARY_EVENT&&t.type!==PacketType.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=deconstructPacket(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}function isObject(t){return"[object Object]"===Object.prototype.toString.call(t)}class Decoder extends Emitter{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===PacketType.BINARY_EVENT;n||e.type===PacketType.BINARY_ACK?(e.type=n?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!isBinary(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===PacketType[n.type])throw new Error("unknown packet type "+n.type);if(n.type===PacketType.BINARY_EVENT||n.type===PacketType.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const r=t.substring(i,e);if(r!=Number(r)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(r)}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case PacketType.CONNECT:return isObject(e);case PacketType.DISCONNECT:return void 0===e;case PacketType.CONNECT_ERROR:return"string"==typeof e||isObject(e);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===RESERVED_EVENTS$1.indexOf(e[0]));case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var parser={__proto__:null,protocol,get PacketType(){return PacketType},Encoder,Decoder};function on(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[on(t,"open",this.onopen.bind(this)),on(t,"packet",this.onpacket.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,i,r;if(RESERVED_EVENTS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:PacketType.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const a=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,o=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),s=(...t)=>{this.io.clearTimeoutFn(r),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,i)=>{const r=(t,e)=>t?i(t):n(e);r.withError=!0,e.push(r),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{if(n===this._queue[0])return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(t);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(t);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...i){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function Backoff(t){this.ms=(t=t||{}).min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};class Manager extends Emitter{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,installTimerFunctions(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||Infinity),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||parser;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=on(e,"open",function(){n.onopen(),t&&t()}),r=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",r);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(i),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(on(t,"ping",this.onping.bind(this)),on(t,"data",this.ondata.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){nextTick(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Socket(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cache={};function lookup(t,e){"object"==typeof t&&(e=t,t=void 0);const n=url(t,(e=e||{}).path||"/socket.io"),i=n.source,r=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[r]&&n.path in cache[r].nsps?s=new Manager(i,e):(cache[r]||(cache[r]=new Manager(i,e)),s=cache[r]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;Object.assign(lookup,{Manager,Socket,io:lookup,connect:lookup}),function(rt){var r,e,i;r={1:[function(t,e,n){e.exports=function(t,e){for(var n=Array(arguments.length-1),i=0,r=2,s=!0;r<arguments.length;)n[i++]=arguments[r++];return new Promise(function(r,a){n[i]=function(t){if(s)if(s=!1,t)a(t);else{for(var e=Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];r.apply(null,e)}};try{t.apply(e||null,n)}catch(t){s&&(s=!1,a(t))}})}},{}],2:[function(t,e,n){n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;1<--e%4&&"="==(t[0|e]||"");)++n;return Math.ceil(3*t.length)/4-n};for(var i=Array(64),r=Array(123),s=0;s<64;)r[i[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(t,e,n){for(var r,s=null,a=[],o=0,l=0;e<n;){var h=t[e++];switch(l){case 0:a[o++]=i[h>>2],r=(3&h)<<4,l=1;break;case 1:a[o++]=i[r|h>>4],r=(15&h)<<2,l=2;break;case 2:a[o++]=i[r|h>>6],a[o++]=i[63&h],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=i[r],a[o++]=61,1===l&&(a[o++]=61)),s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))};var a="invalid encoding";n.decode=function(t,e,n){for(var i,s=n,o=0,l=0;l<t.length;){var h=t.charCodeAt(l++);if(61==h&&1<o)break;if((h=r[h])===rt)throw Error(a);switch(o){case 0:i=h,o=1;break;case 1:e[n++]=i<<2|(48&h)>>4,i=h,o=2;break;case 2:e[n++]=(15&i)<<4|(60&h)>>2,i=h,o=3;break;case 3:e[n++]=(3&i)<<6|h,o=0}}if(1===o)throw Error(a);return n-s},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,e,n){(e.exports=function t(e,n){"string"==typeof e&&(n=e,e=rt);var i=[];function r(e){if("string"!=typeof e){var n=s();if(t.verbose&&console.log("codegen: "+n),n="return "+n,e){for(var a=Object.keys(e),o=Array(a.length+1),l=Array(a.length),h=0;h<a.length;)o[h]=a[h],l[h]=e[a[h++]];return o[h]=n,Function.apply(null,o).apply(null,l)}return Function(n)()}for(var d=Array(arguments.length-1),c=0;c<d.length;)d[c]=arguments[++c];if(c=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=d[c++];switch(e){case"d":case"f":return""+ +(""+n);case"i":return""+Math.floor(n);case"j":return JSON.stringify(n);case"s":return""+n}return"%"}),c!==d.length)throw Error("parameter count mismatch");return i.push(e),r}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+i.join("\n ")+"\n}"}return r.toString=s,r}).verbose=!1},{}],4:[function(t,e,n){function i(){this.i={}}(e.exports=i).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},i.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],i=0;i<n.length;)n[i].fn===e?n.splice(i,1):++i;return this},i.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<e.length;)e[i].fn.apply(e[i++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var i=t(1),r=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&r&&r.readFile?r.readFile(t,function(i,r){return i&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):i?n(i):n(null,e.binary?r:r.toString("utf8"))}):s.xhr(t,e,n):i(s,this,t,e)}s.xhr=function(t,e,n){var i=new XMLHttpRequest;i.onreadystatechange=function(){if(4!==i.readyState)return rt;if(0!==i.status&&200!==i.status)return n(Error("status "+i.status));if(e.binary){if(!(t=i.response))for(var t=[],r=0;r<i.responseText.length;++r)t.push(255&i.responseText.charCodeAt(r));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,i.responseText)},e.binary&&("overrideMimeType"in i&&i.overrideMimeType("text/plain; charset=x-user-defined"),i.responseType="arraybuffer"),i.open("GET",t),i.send()}},{1:1,7:7}],6:[function(t,e,n){function i(t){function e(t,e,n,i){var r=e<0?1:0;t(0===(e=r?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(r<<31|2139095040)>>>0:e<11754943508222875e-54?(r<<31|Math.round(e/1401298464324817e-60))>>>0:(r<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,i)}function n(t,e,n){return e=2*((t=t(e,n))>>31)+1,n=t>>>23&255,t&=8388607,255==n?t?NaN:1/0*e:0==n?1401298464324817e-60*e*t:e*Math.pow(2,n-150)*(8388608+t)}function i(t,e,n){c[0]=t,e[n]=u[0],e[n+1]=u[1],e[n+2]=u[2],e[n+3]=u[3]}function l(t,e,n){c[0]=t,e[n]=u[3],e[n+1]=u[2],e[n+2]=u[1],e[n+3]=u[0]}function h(t,e){return u[0]=t[e],u[1]=t[e+1],u[2]=t[e+2],u[3]=t[e+3],c[0]}function d(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],c[0]}var c,u,f,p,_;function m(t,e,n,i,r,s){var a,o=i<0?1:0;0===(i=o?-i:i)?(t(0,r,s+e),t(0<1/i?0:2147483648,r,s+n)):isNaN(i)?(t(0,r,s+e),t(2146959360,r,s+n)):17976931348623157e292<i?(t(0,r,s+e),t((o<<31|2146435072)>>>0,r,s+n)):i<22250738585072014e-324?(t((a=i/5e-324)>>>0,r,s+e),t((o<<31|a/4294967296)>>>0,r,s+n)):(t(4503599627370496*(a=i*Math.pow(2,-(i=1024===(i=Math.floor(Math.log(i)/Math.LN2))?1023:i)))>>>0,r,s+e),t((o<<31|i+1023<<20|1048576*a&1048575)>>>0,r,s+n))}function g(t,e,n,i,r){return e=t(i,r+e),i=2*((t=t(i,r+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(r=t>>>20&2047)?n?NaN:1/0*i:0==r?5e-324*i*n:i*Math.pow(2,r-1075)*(n+4503599627370496)}function y(t,e,n){f[0]=t,e[n]=p[0],e[n+1]=p[1],e[n+2]=p[2],e[n+3]=p[3],e[n+4]=p[4],e[n+5]=p[5],e[n+6]=p[6],e[n+7]=p[7]}function v(t,e,n){f[0]=t,e[n]=p[7],e[n+1]=p[6],e[n+2]=p[5],e[n+3]=p[4],e[n+4]=p[3],e[n+5]=p[2],e[n+6]=p[1],e[n+7]=p[0]}function b(t,e){return p[0]=t[e],p[1]=t[e+1],p[2]=t[e+2],p[3]=t[e+3],p[4]=t[e+4],p[5]=t[e+5],p[6]=t[e+6],p[7]=t[e+7],f[0]}function S(t,e){return p[7]=t[e],p[6]=t[e+1],p[5]=t[e+2],p[4]=t[e+3],p[3]=t[e+4],p[2]=t[e+5],p[1]=t[e+6],p[0]=t[e+7],f[0]}return"undefined"!=typeof Float32Array?(c=new Float32Array([-0]),u=new Uint8Array(c.buffer),t.writeFloatLE=(_=128===u[3])?i:l,t.writeFloatBE=_?l:i,t.readFloatLE=_?h:d,t.readFloatBE=_?d:h):(t.writeFloatLE=e.bind(null,r),t.writeFloatBE=e.bind(null,s),t.readFloatLE=n.bind(null,a),t.readFloatBE=n.bind(null,o)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),p=new Uint8Array(f.buffer),t.writeDoubleLE=(_=128===p[7])?y:v,t.writeDoubleBE=_?v:y,t.readDoubleLE=_?b:S,t.readDoubleBE=_?S:b):(t.writeDoubleLE=m.bind(null,r,0,4),t.writeDoubleBE=m.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function r(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function s(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function a(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}e.exports=i(i)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,e,n){var i=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=i(t);t="",n&&(t=e.shift()+"/");for(var r=0;r<e.length;)".."===e[r]?0<r&&".."!==e[r-1]?e.splice(--r,2):n?e.splice(r,1):++r:"."===e[r]?e.splice(r,1):++r;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=r(e)),!i(e)&&(t=(t=n?t:r(t)).replace(/(?:\/|^)[^/]+$/,"")).length?r(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var i=n||8192,r=i>>>1,s=null,a=i;return function(n){return n<1||r<n?t(n):(i<a+n&&(s=t(i),a=0),n=e.call(s,a,a+=n),7&a&&(a=1+(7|a)),n)}}},{}],10:[function(t,e,n){n.length=function(t){for(var e,n=0,i=0;i<t.length;++i)(e=t.charCodeAt(i))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(i+1))?(++i,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var i,r=null,s=[],a=0;e<n;)(i=t[e++])<128?s[a++]=i:191<i&&i<224?s[a++]=(31&i)<<6|63&t[e++]:239<i&&i<365?(i=((7&i)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(i>>10),s[a++]=56320+(1023&i)):s[a++]=(15&i)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((r=r||[]).push(String.fromCharCode.apply(String,s)),a=0);return r?(a&&r.push(String.fromCharCode.apply(String,s.slice(0,a))),r.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var i,r,s=n,a=0;a<t.length;++a)(i=t.charCodeAt(a))<128?e[n++]=i:(i<2048?e[n++]=i>>6|192:(55296==(64512&i)&&56320==(64512&(r=t.charCodeAt(a+1)))?(++a,e[n++]=(i=65536+((1023&i)<<10)+(1023&r))>>18|240,e[n++]=i>>12&63|128):e[n++]=i>>12|224,e[n++]=i>>6&63|128),e[n++]=63&i|128);return n-s}},{}],11:[function(t,e,n){e.exports=r;var i=/\/|\./;function r(t,e){i.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),r[t]=e}r("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),r("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),r("timestamp",{Timestamp:e}),r("empty",{Empty:{fields:{}}}),r("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),r("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),r("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),r.get=function(t){return r[t]||null}},{}],12:[function(t,e,n){var i=t(15),r=t(37);function s(t,e,n,r){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof i){t("switch(d%s){",r);for(var a=e.resolvedType.values,o=Object.keys(a),l=0;l<o.length;++l)a[o[l]]!==e.typeDefault||s||(t("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',r,r,r),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",r,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',r)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",r,n,r);else{var h=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",r,r);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":h=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,h)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function a(t,e,n,r){if(e.resolvedType)e.resolvedType instanceof i?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,s?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=r.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!e.length)return n("return new this.ctor");n("var m=new this.ctor");for(var a=0;a<e.length;++a){var o=e[a].resolve(),l=r.safeProp(o.name);o.map?(n("if(d%s){",l)('if(typeof d%s!=="object")',l)("throw TypeError(%j)",o.fullName+": object expected")("m%s={}",l)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",l),s(n,o,a,l+"[ks[i]]")("}")("}")):o.repeated?(n("if(d%s){",l)("if(!Array.isArray(d%s))",l)("throw TypeError(%j)",o.fullName+": array expected")("m%s=[]",l)("for(var i=0;i<d%s.length;++i){",l),s(n,o,a,l+"[i]")("}")("}")):(o.resolvedType instanceof i||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof i||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(r.compareFieldsById);if(!e.length)return r.codegen()("return {}");for(var n=r.codegen(["m","o"],t.name+"$toObject")("if(!o)")("o={}")("var d={}"),s=[],o=[],l=[],h=0;h<e.length;++h)e[h].partOf||(e[h].resolve().repeated?s:e[h].map?o:l).push(e[h]);if(s.length){for(n("if(o.arrays||o.defaults){"),h=0;h<s.length;++h)n("d%s=[]",r.safeProp(s[h].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),h=0;h<o.length;++h)n("d%s={}",r.safeProp(o[h].name));n("}")}if(l.length){for(n("if(o.defaults){"),h=0;h<l.length;++h){var d,c=r.safeProp((f=l[h]).name);f.resolvedType instanceof i?n("d%s=o.enums===String?%j:%j",c,f.resolvedType.valuesById[f.typeDefault],f.typeDefault):f.long?n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",f.typeDefault.low,f.typeDefault.high,f.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",c)("}else")("d%s=o.longs===String?%j:%i",c,f.typeDefault.toString(),f.typeDefault.toNumber()):f.bytes?(d="["+Array.prototype.slice.call(f.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",c,String.fromCharCode.apply(String,f.typeDefault))("else{")("d%s=%s",c,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",c,c)("}")):n("d%s=%j",c,f.typeDefault)}n("}")}var u=!1;for(h=0;h<e.length;++h){var f,p=t.e.indexOf(f=e[h]);c=r.safeProp(f.name),f.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",c,c)("d%s={}",c)("for(var j=0;j<ks2.length;++j){"),a(n,f,p,c+"[ks2[j]]")("}")):f.repeated?(n("if(m%s&&m%s.length){",c,c)("d%s=[]",c)("for(var j=0;j<m%s.length;++j){",c),a(n,f,p,c+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",c,f.name),a(n,f,p,c),f.partOf&&n("if(o.oneofs)")("d%s=%j",r.safeProp(f.partOf.name),f.name)),n("}")}return n("return d")}},{15:15,37:37}],13:[function(t,e,n){e.exports=function(t){for(var e=s.codegen(["r","l","e"],t.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(t.fieldsArray.filter(function(t){return t.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),n=0;n<t.fieldsArray.length;++n){var a=t.e[n].resolve(),o=a.resolvedType instanceof i?"int32":a.type,l="m"+s.safeProp(a.name);e("case %i: {",a.id),a.map?(e("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),r.defaults[a.keyType]!==rt?e("k=%j",r.defaults[a.keyType]):e("k=null"),r.defaults[o]!==rt?e("value=%j",r.defaults[o]):e("value=null"),e("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),r.basic[o]===rt?e("value=types[%i].decode(r,r.uint32())",n):e("value=r.%s()",o),e("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),e(r.long[a.keyType]!==rt?'%s[typeof k==="object"?util.longToHash(k):k]=value':"%s[k]=value",l)):a.repeated?(e("if(!(%s&&%s.length))",l,l)("%s=[]",l),r.packed[o]!==rt&&e("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,o)("}else"),r.basic[o]===rt?e(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,n):e("%s.push(r.%s())",l,o)):r.basic[o]===rt?e(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,n):e("%s=r.%s()",l,o),e("break")("}")}for(e("default:")("r.skipType(t&7)")("break")("}")("}"),n=0;n<t.e.length;++n){var h=t.e[n];h.required&&e("if(!m.hasOwnProperty(%j))",h.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+h.name+"'")}return e("return m")};var i=t(15),r=t(36),s=t(37)},{15:15,36:36,37:37}],14:[function(t,e,n){e.exports=function(t){for(var e,n=s.codegen(["m","w"],t.name+"$encode")("if(!w)")("w=Writer.create()"),o=t.fieldsArray.slice().sort(s.compareFieldsById),l=0;l<o.length;++l){var h=o[l].resolve(),d=t.e.indexOf(h),c=h.resolvedType instanceof i?"int32":h.type,u=r.basic[c];e="m"+s.safeProp(h.name),h.map?(n("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",e,h.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",e)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(h.id<<3|2)>>>0,8|r.mapKey[h.keyType],h.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",d,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,c,e),n("}")("}")):h.repeated?(n("if(%s!=null&&%s.length){",e,e),h.packed&&r.packed[c]!==rt?n("w.uint32(%i).fork()",(h.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",c,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,h,d,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(h.id<<3|u)>>>0,c,e)),n("}")):(h.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,h.name),u===rt?a(n,h,d,e):n("w.uint32(%i).%s(%s)",(h.id<<3|u)>>>0,c,e))}return n("return w")};var i=t(15),r=t(36),s=t(37);function a(t,e,n,i){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,i,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,i,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var i=t(24),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,r,s,a){if(i.call(this,t,n),e&&"object"!=typeof e)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=s||{},this.valuesOptions=a,this.o={},this.reserved=rt,e)for(var o=Object.keys(e),l=0;l<o.length;++l)"number"==typeof e[o[l]]&&(this.valuesById[this.values[o[l]]=e[o[l]]]=o[l])}a.prototype.u=function(t){return i.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(t=>{var e=Object.assign({},this.h);this.o[t]=Object.assign(e,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},a.fromJSON=function(t,e){return(t=new a(t,e.values,e.options,e.comment,e.comments)).reserved=e.reserved,e.edition&&(t.f=e.edition),t.a="proto3",t},a.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,s.toObject(["edition",this.c(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"comment",t?this.comment:rt,"comments",t?this.comments:rt])},a.prototype.add=function(t,e,n,i){if(!s.isString(t))throw TypeError("name must be a string");if(!s.isInteger(e))throw TypeError("id must be an integer");if(this.values[t]!==rt)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(e))throw Error("id "+e+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[e]!==rt){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+e+" in "+this);this.values[t]=e}else this.valuesById[this.values[t]=e]=t;return i&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=i||null),this.comments[t]=n||null,this},a.prototype.remove=function(t){if(!s.isString(t))throw TypeError("name must be a string");var e=this.values[t];if(null==e)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[e],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},a.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=h;var i,r=t(24),s=(((h.prototype=Object.create(r.prototype)).constructor=h).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function h(t,e,n,i,s,h,d){if(o.isObject(i)?(d=s,h=i,i=s=rt):o.isObject(s)&&(d=h,h=s,s=rt),r.call(this,t,h),!o.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!o.isString(n))throw TypeError("type must be a string");if(i!==rt&&!l.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(s!==rt&&!o.isString(s))throw TypeError("extend must be a string");this.rule=(i="proto3_optional"===i?"optional":i)&&"optional"!==i?i:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!o.Long&&a.long[n]!==rt,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=d}h.fromJSON=function(t,e){return t=new h(t,e.id,e.type,e.rule,e.extend,e.options,e.comment),e.edition&&(t.f=e.edition),t.a="proto3",t},Object.defineProperty(h.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.h.field_presence}}),Object.defineProperty(h.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(h.prototype,"delimited",{get:function(){return this.resolvedType instanceof i&&"DELIMITED"===this.h.message_encoding}}),Object.defineProperty(h.prototype,"packed",{get:function(){return"PACKED"===this.h.repeated_field_encoding}}),Object.defineProperty(h.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.h.field_presence)}}),h.prototype.setOption=function(t,e,n){return r.prototype.setOption.call(this,t,e,n)},h.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,o.toObject(["edition",this.c(),"rule","optional"!==this.rule&&this.rule||rt,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},h.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===rt?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.typeDefault=this.resolvedType instanceof i?null:this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===rt||!this.resolvedType||this.resolvedType instanceof s||delete this.options.packed,Object.keys(this.options).length||(this.options=rt)),this.long?(this.typeDefault=o.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(o.base64.test(this.typeDefault)?o.base64.decode(this.typeDefault,t=o.newBuffer(o.base64.length(this.typeDefault)),0):o.utf8.write(this.typeDefault,t=o.newBuffer(o.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.defaultValue=this.map?o.emptyObject:this.repeated?o.emptyArray:this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),r.prototype.resolve.call(this))},h.prototype.l=function(t){var e;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&a.defaults[this.type]===rt&&(e=this.parent.get(this.type.split(".").pop()))&&e instanceof i&&e.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},h.prototype.u=function(t){return r.prototype.u.call(this,this.f||t)},h.d=function(t,e,n,i){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(r,s){o.decorateType(r.constructor).add(new h(s,t,e,n,{default:i}))}},h.p=function(t){i=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var i=e.exports=t(18);i.build="light",i.load=function(t,e,n){return(e="function"==typeof e?(n=e,new i.Root):e||new i.Root).load(t,n)},i.loadSync=function(t,e){return(e=e||new i.Root).loadSync(t)},i.encoder=t(14),i.decoder=t(13),i.verifier=t(40),i.converter=t(12),i.ReflectionObject=t(24),i.Namespace=t(23),i.Root=t(29),i.Enum=t(15),i.Type=t(35),i.Field=t(16),i.OneOf=t(25),i.MapField=t(20),i.Service=t(33),i.Method=t(22),i.Message=t(21),i.wrappers=t(41),i.types=t(36),i.util=t(37),i.ReflectionObject.p(i.Root),i.Namespace.p(i.Type,i.Service,i.Enum),i.Root.p(i.Type),i.Field.p(i.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,e,n){var i=n;function r(){i.util.p(),i.Writer.p(i.BufferWriter),i.Reader.p(i.BufferReader)}i.build="minimal",i.Writer=t(42),i.BufferWriter=t(43),i.Reader=t(27),i.BufferReader=t(28),i.util=t(39),i.rpc=t(31),i.roots=t(30),i.configure=r,r()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,e,n){(e=e.exports=t(17)).build="full",e.tokenize=t(34),e.parse=t(26),e.common=t(11),e.Root.p(e.Type,e.parse,e.common)},{11:11,17:17,26:26,34:34}],20:[function(t,e,n){e.exports=a;var i=t(16),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,r,a,o){if(i.call(this,t,e,r,rt,rt,a,o),!s.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(t,e){return new a(t,e.id,e.keyType,e.type,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.resolve=function(){if(this.resolved)return this;if(r.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return i.prototype.resolve.call(this)},a.d=function(t,e,n){return"function"==typeof n?n=s.decorateType(n).name:n&&"object"==typeof n&&(n=s.decorateEnum(n).name),function(i,r){s.decorateType(i.constructor).add(new a(r,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=r;var i=t(39);function r(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}r.create=function(t){return this.$type.create(t)},r.encode=function(t,e){return this.$type.encode(t,e)},r.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},r.decode=function(t){return this.$type.decode(t)},r.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},r.verify=function(t){return this.$type.verify(t)},r.fromObject=function(t){return this.$type.fromObject(t)},r.toObject=function(t,e){return this.$type.toObject(t,e)},r.prototype.toJSON=function(){return this.$type.toObject(this,i.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var i=t(24),r=(((s.prototype=Object.create(i.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,h,d){if(r.isObject(a)?(l=a,a=o=rt):r.isObject(o)&&(l=o,o=rt),e!==rt&&!r.isString(e))throw TypeError("type must be a string");if(!r.isString(n))throw TypeError("requestType must be a string");if(!r.isString(s))throw TypeError("responseType must be a string");i.call(this,t,l),this.type=e||"rpc",this.requestType=n,this.requestStream=!!a||rt,this.responseType=s,this.responseStream=!!o||rt,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=h,this.parsedOptions=d}s.fromJSON=function(t,e){return new s(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment,e.parsedOptions)},s.prototype.toJSON=function(t){return r.toObject(["type","rpc"!==this.type&&this.type||rt,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),i.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=c;var i,r,s,a=t(24),o=(((c.prototype=Object.create(a.prototype)).constructor=c).className="Namespace",t(16)),l=t(37),h=t(25);function d(t,e){if(!t||!t.length)return rt;for(var n={},i=0;i<t.length;++i)n[t[i].name]=t[i].toJSON(e);return n}function c(t,e){a.call(this,t,e),this.nested=rt,this.v=null,this.b={},this.w=!0,this.y=!0}function u(t){t.v=null,t.b={};for(var e=t;e=e.parent;)e.b={};return t}c.fromJSON=function(t,e){return new c(t,e.options).addJSON(e.nested)},c.arrayToJSON=d,c.isReservedId=function(t,e){if(t)for(var n=0;n<t.length;++n)if("string"!=typeof t[n]&&t[n][0]<=e&&t[n][1]>e)return!0;return!1},c.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),c.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",d(this.nestedArray,t)])},c.prototype.addJSON=function(t){if(t)for(var e,n=Object.keys(t),a=0;a<n.length;++a)this.add(((e=t[n[a]]).fields!==rt?i:e.values!==rt?s:e.methods!==rt?r:e.id!==rt?o:c).fromJSON(n[a],e));return this},c.prototype.get=function(t){return this.nested&&this.nested[t]||null},c.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},c.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof i||t instanceof h||t instanceof s||t instanceof r||t instanceof c))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof c&&t instanceof c)||e instanceof i||e instanceof r)throw Error("duplicate name '"+t.name+"' in "+this);for(var n=e.nestedArray,a=0;a<n.length;++a)t.add(n[a]);this.remove(e),this.nested||(this.nested={}),t.setOptions(e.options,!0)}}else this.nested={};this.nested[t.name]=t,this instanceof i||this instanceof r||this instanceof s||this instanceof o||t.f||(t.f=t.a),this.w=!0,this.y=!0;for(var l=this;l=l.parent;)l.w=!0,l.y=!0;return t.onAdd(this),u(this)},c.prototype.remove=function(t){if(!(t instanceof a))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=rt),t.onRemove(this),u(this)},c.prototype.define=function(t,e){if(l.isString(t))t=t.split(".");else if(!Array.isArray(t))throw TypeError("illegal path");if(t&&t.length&&""===t[0])throw Error("path must be relative");for(var n=this;0<t.length;){var i=t.shift();if(n.nested&&n.nested[i]){if(!((n=n.nested[i])instanceof c))throw Error("path conflicts with non-namespace objects")}else n.add(n=new c(i))}return e&&n.addJSON(e),n},c.prototype.resolveAll=function(){if(this.y){this.g(this.f);var t=this.nestedArray,e=0;for(this.resolve();e<t.length;)t[e]instanceof c?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},c.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(e=>{e.g(t)})),this},c.prototype.lookup=function(t,e,n){if("boolean"==typeof e?(n=e,e=rt):e&&!Array.isArray(e)&&(e=[e]),l.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var i=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var r=this.root.j&&this.root.j["."+i];if(r&&(!e||~e.indexOf(r.constructor)))return r;if((r=this.k(t,i))&&(!e||~e.indexOf(r.constructor)))return r;if(!n)for(var s=this;s.parent;){if((r=s.parent.k(t,i))&&(!e||~e.indexOf(r.constructor)))return r;s=s.parent}return null},c.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),i=null;if(n)1===t.length?i=n:n instanceof c&&(t=t.slice(1),i=n.k(t,t.join(".")));else for(var r=0;r<this.nestedArray.length;++r)this.v[r]instanceof c&&(n=this.v[r].k(t,e))&&(i=n);return this.b[e]=i},c.prototype.lookupType=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such type: "+t)},c.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},c.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[i,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},c.prototype.lookupService=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},c.p=function(t,e,n){i=t,r=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=h).className="ReflectionObject";const i=t(25);var r,s=t(37),a={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},o={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},l={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function h(t,e){if(!s.isString(t))throw TypeError("name must be a string");if(e&&!s.isObject(e))throw TypeError("options must be an object");this.options=e,this.parsedOptions=null,this.name=t,this.f=null,this.a="proto2",this.h={},this.O=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(h.prototype,{root:{get:function(){for(var t=this;null!==t.parent;)t=t.parent;return t}},fullName:{get:function(){for(var t=[this.name],e=this.parent;e;)t.unshift(e.name),e=e.parent;return t.join(".")}}}),h.prototype.toJSON=function(){throw Error()},h.prototype.onAdd=function(t){this.parent&&this.parent!==t&&this.parent.remove(this),this.parent=t,this.resolved=!1,(t=t.root)instanceof r&&t.A(this)},h.prototype.onRemove=function(t){(t=t.root)instanceof r&&t.T(this),this.parent=null,this.resolved=!1},h.prototype.resolve=function(){return this.resolved||this.root instanceof r&&(this.resolved=!0),this},h.prototype.g=function(t){return this.u(this.f||t)},h.prototype.u=function(t){if(!this.O){var e={};if(!t)throw Error("Unknown edition for "+this.fullName);var n=Object.assign(this.options?Object.assign({},this.options.features):{},this.l(t));if(this.f){if("proto2"===t)e=Object.assign({},o);else if("proto3"===t)e=Object.assign({},l);else{if("2023"!==t)throw Error("Unknown edition: "+t);e=Object.assign({},a)}this.h=Object.assign(e,n||{})}else{if(this.partOf instanceof i)t=Object.assign({},this.partOf.h),this.h=Object.assign(t,n||{});else if(!this.declaringField){if(!this.parent)throw Error("Unable to find a parent for "+this.fullName);e=Object.assign({},this.parent.h),this.h=Object.assign(e,n||{})}this.extensionField&&(this.extensionField.h=this.h)}this.O=!0}},h.prototype.l=function(){return{}},h.prototype.getOption=function(t){return this.options?this.options[t]:rt},h.prototype.setOption=function(t,e,n){return this.options||(this.options={}),/^features\./.test(t)?s.setProperty(this.options,t,e,n):n&&this.options[t]!==rt||(this.getOption(t)!==e&&(this.resolved=!1),this.options[t]=e),this},h.prototype.setParsedOption=function(t,e,n){this.parsedOptions||(this.parsedOptions=[]);var i,r,a=this.parsedOptions;return n?(i=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(r=i[t],n,e):((i={})[t]=s.setProperty({},n,e),a.push(i)):((r={})[t]=e,a.push(r)),this},h.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),i=0;i<n.length;++i)this.setOption(n[i],t[n[i]],e);return this},h.prototype.toString=function(){var t=this.constructor.className,e=this.fullName;return e.length?t+" "+e:t},h.prototype.c=function(){return this.f&&"proto3"!==this.f?this.f:rt},h.p=function(t){r=t}},{25:25,37:37}],25:[function(t,e,n){e.exports=a;var i=t(24),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,r){if(Array.isArray(e)||(n=e,e=rt),i.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=r}function o(t){if(t.parent)for(var e=0;e<t.fieldsArray.length;++e)t.fieldsArray[e].parent||t.parent.add(t.fieldsArray[e])}a.fromJSON=function(t,e){return new a(t,e.oneof,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["options",this.options,"oneof",this.oneof,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.add=function(t){if(t instanceof r)return t.parent&&t.parent!==this.parent&&t.parent.remove(t),this.oneof.push(t.name),this.fieldsArray.push(t),o(t.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(t){if(!(t instanceof r))throw TypeError("field must be a Field");var e=this.fieldsArray.indexOf(t);if(e<0)throw Error(t+" is not a member of "+this);return this.fieldsArray.splice(e,1),-1<(e=this.oneof.indexOf(t.name))&&this.oneof.splice(e,1),t.partOf=null,this},a.prototype.onAdd=function(t){i.prototype.onAdd.call(this,t);for(var e=0;e<this.oneof.length;++e){var n=t.get(this.oneof[e]);n&&!n.partOf&&(n.partOf=this).fieldsArray.push(n)}o(this)},a.prototype.onRemove=function(t){for(var e,n=0;n<this.fieldsArray.length;++n)(e=this.fieldsArray[n]).parent&&e.parent.remove(e);i.prototype.onRemove.call(this,t)},Object.defineProperty(a.prototype,"isProto3Optional",{get:function(){var t;return null!=this.fieldsArray&&1===this.fieldsArray.length&&null!=(t=this.fieldsArray[0]).options&&!0===t.options.proto3_optional}}),a.d=function(){for(var t=Array(arguments.length),e=0;e<arguments.length;)t[e]=arguments[e++];return function(e,n){s.decorateType(e.constructor).add(new a(n,t)),Object.defineProperty(e,n,{get:s.oneOfGetter(t),set:s.oneOfSetter(t)})}}},{16:16,24:24,37:37}],26:[function(t,e,n){(e.exports=x).filename=null,x.defaults={keepCase:!1};var i=t(34),r=t(29),s=t(35),a=t(16),o=t(20),l=t(25),h=t(15),d=t(33),c=t(22),u=t(24),f=t(36),p=t(37),_=/^[1-9][0-9]*$/,m=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,b=/^-?0[0-7]+$/,S=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,w=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function x(t,e,n){e instanceof r||(n=e,e=new r);var T,A,R,B,C,k,I=(n=n||x.defaults).preferTrailingComment||!1,P=i(t,n.alternateCommentMode||!1),D=P.next,U=P.push,O=P.peek,F=P.skip,L=P.cmnt,M=!0,N="proto2",z=e,G=[],$={},W=n.keepCase?function(t){return t}:p.camelCase;function j(t,e,n){var i=x.filename;return n||(x.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(i?i+", ":"")+"line "+P.line+")")}function H(){var t,e=[];do{if('"'!==(t=D())&&"'"!==t)throw j(t)}while(e.push(D()),F(t),'"'===(t=O())||"'"===t);return e.join("")}function V(t){var e=D();switch(e){case"'":case'"':return U(e),H();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,i=1;switch("-"==(n[0]||"")&&(i=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return i*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(_.test(n))return i*parseInt(n,10);if(g.test(n))return i*parseInt(n,16);if(v.test(n))return i*parseInt(n,8);if(S.test(n))return i*parseFloat(n);throw j(n,"number",!0)}catch(n){if(t&&w.test(e))return e;throw j(e,"value")}}function K(t,e){var n;do{if(!e||'"'!==(i=O())&&"'"!==i)try{t.push([n=Y(D()),F("to",!0)?Y(D()):n])}catch(n){if(!(e&&w.test(i)&&2023<=N))throw n;t.push(i)}else{var i=H();if(t.push(i),2023<=N)throw j(i,"id")}}while(F(",",!0));var r={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};Z(r,function(t){if("option"!==t)throw j(t);tt(r,t),F(";")},function(){nt(r)})}function Y(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(m.test(t))return parseInt(t,10);if(y.test(t))return parseInt(t,16);if(b.test(t))return parseInt(t,8)}throw j(t,"id")}function X(t,e){switch(e){case"option":return tt(t,e),F(";"),1;case"message":return q(t),1;case"enum":return J(t),1;case"service":var n,i,r=t;if(E.test(i=D()))return Z(n=new d(i),function(t){if(!X(n,t)){if("rpc"!==t)throw j(t);var e=n,i=L(),r=t;if(!E.test(t=D()))throw j(t,"name");var s,a,o,l=t;if(F("("),F("stream",!0)&&(a=!0),!w.test(t=D()))throw j(t);if(s=t,F(")"),F("returns"),F("("),F("stream",!0)&&(o=!0),!w.test(t=D()))throw j(t);F(")");var h=new c(l,r,s,t,a,o);h.comment=i,Z(h,function(t){if("option"!==t)throw j(t);tt(h,t),F(";")}),e.add(h)}}),r.add(n),r===z&&G.push(n),1;throw j(i,"service name");case"extend":var s,a=t;if(r=e,w.test(r=D()))return s=r,Z(null,function(t){switch(t){case"required":case"repeated":Q(a,t,s);break;case"optional":Q(a,"proto3"===N?"proto3_optional":"optional",s);break;default:if("proto2"===N||!w.test(t))throw j(t);U(t),Q(a,"optional",s)}}),1;throw j(r,"reference")}}function Z(t,e,n){var i,r=P.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=x.filename),F("{",!0)){for(;"}"!==(i=D());)e(i);F(";",!0)}else n&&n(),F(";"),t&&("string"!=typeof t.comment||I)&&(t.comment=L(r)||t.comment)}function q(t,e){if(!E.test(e=D()))throw j(e,"type name");var n=new s(e);Z(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,i=(F("<"),D());if(f.mapKey[i]===rt)throw j(i,"type");F(",");var r=D();if(!w.test(r))throw j(r,"type");F(">");var s=D();if(!E.test(s))throw j(s,"name");F("=");var a=new o(W(s),Y(D()),i,r);Z(a,function(t){if("option"!==t)throw j(t);tt(a,t),F(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==N)throw j(t);case"repeated":Q(n,t);break;case"optional":if("proto3"===N)Q(n,"proto3_optional");else{if("proto2"!==N)throw j(t);Q(n,"optional")}break;case"oneof":if(s=n,i=t,!E.test(i=D()))throw j(i,"name");var h=new l(W(i));Z(h,function(t){"option"===t?(tt(h,t),F(";")):(U(t),Q(h,"optional"))}),s.add(h);break;case"extensions":K(n.extensions||(n.extensions=[]));break;case"reserved":K(n.reserved||(n.reserved=[]),!0);break;default:if("proto2"===N||!w.test(t))throw j(t);U(t),Q(n,"optional")}}),t.add(n),t===z&&G.push(n)}function Q(t,e,n){var i=D();if("group"===i){var r=t,o=e;if(2023<=N)throw j("group");var h,d,c=D();if(E.test(c))return c===(d=p.lcFirst(c))&&(c=p.ucFirst(c)),F("="),u=Y(D()),(h=new s(c)).group=!0,(d=new a(d,u,c,o)).filename=x.filename,Z(h,function(t){switch(t){case"option":tt(h,t),F(";");break;case"required":case"repeated":Q(h,t);break;case"optional":Q(h,"proto3"===N?"proto3_optional":"optional");break;case"message":q(h);break;case"enum":J(h);break;case"reserved":K(h.reserved||(h.reserved=[]),!0);break;default:throw j(t)}}),void r.add(h).add(d);throw j(c,"name")}for(;i.endsWith(".")||O().startsWith(".");)i+=D();if(!w.test(i))throw j(i,"type");var u=D();if(!E.test(u))throw j(u,"name");u=W(u),F("=");var f=new a(u,Y(D()),i,e,n);Z(f,function(t){if("option"!==t)throw j(t);tt(f,t),F(";")},function(){nt(f)}),"proto3_optional"===e?(o=new l("_"+u),f.setOption("proto3_optional",!0),o.add(f),t.add(o)):t.add(f),t===z&&G.push(f)}function J(t,e){if(!E.test(e=D()))throw j(e,"name");var n=new h(e);Z(n,function(t){switch(t){case"option":tt(n,t),F(";");break;case"reserved":K(n.reserved||(n.reserved=[]),!0),n.reserved===rt&&(n.reserved=[]);break;default:var e=n,i=t;if(!E.test(i))throw j(i,"name");F("=");var r=Y(D(),!0),s={options:rt,getOption:function(t){return this.options[t]},setOption:function(t,e){u.prototype.setOption.call(s,t,e)},setParsedOption:function(){return rt}};return Z(s,function(t){if("option"!==t)throw j(t);tt(s,t),F(";")},function(){nt(s)}),void e.add(i,r,s.comment,s.parsedOptions||s.options)}}),t.add(n),t===z&&G.push(n)}function tt(t,e){var n=!0;for("option"===e&&(e=D());"="!==e;){if("("===e&&(i=D(),F(")"),e="("+i+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var i=e.split("."),r=i[0]+".";e=i[1];continue}r=e}else a=a?a+e:e;e=D()}var s=function t(e,n){if(F("{",!0)){for(var i={};!F("}",!0);){if(!E.test(B=D()))throw j(B,"name");if(null===B)throw j(B,"end of input");var r,s,a=B;if(F(":",!0),"{"===O())r=t(e,n+"."+B);else if("["===O()){if(r=[],F("[",!0)){for(;s=V(!0),r.push(s),F(",",!0););F("]"),void 0!==s&&et(e,n+"."+B,s)}}else r=V(!0),et(e,n+"."+B,r);var o=i[a];o&&(r=[].concat(o).concat(r)),i[a]=r,F(",",!0),F(";",!0)}return i}var l=V(!0);return et(e,n,l),l}(t,s=a?r.concat(a):r),a=a&&"."===a[0]?a.slice(1):a;r=r&&"."===r[r.length-1]?r.slice(0,-1):r,t.setParsedOption&&t.setParsedOption(r,s,a)}function et(t,e,n){z===t&&/^features\./.test(e)?$[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(F("[",!0)){for(;tt(t,"option"),F(",",!0););F("]")}}for(;null!==(B=D());)switch(B){case"package":if(!M)throw j(B);if(T!==rt)throw j("package");if(T=D(),!w.test(T))throw j(T,"name");z=z.define(T),F(";");break;case"import":if(!M)throw j(B);switch(k=void 0,O()){case"weak":k=R=R||[],D();break;case"public":D();default:k=A=A||[]}C=H(),F(";"),k.push(C);break;case"syntax":if(!M)throw j(B);if(F("="),(N=H())<2023)throw j(N,"syntax");F(";");break;case"edition":if(!M)throw j(B);if(F("="),N=H(),!["2023"].includes(N))throw j(N,"edition");F(";");break;case"option":tt(z,B),F(";",!0);break;default:if(X(z,B)){M=!1;continue}throw j(B)}return G.forEach(t=>{t.f=N,Object.keys($).forEach(e=>{t.getOption(e)===rt&&t.setOption(e,$[e],!0)})}),x.filename=null,{package:T,imports:A,weakImports:R,root:e}}},{15:15,16:16,20:20,22:22,24:24,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,e,n){e.exports=l;var i,r=t(39),s=r.LongBits,a=r.utf8;function o(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function l(t){this.buf=t,this.pos=0,this.len=t.length}function h(){return r.Buffer?function(t){return(l.create=function(t){return r.Buffer.isBuffer(t)?new i(t):c(t)})(t)}:c}var d,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new l(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new l(t);throw Error("illegal buffer")};function u(){var t=new s(0,0),e=0;if(!(4<this.len-this.pos)){for(;e<3;++e){if(this.pos>=this.len)throw o(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,4<this.len-this.pos){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw o(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function f(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw o(this,8);return new s(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}l.create=h(),l.prototype._=r.Array.prototype.subarray||r.Array.prototype.slice,l.prototype.uint32=(d=4294967295,function(){if(d=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(d=(d|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return d;throw this.pos=this.len,o(this,10)}),l.prototype.int32=function(){return 0|this.uint32()},l.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},l.prototype.bool=function(){return 0!==this.uint32()},l.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return f(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|f(this.buf,this.pos+=4)},l.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=r.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},l.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=r.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},l.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?(t=r.Buffer)?t.alloc(0):new this.buf.constructor(0):this._.call(this.buf,e,n)},l.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},l.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},l.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},l.p=function(t){i=t,l.create=h(),i.p();var e=r.Long?"toLong":"toNumber";r.merge(l.prototype,{int64:function(){return u.call(this)[e](!1)},uint64:function(){return u.call(this)[e](!0)},sint64:function(){return u.call(this).zzDecode()[e](!1)},fixed64:function(){return p.call(this)[e](!0)},sfixed64:function(){return p.call(this)[e](!1)}})}},{39:39}],28:[function(t,e,n){e.exports=s;var i=t(27),r=((s.prototype=Object.create(i.prototype)).constructor=s,t(39));function s(t){i.call(this,t)}s.p=function(){r.Buffer&&(s.prototype._=r.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.p()},{27:27,39:39}],29:[function(t,e,n){e.exports=c;var i,r,s,a=t(23),o=(((c.prototype=Object.create(a.prototype)).constructor=c).className="Root",t(16)),l=t(15),h=t(25),d=t(37);function c(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}c.fromJSON=function(t,e){return e=e||new c,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},c.prototype.resolvePath=d.path.resolve,c.prototype.fetch=d.fetch,c.prototype.load=function t(e,n,i){"function"==typeof n&&(i=n,n=rt);var a=this;if(!i)return d.asPromise(t,a,e,n);var o=i===u;function l(t,e){if(i){if(o)throw t;e&&e.resolveAll();var n=i;i=null,n(t,e)}}function h(t){var e=t.lastIndexOf("google/protobuf/");return-1<e&&(t=t.substring(e))in s?t:null}function c(t,e){try{if(d.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),d.isString(e)){r.filename=t;var i,s=r(e,a,n),c=0;if(s.imports)for(;c<s.imports.length;++c)(i=h(s.imports[c])||a.resolvePath(t,s.imports[c]))&&f(i);if(s.weakImports)for(c=0;c<s.weakImports.length;++c)(i=h(s.weakImports[c])||a.resolvePath(t,s.weakImports[c]))&&f(i,!0)}else a.setOptions(e.options).addJSON(e.nested)}catch(t){l(t)}o||p||l(null,a)}function f(t,e){if(t=h(t)||t,!~a.files.indexOf(t))if(a.files.push(t),t in s)o?c(t,s[t]):(++p,setTimeout(function(){--p,c(t,s[t])}));else if(o){var n;try{n=d.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}c(t,n)}else++p,a.fetch(t,function(n,r){--p,i&&(n?e?p||l(null,a):l(n):c(t,r))})}var p=0;d.isString(e)&&(e=[e]);for(var _,m=0;m<e.length;++m)(_=a.resolvePath("",e[m]))&&f(_);return o?a.resolveAll():p||l(null,a),a},c.prototype.loadSync=function(t,e){if(d.isNode)return this.load(t,e,u);throw Error("not supported")},c.prototype.resolveAll=function(){if(!this.y)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(t){return"'extend "+t.extend+"' in "+t.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var f=/^[A-Z]/;function p(t,e){var n,i=e.parent.lookup(e.extend);if(i)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),i.get(n.name)||((n.declaringField=e).extensionField=n,i.add(n)),1}c.prototype.A=function(t){if(t instanceof o)t.extend===rt||t.extensionField||p(0,t)||this.deferred.push(t);else if(t instanceof l)f.test(t.name)&&(t.parent[t.name]=t.values);else if(!(t instanceof h)){if(t instanceof i)for(var e=0;e<this.deferred.length;)p(0,this.deferred[e])?this.deferred.splice(e,1):++e;for(var n=0;n<t.nestedArray.length;++n)this.A(t.v[n]);f.test(t.name)&&(t.parent[t.name]=t)}(t instanceof i||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},c.prototype.T=function(t){var e;if(t instanceof o)t.extend!==rt&&(t.extensionField?(t.extensionField.parent.remove(t.extensionField),t.extensionField=null):-1<(e=this.deferred.indexOf(t))&&this.deferred.splice(e,1));else if(t instanceof l)f.test(t.name)&&delete t.parent[t.name];else if(t instanceof a){for(var n=0;n<t.nestedArray.length;++n)this.T(t.v[n]);f.test(t.name)&&delete t.parent[t.name]}delete this.j[t.fullName]},c.p=function(t,e,n){i=t,r=e,s=n}},{15:15,16:16,23:23,25:25,37:37}],30:[function(t,e,n){e.exports={}},{}],31:[function(t,e,n){n.Service=t(32)},{32:32}],32:[function(t,e,n){e.exports=r;var i=t(39);function r(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");i.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((r.prototype=Object.create(i.EventEmitter.prototype)).constructor=r).prototype.rpcCall=function t(e,n,r,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return i.asPromise(t,o,e,n,r,s);if(!o.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),rt;try{return o.rpcImpl(e,n[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(t,n){if(t)return o.emit("error",t,e),a(t);if(null===n)return o.end(!0),rt;if(!(n instanceof r))try{n=r[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return o.emit("error",t,e),a(t)}return o.emit("data",n,e),a(null,n)})}catch(t){return o.emit("error",t,e),setTimeout(function(){a(t)},0),rt}},r.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{39:39}],33:[function(t,e,n){e.exports=o;var i=t(23),r=(((o.prototype=Object.create(i.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){i.call(this,t,e),this.methods={},this.x=null}function l(t){return t.x=null,t}o.fromJSON=function(t,e){var n=new o(t,e.options);if(e.methods)for(var i=Object.keys(e.methods),s=0;s<i.length;++s)n.add(r.fromJSON(i[s],e.methods[i[s]]));return e.nested&&n.addJSON(e.nested),e.edition&&(n.f=e.edition),n.comment=e.comment,n.a="proto3",n},o.prototype.toJSON=function(t){var e=i.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",i.arrayToJSON(this.methodsArray,t)||{},"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},Object.defineProperty(o.prototype,"methodsArray",{get:function(){return this.x||(this.x=s.toArray(this.methods))}}),o.prototype.get=function(t){return this.methods[t]||i.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){i.prototype.resolve.call(this);for(var t=this.methodsArray,e=0;e<t.length;++e)t[e].resolve()}return this},o.prototype.g=function(t){return this.w&&(i.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(e=>{e.g(t)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof r?l((this.methods[t.name]=t).parent=this):i.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof r){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,l(this)}return i.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var i,r=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((i=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");r[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:i,q:i.resolvedRequestType.ctor,s:i.resolvedResponseType.ctor})}return r}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=f;var i=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,h=/\s/,d=/\\(.?)/g,c={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(d,function(t,e){switch(e){case"\\":case"":return e;default:return c[e]||""}})}function f(t,e){t=t.toString();var n=0,d=t.length,c=1,f=0,p={},_=[],m=null;function g(t){return Error("illegal "+t+" (line "+c+")")}function y(e){return t[0|e]||""}function v(n,i,r){var s,h={type:t[0|n++]||"",lineEmpty:!1,leading:r},d=n-(r=e?2:3);do{if(--d<0||"\n"==(s=t[0|d]||"")){h.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,i).split(l),_=0;_<u.length;++_)u[_]=u[_].replace(e?o:a,"").trim();h.text=u.join("\n").trim(),p[c]=h,f=c}function b(e){var n=S(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function S(t){for(var e=t;e<d&&"\n"!==y(e);)e++;return e}function E(){if(0<_.length)return _.shift();if(m){var a="'"===m?s:r,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,w(m),m=null,u(o[1]);throw g("string")}var l,f,p,E,x,T=0===n;do{if(n===d)return null;for(l=!1;h.test(p=y(n));)if("\n"===p&&(T=!0,++c),++n===d)return null;if("/"===y(n)){if(++n===d)throw g("comment");if("/"===y(n))if(e){if(x=!1,b((E=n)-1))for(x=!0;(n=S(n))!==d&&(n++,T&&b(n)););else n=Math.min(d,S(n)+1);x&&(v(E,n,T),T=!0),c++}else{for(x="/"===y(E=n+1);"\n"!==y(++n);)if(n===d)return null;++n,x&&(v(E,n-1,T),T=!0),++c}else{if("*"!==(p=y(n)))return"/";E=n+1,x=e||"*"===y(E);do{if("\n"===p&&++c,++n===d)throw g("comment")}while(f=p,p=y(n),"*"!==f||"/"!==p);++n,x&&(v(E,n-2,T),T=!0)}l=!0}}while(l);var A=n;if(i.lastIndex=0,!i.test(y(A++)))for(;A<d&&!i.test(y(A));)++A;return'"'!=(a=t.substring(n,n=A))&&"'"!=a||(m=a),a}function w(t){_.push(t)}function x(){if(!_.length){var t=E();if(null===t)return null;w(t)}return _[0]}return Object.defineProperty({next:E,peek:x,push:w,skip:function(t,e){var n=x();if(n===t)return E(),!0;if(e)return!1;throw g("token '"+n+"', '"+t+"' expected")},cmnt:function(t){var n,i=null;return t===rt?(n=p[c-1],delete p[c-1],n&&(e||"*"===n.type||n.lineEmpty)&&(i=n.leading?n.text:null)):(f<t&&x(),n=p[t],delete p[t],!n||n.lineEmpty||!e&&"/"!==n.type||(i=n.leading?null:n.text)),i}},"line",{get:function(){return c}})}f.unescape=u},{}],35:[function(t,e,n){e.exports=y;var i=t(23),r=(((y.prototype=Object.create(i.prototype)).constructor=y).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),h=t(21),d=t(27),c=t(42),u=t(37),f=t(14),p=t(13),_=t(40),m=t(12),g=t(41);function y(t,e){i.call(this,t,e),this.fields={},this.oneofs=rt,this.extensions=rt,this.reserved=rt,this.group=rt,this.S=null,this.e=null,this.I=null,this.N=null}function v(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(y.prototype,{fieldsById:{get:function(){if(!this.S){this.S={};for(var t=Object.keys(this.fields),e=0;e<t.length;++e){var n=this.fields[t[e]],i=n.id;if(this.S[i])throw Error("duplicate id "+i+" in "+this);this.S[i]=n}}return this.S}},fieldsArray:{get:function(){return this.e||(this.e=u.toArray(this.fields))}},oneofsArray:{get:function(){return this.I||(this.I=u.toArray(this.oneofs))}},ctor:{get:function(){return this.N||(this.ctor=y.generateConstructor(this)())},set:function(t){for(var e=t.prototype,n=(e instanceof h||((t.prototype=new h).constructor=t,u.merge(t.prototype,e)),t.$type=t.prototype.$type=this,u.merge(t,h,!0),this.N=t,0);n<this.fieldsArray.length;++n)this.e[n].resolve();var i={};for(n=0;n<this.oneofsArray.length;++n)i[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,i)}}}),y.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),i=0;i<t.fieldsArray.length;++i)(e=t.e[i]).map?n("this%s={}",u.safeProp(e.name)):e.repeated&&n("this%s=[]",u.safeProp(e.name));return n("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},y.fromJSON=function(t,e){for(var n=new y(t,e.options),h=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),d=0;d<h.length;++d)n.add((void 0!==e.fields[h[d]].keyType?o:a).fromJSON(h[d],e.fields[h[d]]));if(e.oneofs)for(h=Object.keys(e.oneofs),d=0;d<h.length;++d)n.add(s.fromJSON(h[d],e.oneofs[h[d]]));if(e.nested)for(h=Object.keys(e.nested),d=0;d<h.length;++d){var c=e.nested[h[d]];n.add((c.id!==rt?a:c.fields!==rt?y:c.values!==rt?r:c.methods!==rt?l:i).fromJSON(h[d],c))}return e.extensions&&e.extensions.length&&(n.extensions=e.extensions),e.reserved&&e.reserved.length&&(n.reserved=e.reserved),e.group&&(n.group=!0),e.comment&&(n.comment=e.comment),e.edition&&(n.f=e.edition),n.a="proto3",n},y.prototype.toJSON=function(t){var e=i.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",i.arrayToJSON(this.oneofsArray,t),"fields",i.arrayToJSON(this.fieldsArray.filter(function(t){return!t.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:rt,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"group",this.group||rt,"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},y.prototype.resolveAll=function(){if(this.y){i.prototype.resolveAll.call(this);for(var t=this.oneofsArray,e=0;e<t.length;)t[e++].resolve();var n=this.fieldsArray;for(e=0;e<n.length;)n[e++].resolve()}return this},y.prototype.g=function(t){return this.w&&(i.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(e=>{e.u(t)}),this.fieldsArray.forEach(e=>{e.u(t)})),this},y.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},y.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof a&&t.extend===rt){if((this.S||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),v(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),v(this)):i.prototype.add.call(this,t)},y.prototype.remove=function(t){if(t instanceof a&&t.extend===rt){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),v(this);throw Error(t+" is not a member of "+this)}if(t instanceof s){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),v(this);throw Error(t+" is not a member of "+this)}return i.prototype.remove.call(this,t)},y.prototype.isReservedId=function(t){return i.isReservedId(this.reserved,t)},y.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)},y.prototype.create=function(t){return new this.ctor(t)},y.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var i;return this.encode=f(this)({Writer:c,types:e,util:u}),this.decode=p(this)({Reader:d,types:e,util:u}),this.verify=_(this)({types:e,util:u}),this.fromObject=m.fromObject(this)({types:e,util:u}),this.toObject=m.toObject(this)({types:e,util:u}),(t=g[t])&&((i=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(i),i.toObject=this.toObject,this.toObject=t.toObject.bind(i)),this},y.prototype.encode=function(t,e){return this.setup().encode(t,e)},y.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},y.prototype.decode=function(t,e){return this.setup().decode(t,e)},y.prototype.decodeDelimited=function(t){return t instanceof d||(t=d.create(t)),this.decode(t,t.uint32())},y.prototype.verify=function(t){return this.setup().verify(t)},y.prototype.fromObject=function(t){return this.setup().fromObject(t)},y.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},y.d=function(t){return function(e){u.decorateType(e,t)}}},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(t,e,n){t=t(37);var i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function r(t,e){var n=0,r={};for(e|=0;n<t.length;)r[i[n+e]]=t[n++];return r}n.basic=r([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=r([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=r([0,0,0,1,1],7),n.mapKey=r([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=r([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var i,r,s=e.exports=t(39),a=t(30),o=(s.codegen=t(3),s.fetch=t(5),s.path=t(8),s.fs=s.inquire("fs"),s.toArray=function(t){if(t){for(var e=Object.keys(t),n=Array(e.length),i=0;i<e.length;)n[i]=t[e[i++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var i=t[n++],r=t[n++];r!==rt&&(e[i]=r)}return e},/\\/g),l=/"/g,h=(s.isReserved=function(t){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t)},s.safeProp=function(t){return!/^[$\w_]+$/.test(t)||s.isReserved(t)?'["'+t.replace(o,"\\\\").replace(l,'\\"')+'"]':"."+t},s.ucFirst=function(t){return(t[0]||"").toUpperCase()+t.substring(1)},/_([a-z])/g),d=(s.camelCase=function(t){return t.substring(0,1)+t.substring(1).replace(h,function(t,e){return e.toUpperCase()})},s.compareFieldsById=function(t,e){return t.id-e.id},s.decorateType=function(e,n){return e.$type?(n&&e.$type.name!==n&&(s.decorateRoot.remove(e.$type),e.$type.name=n,s.decorateRoot.add(e.$type)),e.$type):(n=new(i=i||t(35))(n||e.name),s.decorateRoot.add(n),n.ctor=e,Object.defineProperty(e,"$type",{value:n,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:n,enumerable:!1}),n)},0);s.decorateEnum=function(e){var n;return e.$type||(n=new(r=r||t(15))("Enum"+d++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,i){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,r){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,r);else{if((n=e[s])&&i)return e;n&&(r=[].concat(n).concat(r)),e[s]=r}return e}(t,e=e.split("."),n);throw TypeError("path must be specified")},Object.defineProperty(s,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(t(29)))}})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(t,e,n){e.exports=r;var i=t(39);function r(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=r.zero=new r(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},r.zeroHash="\0\0\0\0\0\0\0\0",r.fromNumber=function(t){var e,n;return 0===t?s:(n=(t=(e=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,e&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new r(n,t))},r.from=function(t){if("number"==typeof t)return r.fromNumber(t);if(i.isString(t)){if(!i.Long)return r.fromNumber(parseInt(t,10));t=i.Long.fromString(t)}return t.low||t.high?new r(t.low>>>0,t.high>>>0):s},r.prototype.toNumber=function(t){var e;return!t&&this.hi>>>31?(e=~this.hi>>>0,-((t=1+~this.lo>>>0)+4294967296*(e=t?e:e+1>>>0))):this.lo+4294967296*this.hi},r.prototype.toLong=function(t){return i.Long?new i.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);r.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new r((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},r.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},r.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,e,n){var i=n;function r(t,e,n){for(var i=Object.keys(e),r=0;r<i.length;++r)t[i[r]]!==rt&&n||(t[i[r]]=e[i[r]]);return t}function s(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack||""}),n&&r(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:rt,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}i.asPromise=t(1),i.base64=t(2),i.EventEmitter=t(4),i.float=t(6),i.inquire=t(7),i.utf8=t(10),i.pool=t(9),i.LongBits=t(38),i.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),i.global=i.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,i.emptyArray=Object.freeze?Object.freeze([]):[],i.emptyObject=Object.freeze?Object.freeze({}):{},i.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},i.isString=function(t){return"string"==typeof t||t instanceof String},i.isObject=function(t){return t&&"object"==typeof t},i.isset=i.isSet=function(t,e){var n=t[e];return null!=n&&t.hasOwnProperty(e)&&("object"!=typeof n||0<(Array.isArray(n)?n:Object.keys(n)).length)},i.Buffer=function(){try{var t=i.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),i.L=null,i.V=null,i.newBuffer=function(t){return"number"==typeof t?i.Buffer?i.V(t):new i.Array(t):i.Buffer?i.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},i.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(t){return t?i.LongBits.from(t).toHash():i.LongBits.zeroHash},i.longFromHash=function(t,e){return t=i.LongBits.fromHash(t),i.Long?i.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},i.merge=r,i.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},i.newError=s,i.ProtocolError=s("ProtocolError"),i.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;-1<n;--n)if(1===e[t[n]]&&this[t[n]]!==rt&&null!==this[t[n]])return t[n]}},i.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},i.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},i.p=function(){var t=i.Buffer;t?(i.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},i.V=t.allocUnsafe||function(e){return new t(e)}):i.L=i.V=null}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(t,e,n){e.exports=function(t){var e=r.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var i=0;i<t.fieldsArray.length;++i){var o,l=t.e[i].resolve(),h="m"+r.safeProp(l.name);l.optional&&e("if(%s!=null&&m.hasOwnProperty(%j)){",h,l.name),l.map?(e("if(!util.isObject(%s))",h)("return%j",s(l,"object"))("var k=Object.keys(%s)",h)("for(var i=0;i<k.length;++i){"),function(t,e,n){switch(e.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.key32Re.test(%s))",n)("return%j",s(e,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.key64Re.test(%s))",n)("return%j",s(e,"integer|Long key"));break;case"bool":t("if(!util.key2Re.test(%s))",n)("return%j",s(e,"boolean key"))}}(e,l,"k[i]"),a(e,l,i,h+"[k[i]]")("}")):l.repeated?(e("if(!Array.isArray(%s))",h)("return%j",s(l,"array"))("for(var i=0;i<%s.length;++i){",h),a(e,l,i,h+"[i]")("}")):(l.partOf&&(o=r.safeProp(l.partOf.name),1===n[l.partOf.name]&&e("if(p%s===1)",o)("return%j",l.partOf.name+": multiple values"),n[l.partOf.name]=1,e("p%s=1",o)),a(e,l,i,h)),l.optional&&e("}")}return e("return null")};var i=t(15),r=t(37);function s(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function a(t,e,n,r){if(e.resolvedType)if(e.resolvedType instanceof i){t("switch(%s){",r)("default:")("return%j",s(e,"enum value"));for(var a=Object.keys(e.resolvedType.values),o=0;o<a.length;++o)t("case %i:",e.resolvedType.values[a[o]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,r)("if(e)")("return%j+e",e.name+".")("}");else switch(e.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",r)("return%j",s(e,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",r,r,r,r)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',r)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',r)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",r)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',r,r,r)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var i=t(21);n[".google.protobuf.Any"]={fromObject:function(t){if(t&&t["@type"]){var e,n=t["@type"].substring(1+t["@type"].lastIndexOf("/"));if(n=this.lookup(n))return~(e="."==(t["@type"][0]||"")?t["@type"].slice(1):t["@type"]).indexOf("/")||(e="/"+e),this.create({type_url:e,value:n.encode(n.fromObject(t)).finish()})}return this.fromObject(t)},toObject:function(t,e){var n,r,s="",a="";return e&&e.json&&t.type_url&&t.value&&(a=t.type_url.substring(1+t.type_url.lastIndexOf("/")),s=t.type_url.substring(0,1+t.type_url.lastIndexOf("/")),(n=this.lookup(a))&&(t=n.decode(t.value))),!(t instanceof this.ctor)&&t instanceof i?(n=t.$type.toObject(t,e),r="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+r,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=c;var i,r=t(39),s=r.LongBits,a=r.base64,o=r.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function h(){}function d(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function c(){this.len=0,this.head=new l(h,0,0),this.tail=this.head,this.states=null}function u(){return r.Buffer?function(){return(c.create=function(){return new i})()}:function(){return new c}}function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=rt,this.val=e}function _(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127<t.lo;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function m(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}c.create=u(),c.alloc=function(t){return new r.Array(t)},r.Array!==Array&&(c.alloc=r.pool(c.alloc,r.Array.prototype.subarray)),c.prototype.M=function(t,e,n){return this.tail=this.tail.next=new l(t,e,n),this.len+=e,this},(p.prototype=Object.create(l.prototype)).fn=function(t,e,n){for(;127<t;)e[n++]=127&t|128,t>>>=7;e[n]=t},c.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},c.prototype.int32=function(t){return t<0?this.M(_,10,s.fromNumber(t)):this.uint32(t)},c.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},c.prototype.int64=c.prototype.uint64=function(t){return t=s.from(t),this.M(_,t.length(),t)},c.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(_,t.length(),t)},c.prototype.bool=function(t){return this.M(f,1,t?1:0)},c.prototype.sfixed32=c.prototype.fixed32=function(t){return this.M(m,4,t>>>0)},c.prototype.sfixed64=c.prototype.fixed64=function(t){return t=s.from(t),this.M(m,4,t.lo).M(m,4,t.hi)},c.prototype.float=function(t){return this.M(r.float.writeFloatLE,4,t)},c.prototype.double=function(t){return this.M(r.float.writeDoubleLE,8,t)};var g=r.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var i=0;i<t.length;++i)e[n+i]=t[i]};c.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(r.isString(t)&&(e=c.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(f,1,0)},c.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(f,1,0)},c.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new l(h,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(h,0,0),this.len=0),this},c.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},c.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},c.p=function(t){i=t,c.create=u(),i.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var i=t(42),r=((s.prototype=Object.create(i.prototype)).constructor=s,t(39));function s(){i.call(this)}function a(t,e,n){t.length<40?r.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=r.V,s.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&"set"===r.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var i=0;i<t.length;)e[n++]=t[i++]}},s.prototype.bytes=function(t){var e=(t=r.isString(t)?r.L(t,"base64"):t).length>>>0;return this.uint32(e),e&&this.M(s.writeBytesBuffer,e,t),this},s.prototype.string=function(t){var e=r.Buffer.byteLength(t);return this.uint32(e),e&&this.M(a,e,t),this},s.p()},{39:39,42:42}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(19),i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}(),$protobuf=protobuf,$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.default||($protobuf.roots.default={}),$root.MeshData=function(){function t(t){if(this.weights=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.index=0,t.prototype.weights=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.index&&Object.hasOwnProperty.call(t,"index")&&e.uint32(8).int32(t.index),null!=t.weights&&t.weights.length){e.uint32(18).fork();for(var n=0;n<t.weights.length;++n)e.float(t.weights[n]);e.ldelim()}return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.MeshData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:r.index=t.int32();break;case 2:if(r.weights&&r.weights.length||(r.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)r.weights.push(t.float());else r.weights.push(t.float());break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.index&&t.hasOwnProperty("index")&&!$util.isInteger(t.index))return"index: integer expected";if(null!=t.weights&&t.hasOwnProperty("weights")){if(!Array.isArray(t.weights))return"weights: array expected";for(var e=0;e<t.weights.length;++e)if("number"!=typeof t.weights[e])return"weights: number[] expected"}return null},t.fromObject=function(t){if(t instanceof $root.MeshData)return t;var e=new $root.MeshData;if(null!=t.index&&(e.index=0|t.index),t.weights){if(!Array.isArray(t.weights))throw TypeError(".MeshData.weights: array expected");e.weights=[];for(var n=0;n<t.weights.length;++n)e.weights[n]=Number(t.weights[n])}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.weights=[]),e.defaults&&(n.index=0),null!=t.index&&t.hasOwnProperty("index")&&(n.index=t.index),t.weights&&t.weights.length){n.weights=[];for(var i=0;i<t.weights.length;++i)n.weights[i]=e.json&&!isFinite(t.weights[i])?String(t.weights[i]):t.weights[i]}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/MeshData"},t}(),$root.JointData=function(){function t(t){if(this.translate=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.translate=$util.emptyArray,t.prototype.rotate=$util.newBuffer([]),t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.translate&&t.translate.length){e.uint32(10).fork();for(var n=0;n<t.translate.length;++n)e.float(t.translate[n]);e.ldelim()}return null!=t.rotate&&Object.hasOwnProperty.call(t,"rotate")&&e.uint32(18).bytes(t.rotate),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.JointData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(r.translate&&r.translate.length||(r.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)r.translate.push(t.float());else r.translate.push(t.float());break;case 2:r.rotate=t.bytes();break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.translate&&t.hasOwnProperty("translate")){if(!Array.isArray(t.translate))return"translate: array expected";for(var e=0;e<t.translate.length;++e)if("number"!=typeof t.translate[e])return"translate: number[] expected"}return null!=t.rotate&&t.hasOwnProperty("rotate")&&!(t.rotate&&"number"==typeof t.rotate.length||$util.isString(t.rotate))?"rotate: buffer expected":null},t.fromObject=function(t){if(t instanceof $root.JointData)return t;var e=new $root.JointData;if(t.translate){if(!Array.isArray(t.translate))throw TypeError(".JointData.translate: array expected");e.translate=[];for(var n=0;n<t.translate.length;++n)e.translate[n]=Number(t.translate[n])}return null!=t.rotate&&("string"==typeof t.rotate?$util.base64.decode(t.rotate,e.rotate=$util.newBuffer($util.base64.length(t.rotate)),0):t.rotate.length>=0&&(e.rotate=t.rotate)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.translate=[]),e.defaults&&(e.bytes===String?n.rotate="":(n.rotate=[],e.bytes!==Array&&(n.rotate=$util.newBuffer(n.rotate)))),t.translate&&t.translate.length){n.translate=[];for(var i=0;i<t.translate.length;++i)n.translate[i]=e.json&&!isFinite(t.translate[i])?String(t.translate[i]):t.translate[i]}return null!=t.rotate&&t.hasOwnProperty("rotate")&&(n.rotate=e.bytes===String?$util.base64.encode(t.rotate,0,t.rotate.length):e.bytes===Array?Array.prototype.slice.call(t.rotate):t.rotate),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/JointData"},t}(),$root.FaceFrameData=function(){function t(t){if(this.js=[],this.ms=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.id=0,t.prototype.s="",t.prototype.sf=0,t.prototype.ef=0,t.prototype.bsw=$util.newBuffer([]),t.prototype.cs=$util.newBuffer([]),t.prototype.js=$util.emptyArray,t.prototype.ms=$util.emptyArray,t.prototype.bodyId=0,t.prototype.faceFrameType=0,t.prototype.asf=0,t.prototype.aef=0,t.prototype.n="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.id&&Object.hasOwnProperty.call(t,"id")&&e.uint32(8).int32(t.id),null!=t.s&&Object.hasOwnProperty.call(t,"s")&&e.uint32(18).string(t.s),null!=t.sf&&Object.hasOwnProperty.call(t,"sf")&&e.uint32(24).int32(t.sf),null!=t.ef&&Object.hasOwnProperty.call(t,"ef")&&e.uint32(32).int32(t.ef),null!=t.bsw&&Object.hasOwnProperty.call(t,"bsw")&&e.uint32(42).bytes(t.bsw),null!=t.cs&&Object.hasOwnProperty.call(t,"cs")&&e.uint32(90).bytes(t.cs),null!=t.js&&t.js.length)for(var n=0;n<t.js.length;++n)$root.JointData.encode(t.js[n],e.uint32(98).fork()).ldelim();if(null!=t.ms&&t.ms.length)for(n=0;n<t.ms.length;++n)$root.MeshData.encode(t.ms[n],e.uint32(106).fork()).ldelim();return null!=t.bodyId&&Object.hasOwnProperty.call(t,"bodyId")&&e.uint32(112).int32(t.bodyId),null!=t.faceFrameType&&Object.hasOwnProperty.call(t,"faceFrameType")&&e.uint32(120).int32(t.faceFrameType),null!=t.asf&&Object.hasOwnProperty.call(t,"asf")&&e.uint32(128).int32(t.asf),null!=t.aef&&Object.hasOwnProperty.call(t,"aef")&&e.uint32(136).int32(t.aef),null!=t.n&&Object.hasOwnProperty.call(t,"n")&&e.uint32(146).string(t.n),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.FaceFrameData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:r.id=t.int32();break;case 2:r.s=t.string();break;case 3:r.sf=t.int32();break;case 4:r.ef=t.int32();break;case 5:r.bsw=t.bytes();break;case 11:r.cs=t.bytes();break;case 12:r.js&&r.js.length||(r.js=[]),r.js.push($root.JointData.decode(t,t.uint32()));break;case 13:r.ms&&r.ms.length||(r.ms=[]),r.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:r.bodyId=t.int32();break;case 15:r.faceFrameType=t.int32();break;case 16:r.asf=t.int32();break;case 17:r.aef=t.int32();break;case 18:r.n=t.string();break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.id&&t.hasOwnProperty("id")&&!$util.isInteger(t.id))return"id: integer expected";if(null!=t.s&&t.hasOwnProperty("s")&&!$util.isString(t.s))return"s: string expected";if(null!=t.sf&&t.hasOwnProperty("sf")&&!$util.isInteger(t.sf))return"sf: integer expected";if(null!=t.ef&&t.hasOwnProperty("ef")&&!$util.isInteger(t.ef))return"ef: integer expected";if(null!=t.bsw&&t.hasOwnProperty("bsw")&&!(t.bsw&&"number"==typeof t.bsw.length||$util.isString(t.bsw)))return"bsw: buffer expected";if(null!=t.cs&&t.hasOwnProperty("cs")&&!(t.cs&&"number"==typeof t.cs.length||$util.isString(t.cs)))return"cs: buffer expected";if(null!=t.js&&t.hasOwnProperty("js")){if(!Array.isArray(t.js))return"js: array expected";for(var e=0;e<t.js.length;++e)if(n=$root.JointData.verify(t.js[e]))return"js."+n}if(null!=t.ms&&t.hasOwnProperty("ms")){if(!Array.isArray(t.ms))return"ms: array expected";for(e=0;e<t.ms.length;++e){var n;if(n=$root.MeshData.verify(t.ms[e]))return"ms."+n}}return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&!$util.isInteger(t.bodyId)?"bodyId: integer expected":null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&!$util.isInteger(t.faceFrameType)?"faceFrameType: integer expected":null!=t.asf&&t.hasOwnProperty("asf")&&!$util.isInteger(t.asf)?"asf: integer expected":null!=t.aef&&t.hasOwnProperty("aef")&&!$util.isInteger(t.aef)?"aef: integer expected":null!=t.n&&t.hasOwnProperty("n")&&!$util.isString(t.n)?"n: string expected":null},t.fromObject=function(t){if(t instanceof $root.FaceFrameData)return t;var e=new $root.FaceFrameData;if(null!=t.id&&(e.id=0|t.id),null!=t.s&&(e.s=String(t.s)),null!=t.sf&&(e.sf=0|t.sf),null!=t.ef&&(e.ef=0|t.ef),null!=t.bsw&&("string"==typeof t.bsw?$util.base64.decode(t.bsw,e.bsw=$util.newBuffer($util.base64.length(t.bsw)),0):t.bsw.length>=0&&(e.bsw=t.bsw)),null!=t.cs&&("string"==typeof t.cs?$util.base64.decode(t.cs,e.cs=$util.newBuffer($util.base64.length(t.cs)),0):t.cs.length>=0&&(e.cs=t.cs)),t.js){if(!Array.isArray(t.js))throw TypeError(".FaceFrameData.js: array expected");e.js=[];for(var n=0;n<t.js.length;++n){if("object"!=typeof t.js[n])throw TypeError(".FaceFrameData.js: object expected");e.js[n]=$root.JointData.fromObject(t.js[n])}}if(t.ms){if(!Array.isArray(t.ms))throw TypeError(".FaceFrameData.ms: array expected");for(e.ms=[],n=0;n<t.ms.length;++n){if("object"!=typeof t.ms[n])throw TypeError(".FaceFrameData.ms: object expected");e.ms[n]=$root.MeshData.fromObject(t.ms[n])}}return null!=t.bodyId&&(e.bodyId=0|t.bodyId),null!=t.faceFrameType&&(e.faceFrameType=0|t.faceFrameType),null!=t.asf&&(e.asf=0|t.asf),null!=t.aef&&(e.aef=0|t.aef),null!=t.n&&(e.n=String(t.n)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.js=[],n.ms=[]),e.defaults&&(n.id=0,n.s="",n.sf=0,n.ef=0,e.bytes===String?n.bsw="":(n.bsw=[],e.bytes!==Array&&(n.bsw=$util.newBuffer(n.bsw))),e.bytes===String?n.cs="":(n.cs=[],e.bytes!==Array&&(n.cs=$util.newBuffer(n.cs))),n.bodyId=0,n.faceFrameType=0,n.asf=0,n.aef=0,n.n=""),null!=t.id&&t.hasOwnProperty("id")&&(n.id=t.id),null!=t.s&&t.hasOwnProperty("s")&&(n.s=t.s),null!=t.sf&&t.hasOwnProperty("sf")&&(n.sf=t.sf),null!=t.ef&&t.hasOwnProperty("ef")&&(n.ef=t.ef),null!=t.bsw&&t.hasOwnProperty("bsw")&&(n.bsw=e.bytes===String?$util.base64.encode(t.bsw,0,t.bsw.length):e.bytes===Array?Array.prototype.slice.call(t.bsw):t.bsw),null!=t.cs&&t.hasOwnProperty("cs")&&(n.cs=e.bytes===String?$util.base64.encode(t.cs,0,t.cs.length):e.bytes===Array?Array.prototype.slice.call(t.cs):t.cs),t.js&&t.js.length){n.js=[];for(var i=0;i<t.js.length;++i)n.js[i]=$root.JointData.toObject(t.js[i],e)}if(t.ms&&t.ms.length)for(n.ms=[],i=0;i<t.ms.length;++i)n.ms[i]=$root.MeshData.toObject(t.ms[i],e);return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&(n.bodyId=t.bodyId),null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&(n.faceFrameType=t.faceFrameType),null!=t.asf&&t.hasOwnProperty("asf")&&(n.asf=t.asf),null!=t.aef&&t.hasOwnProperty("aef")&&(n.aef=t.aef),null!=t.n&&t.hasOwnProperty("n")&&(n.n=t.n),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameData"},t}(),$root.FaceFrameDataList=function(){function t(t){if(this.data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.data=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.data&&t.data.length)for(var n=0;n<t.data.length;++n)$root.FaceFrameData.encode(t.data[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.FaceFrameDataList;t.pos<i;){var s=t.uint32();if(s===n)break;s>>>3==1?(r.data&&r.data.length||(r.data=[]),r.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.data&&t.hasOwnProperty("data")){if(!Array.isArray(t.data))return"data: array expected";for(var e=0;e<t.data.length;++e){var n=$root.FaceFrameData.verify(t.data[e]);if(n)return"data."+n}}return null},t.fromObject=function(t){if(t instanceof $root.FaceFrameDataList)return t;var e=new $root.FaceFrameDataList;if(t.data){if(!Array.isArray(t.data))throw TypeError(".FaceFrameDataList.data: array expected");e.data=[];for(var n=0;n<t.data.length;++n){if("object"!=typeof t.data[n])throw TypeError(".FaceFrameDataList.data: object expected");e.data[n]=$root.FaceFrameData.fromObject(t.data[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.data=[]),t.data&&t.data.length){n.data=[];for(var i=0;i<t.data.length;++i)n.data[i]=$root.FaceFrameData.toObject(t.data[i],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameDataList"},t}();const proxyProtobuf=protobuf.roots.default,pointNameObj={connect_sdk:"连接SDK",connect_sdk_success:"连接SDK成功",llm_text_sdk_received:"大模型输出的文本SDK前端收到",rendering_data_received:"客户端收到音频数据时间",rendering_display:"客户端播放音频数据时间",close_session:"关闭会话",audio_data_expired:"音频数据过期"};class Ttsa{clearReconnectTimer(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()}clearSocketReconnectTimer(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(()=>{this.send("client_heartbeat",{timestamp:Date.now(),frame:this.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)}constructor(t){var e=this;this.TAG="[TTSA]",this._lastSessionId="",this.reconnectTimer=-1,this.socketReconnectTimer=-1,this.wsConnectTimer=0,this.enterOfflineFlag=!1,this.syncTimestampInterval=0,this.syncTimestampNum=5e3,this.SYNC_INTERVAL=3e5,this.lastSyncTime=Date.now(),this.heartbeatTimer=-1,this.HEARTBEAT_INTERVAL=2e3,this._isResume=!1,this.clearOldWsTimeoutTimer=()=>{this.wsConnectTimer&&(clearTimeout(this.wsConnectTimer),this.wsConnectTimer=0)},this.initWsTimeoutTimer=()=>{this.clearOldWsTimeoutTimer(),this.wsConnectTimer=window.setTimeout(async function(){try{e.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"}),e.session_id&&(await e.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT"),e.ws.disconnect()),e.reStartSDK()}finally{e.clearOldWsTimeoutTimer()}},1e3*(this.reconnect_client_timeout+10))},this.appInfo=t.appInfo,this.sdk=t.sdkInstance,this.room=t.room,this.session_id=t.session_id,this.token=t.token,this.framedata_proto_version=t.framedata_proto_version,this._uniqueSpeakId=0,this.runStartFrameIndex=t.runStartFrameIndex,this.ttsaStateChangeHandle=t.ttsaStateChangeHandle,this.reloadSuccess=t.reloadSuccess,this.session_speak_req_id=0,this.enterOfflineMode=t.enterOfflineMode,this.reStartSDK=t.reStartSDK,this.reconnect_client_timeout=t.reconnect_client_timeout,this.reconnect_timeout=t.reconnect_timeout,this.sendVoiceEnd=t.sendVoiceEnd,this.getCurrentFrameIndex=t.getCurrentFrameIndex;const n=lookup(t.url,{query:{token:this.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});n.on("connect",()=>{this.clearReconnectTimer(),this.initWsTimeoutTimer(),this.startHeartbeat(),this.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);const t={room:this.room,client_type:"web",invisible_mode:this.sdk.getPendingInvisibleMode()};this.send("enter_room",t),this.sdk.getStatus()===AvatarStatus.offline&&this.sdk.getIsInitialized()&&this.reloadSuccess()}),n.on("first_start_timestamp",e=>{window.avatarSDKLogger.log(this.TAG,"first_start_timestamp",e),this.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(this.TAG,"ready"),this.reloadSuccess(),t.onReady()}),n.on("state_change",t=>{this.ttsaStateChangeHandle(t)}),n.on("tts_audio",e=>{try{const n=msgpack_min.decode(e);this.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:n[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(this.TAG,"下发音频数据tts_audio",n),t.handleMessage(EFrameDataType.AUDIO,n)}catch(t){this.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),n.on("face_data",async function(n){try{if(e.framedata_proto_version){let i=[];const r=new Uint8Array(n),s=pako.inflate(r);i=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,()=>{}).toJSON()||{data:[]}).data.map(t=>{const e=(t.js||[]).map(t=>({translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]})),n=(t.ms||[]).map(t=>({index:t.index||0,weights:t.weights||[]}));return _extends({},t,{bsw:t.bsw?scaledInt16BytesToFloat32(t.bsw):[],js:e,ms:n,body_id:t.bodyId||0,face_frame_type:t.faceFrameType||0})}),t.handleMessage(EFrameDataType.FACE,i),"speak"!==i[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",i)}else{const i=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",i),"speak"!==i[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,i)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}}),n.on("body_data",e=>{try{let n=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,n[0].s);const i=n.map(t=>_extends({},t,{x_offset:[]}));window.avatarSDKLogger.log(this.TAG,"body_data",JSON.stringify(i),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,n)}catch(t){this.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),n.on("event_data",e=>{try{const n=msgpack_min.decode(e);window.avatarSDKLogger.log(this.TAG,"event_data",JSON.stringify(n)),t.handleMessage(EFrameDataType.EVENT,n)}catch(t){this.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),n.on("sync_frame",e=>{t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),n.on("aa_frame",e=>{window.avatarSDKLogger.log(this.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),n.on("error_message",t=>{this.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),n.on("disconnect",i=>{this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),"io client disconnect"!==i&&(this.enterOfflineFlag?window.avatarSDKLogger.warn(this.TAG,"已在离线处理中,忽略重复的disconnect事件"):(this.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:`client Warning: socket disconnect, ${i}`}),window.avatarSDKLogger.warn(this.TAG,`${t.url} 已断开`,"disconnect原因",i),this.enterOfflineFlag=!0,this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),-1===this.socketReconnectTimer&&this.reconnect_timeout>0&&(this.socketReconnectTimer=window.setTimeout(()=>{try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(this.TAG,"disconnect error",t)}this.socketReconnectTimer=-1},1e3*this.reconnect_timeout)),-1===this.reconnectTimer&&(this.reconnectTimer=window.setTimeout(async function(){try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(e.TAG,"disconnect error",t)}await e.sdk.stopSessionFromSocket("WS_TIMEOUT"),e.reStartSDK()},1e3*this.reconnect_client_timeout))))}),n.on("client_quit",t=>{window.avatarSDKLogger.warn(this.TAG,"client_quit","断开原因",t),n.disconnect(),this.session_speak_req_id=0,Object.keys(t).length&&this.sdk.onMessage({code:EErrorCode.SOCKET_QUIT,message:`ttsa主动关闭 reason: ${JSON.stringify({e:t})}`,e:t}),["user","char_bin_load_error","admin kick","nebula admin stop","no_time"].includes(null==t?void 0:t.stop_reason)?(this.sdk.destroyClient(),this.sdk.onStatusChange(AvatarStatus.close)):(this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),this.reStartSDK())}),n.on("connect_error",t=>{this.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),n.onAny((t,e)=>{this.ws.connected&&this.initWsTimeoutTimer()}),this.ws=n}start(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")}idle(){this.stateChange("idle")}listen(){this.stateChange("listen")}think(){this.stateChange("think")}interactiveidle(){this.stateChange("interactive_idle")}enterInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})}exitInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})}firstStartTimestamp(t){const e=Date.now()/1e3,n={server_time:t,client_time:e},i=this._getResumeInfo();this._isResume&&i&&i.client_frame>0?n.resume_from_offline_idle=i:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)}syncTimestamp(){this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(()=>{const t=Date.now();if(t-this.lastSyncTime>=this.SYNC_INTERVAL){const e=this.getCurrentFrameIndex();this.sendSyncTimestamp(e),this.lastSyncTime=t}},this.syncTimestampNum)}sendSyncTimestamp(t){const e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})}sendText(t,e,n,i={client_speak_id:""}){if(!this.ws.connected)return;const r=this.getUniqueSpeakId();null!=i&&i.client_speak_id||(i.client_speak_id=r);const s={ssml:t,is_start:e,is_end:n,extra:i,multi_turn_conversation_id:r,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.1.0"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},i,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:r,speak_id:this.session_speak_req_id++})),e&&(window.performanceTracker.markStart(performanceConstant.start_action_res,"speak"),window.performanceTracker.markStart(performanceConstant.start_action_render,"speak"),window.performanceTracker.markStart(performanceConstant.voice_response_play,"speak")),n&&this.updateUniqueSpeakId(),this.send("send_text",s),r}sendSdkPoint(t,e={},n){this.send("sdk_burial_point",_extends({},e,n,this.appInfo,{burial_type:1,session_id:this.session_id,event_en_name:t,event_cn_name:pointNameObj[t],device:navigator.userAgent,timestamp:e.timestamp||Date.now(),sdkVersion:"2.1.0"}))}stateChange(t,e){const n={state:t,params:e||{}};window.performanceTracker.markStart(performanceConstant.start_action_res,t),window.performanceTracker.markStart(performanceConstant.start_action_render,t),this.send("state_change",n)}sendPerfLog(t){}changeLayout(t){this.send("change_layout",t)}changeWalkConfig(t){this.send("walk_config",t)}send(t,e){this.ws.connected&&this.ws.emit(t,e)}sendDeviceInfo(t){this.send("stat_report",t)}getStatus(){return this.ws.connected}_setResumeInfoCallback(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e}_getResumeInfo(){if(this.getResumeInfo){const t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null}updateUniqueSpeakId(){this._uniqueSpeakId+=1}getUniqueSpeakId(){return`${this._uniqueSpeakId}-${this.session_id}`}close(){this.ws&&this.ws.disconnect(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.session_speak_req_id=0,-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0)}connect(){this.ws.connect()}seekToFrame(t){this.ws.emit("seek_to_frame",{frame:t})}}function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}`}catch(e){return window.avatarSDKLogger.error("Error formatting timestamp:",e),t}}class DebugOverlay{constructor(t,e){this.container=null,this.sdkContainer=null,this.updateInterval=null,this.errors=[],this.fps=0,this.frameCount=0,this.lastFpsUpdate=performance.now(),this.videoInfo={name:"",body_id:0,id:0},this.audioInfo={sf:0,ef:0,ad:new Uint8Array},this.eventInfo={sf:0,ef:0,event:[]},this.memoryInfo={},this.perfMetrics={},this.currentFrameIndex=0,this.domRefs={},this.sdk=t,this.sdkContainer=t.el,this.sessionInfo=e,this.startTime=Date.now(),this.trackFPS(),this.trackMemory()}setAudioInfo(t){this.audioInfo=t}setEventData(t){this.eventInfo=t}addError(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()}show(){this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(()=>this.updateTextOnly(),200)),this.updateTextOnly()}hide(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null}setVideoInfo(t){this.videoInfo=t}updateTextOnly(){var t,e;if(!this.container)return;this.sessionInfo.session_id=this.sdk.resourceManager.session_id,this.currentFrameIndex=null!=(t=null==(e=this.sdk.renderScheduler.frameAnimationController)?void 0:e.getCurrentFrame())?t:0,this.updatePerfMetrics(),this.updateMemory(),this.setText("look_name",this.sessionInfo.config.look_name),this.setText("video_name",`${this.videoInfo.name} - ${this.videoInfo.body_id}`),this.setText("session_id",this.sessionInfo.session_id),this.setText("frame_idx",String(this.currentFrameIndex)),this.setText("audio_info",`开始帧: ${this.audioInfo.sf} / 结束帧: ${this.audioInfo.ef} / 长度: ${this.audioInfo.ad.length}`),this.setText("event_info",`开始帧: ${this.eventInfo.sf} / 结束帧: ${this.eventInfo.ef} / 长度: ${this.eventInfo.event.length}`),this.setText("perf",this.formatPerfMetrics()),this.setText("fps",String(this.fps)),this.setText("mem",this.formatMemory());const n=((Date.now()-this.startTime)/1e3).toFixed(1);this.setText("session_start",formatTimestamp(this.sessionInfo.session_start_time)),this.setText("session_duration",`${n}s`),this.setText("network",this.getNetworkInfo()),this.setText("error_count",`(${this.errors.length})`),this.setText("error_log",this.formatErrors(!1)),this.setText("ttsa_error_log",this.formatErrors(!0))}setText(t,e){const n=this.domRefs[t];n&&(n.innerHTML=e)}copySessionId(){const t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(()=>{}).catch(t=>{console.warn("复制失败",t)})}createOverlay(){var t;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";const e=(t,e,n="")=>{const i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML=`<span style="color:#888;font-size:11px;">${e}:</span>`;const r=document.createElement("span");return r.style.color="#fff",r.style.fontSize="11px",r.style.marginLeft="4px",r.textContent=n,i.append(r),this.domRefs[t]=r,i},n=document.createElement("h3");n.textContent="🔍 调试信息",n.style.margin="0 0 12px 0",n.style.color="#00ff88",n.style.fontSize="14px";const i=document.createElement("div");i.append(n,e("look_name","角色look_name"),e("video_name","当前视频"),(()=>{const t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";const e=document.createElement("span");e.style.color="#888",e.style.fontSize="11px",e.textContent="会话 ID:";const n=document.createElement("span");n.style.color="#fff",n.style.fontSize="11px",n.style.wordBreak="break-all",n.style.flex="1",this.domRefs.session_id=n;const i=document.createElement("button");return i.textContent="复制",i.style.fontSize="10px",i.style.padding="2px 6px",i.style.borderRadius="3px",i.style.border="none",i.style.background="#007aff",i.style.color="#fff",i.style.cursor="pointer",i.onclick=()=>this.copySessionId(),t.append(e,n,i),t})(),e("frame_idx","当前帧"),e("audio_info","下发音频"),e("event_info","下发事件"),e("fps","FPS"));const r=document.createElement("div");r.style.marginBottom="8px",r.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';const s=document.createElement("div");s.style.fontSize="11px",s.style.background="rgba(0,0,0,0.2)",s.style.padding="4px",s.style.borderRadius="4px",s.style.color="#fff",this.domRefs.perf=s,i.append(r,s);const a=document.createElement("div");a.style.borderTop="1px solid #444",a.style.paddingTop="8px",a.style.marginBottom="8px";const o=document.createElement("h4");o.style.margin="0 0 6px 0",o.style.fontSize="12px",o.style.color="#888";const l=document.createElement("span");this.domRefs.error_count=l,o.append("✅ 错误日志 ",l),a.append(o);const h=t=>{const e=document.createElement("pre");return e.style.margin="0 0 4px 0",e.style.padding="6px",e.style.background="rgba(255,255,255,0.05)",e.style.borderRadius="4px",e.style.fontSize="10px",e.style.lineHeight="1.3",e.style.color="#888",e.style.maxHeight="120px",e.style.overflowY="auto",e.style.whiteSpace="pre-wrap",this.domRefs[t]=e,e},d=h("error_log"),c=h("ttsa_error_log");a.append(d,c),i.append(a),i.append(e("mem","内存占用"),e("session_start","会话开始时间"),e("session_duration","会话时长"),e("network","网络信息")),this.container.append(i),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)}formatErrors(t){let e=this.errors;return e=e.filter(t?t=>t.code===EErrorCode.TTSA_ERROR:t=>t.code!==EErrorCode.TTSA_ERROR),0===e.length?"暂无错误":e.map(t=>`[${new Date(t.timestamp).toLocaleTimeString()}] ${t.code}: ${t.message}`).join("\n")}updatePerfMetrics(){if(!window.performanceTracker)return;const t=window.performanceTracker.getVideoMetrics();for(const[n,i]of Object.entries(t)){var e;const t=null!=(e=null==i?void 0:i.time)?e:0;this.perfMetrics[n]||(this.perfMetrics[n]={times:[],avg:0,last:0,count:0});const r=this.perfMetrics[n];r.times.push(t),r.last=t,r.count++,r.avg=r.times.reduce((t,e)=>t+e,0)/r.times.length}}formatPerfMetrics(){const t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(([t,e])=>`${t}: 最近:${e.last.toFixed(2)}ms 平均:${e.avg.toFixed(2)}ms 次数:${e.count}`).join("<br>"):"暂无数据"}formatMemory(){const t=this.memoryInfo;return t.usedJSHeapSize?`${(t.usedJSHeapSize/1048576).toFixed(1)}MB / ${(t.totalJSHeapSize/1048576).toFixed(1)}MB / ${(t.jsHeapSizeLimit/1048576).toFixed(1)}MB`:"N/A"}trackFPS(){const t=e=>{this.frameCount++,e-this.lastFpsUpdate>=1e3&&(this.fps=this.frameCount,this.frameCount=0,this.lastFpsUpdate=e),requestAnimationFrame(t)};requestAnimationFrame(t)}updateMemory(){var t;if(null!=(t=window.performance)&&t.memory){const t=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:t.jsHeapSizeLimit,totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize}}}trackMemory(){var t;null!=(t=window.performance)&&t.memory&&setInterval(()=>this.updateMemory(),1e3)}getNetworkInfo(){const t=navigator.connection;return t?`类型:${t.effectiveType} 下行:${t.downlink}Mbps 延迟:${t.rtt}ms`:"N/A"}applyStyles(t){t.style.position="fixed",t.style.bottom="50px",t.style.right="10px",t.style.width="350px",t.style.maxHeight="400px",t.style.overflowY="auto",t.style.background="rgba(0,0,0,0.8)",t.style.borderRadius="8px",t.style.padding="10px",t.style.zIndex="99999",t.style.fontSize="12px",t.style.color="#fff",t.style.textAlign="left"}enableDrag(t){let e=!1,n=0,i=0,r=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",a=>{e=!0,n=a.clientX,i=a.clientY,r=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",a=>{e&&(t.style.left=r+a.clientX-n+"px",t.style.top=s+a.clientY-i+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",()=>{e=!1,document.body.style.userSelect=""})}}class NetworkMonitor{constructor(t){this.TAG="[NetworkMonitor]",this.retryCount=1,this.retryTimer=-1,this.options=t,this.bindHandleOnline=this._handleOnline.bind(this),this.bindHandleOffline=this._handleOffline.bind(this),this._initEventListeners()}_initEventListeners(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)}_handleOnline(){window.clearTimeout(this.retryTimer),NetworkMonitor.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")}_handleOffline(){NetworkMonitor.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()}_attempt(){let t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(()=>{},t)}setState(t){NetworkMonitor.ONLINE=t}destroy(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1}}function Errors(t){var e,n;return{code:t.code,error_code:null!=(e=ERROR_CODE_MAP[t.code])?e:t.code,error_name:null!=(n=ERROR_NAME_MAP[t.code])?n:"UNKNOWN_ERROR",message:t.message,session_id:t.session_id||"",client_speak_id:t.client_speak_id,timestamp:Date.now(),originalError:t.e?JSON.stringify(t.e):null}}NetworkMonitor.ONLINE=!0;let isLoggingEnabled=!1;function executeLog(t,...e){isLoggingEnabled&&"function"==typeof t&&t(...e)}const sdkLog={log:(...t)=>executeLog(console.log,...t),info:(...t)=>executeLog(console.info,...t),warn:(...t)=>executeLog(console.warn,...t),error:(...t)=>executeLog(console.error,...t)};function setLoggingEnabled(t){isLoggingEnabled=t,t?console.log("[AVATAR SDK] version:","2.1.0","日志已启用"):console.log("[AVATAR SDK] version:","2.1.0","日志已禁用")}function sampleUniformTensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function sampleUniformPCATensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255*2-1:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535*2-1:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295*2-1:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295*2-1:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function getVertices(t,e){let n=t.char,i=n.evalSkeleton(),r=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=r[t].apply(i[t].inv());s[t]=e.homogeneous_matrix()}let a=[];for(let t=0;t<n.mesh.length;t++){let i=[];for(let r=0;r<n.mesh[t].blendshapes.size[0];r++){let a=[],o=n.mesh[t].vertices,l=n.mesh[t].blendshapes,h=e.blendshapeWeights;for(let t=0;t<3;t++)a.push(o.data[r*o.size[1]+t]);for(let e=0;e<n.mesh[t].blendshapeIndices.length;e++)for(let i=0;i<3;i++)a[i]+=h[n.mesh[t].blendshapeIndices[e]]*Number(l.data[(r*l.size[1]+i)*l.size[2]+e]);a.push(1);let d=[0,0,0,0],c=n.mesh[t].jointIndex,u=n.mesh[t].jointWeight;for(let t=0;t<n.maxJointsPerVertex;t++){let e=c[r*n.maxJointsPerVertex+t];if(e<n.skeleton.length){let i=mvmul(s[e],a);for(let e=0;e<4;e++)d[e]+=u[r*n.maxJointsPerVertex+t]*i[e]}}for(let t=0;t<3;t++)d[t]/=d[3];i.push([d[0],d[1],d[2]])}a.push(i)}return a}function getPCATextures(t,e){let n=t.char,i=[];for(let t=0;t<n.mesh.length;t++){let r=n.mesh[t].textureModels[e.mesh[t].textureModelIndex],s=[],a=new Uint8ClampedArray(r.data.size[1]*r.data.size[2]*4),o=1;r.scalingFactor&&(o*=Number(r.scalingFactor.data[0]));for(let t=0;t<r.data.size[1];t++){let e=[];for(let n=0;n<r.data.size[2];n++){let i=[];for(let e=0;e<3;e++)i.push(o*sampleUniformPCATensor(r.data.data,3*(t*r.data.size[2]+n)+e));e.push(i)}s.push(e)}for(let n=1;n<r.data.size[0];n++){let i=e.mesh[t].texturePCAWeights[n-1];r.scalingFactor&&(i*=Number(r.scalingFactor.data[n]));for(let t=0;t<r.data.size[1];t++)for(let e=0;e<r.data.size[2];e++)for(let a=0;a<3;a++)s[t][e][a]+=i*sampleUniformPCATensor(r.data.data,3*((n*r.data.size[1]+t)*r.data.size[2]+e)+a)}for(let t=0;t<r.data.size[1];t++)for(let e=0;e<r.data.size[2];e++){for(let n=0;n<3;n++)a[4*(t*r.data.size[2]+e)+n]=Math.round(255*s[r.data.size[1]-1-t][e][2-n]);a[4*(t*r.data.size[2]+e)+3]=255}i.push(new ImageData(a,r.data.size[1],r.data.size[2]))}return i}function exportAsWavefrontObj(t){let e="",n="",i=1,r=0;for(const s of t){for(const t of s.vertices)e+=`v ${t[0]} ${t[1]} ${t[2]}\n`;for(const t of s.uv)e+=`vt ${t[0]} ${t[1]}}\n`;n+=`g Obj${r}\n`;for(const t of s.polygons)n+=`f ${t.map(t=>(t+i).toString()).map(t=>`${t}/${t}`).join(" ")}\n`;i+=s.vertices.length,r+=1}return e+n}function getWavefrontObjFromVertices(t,e){function n(t,e){let n=[];for(let i=0;i<t.length;i++)0==i%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,i));return n}function i(t,e){let n=[];for(let i=0;i<t.length;i++)0==i%e&&n.push([]),n[n.length-1].push(Number(t[i]));return n}let r=t.char,s=[];for(let t=0;t<r.mesh.length;t++)s.push({vertices:e[t],uv:n(r.mesh[t].UVCoord.data,2),polygons:i(r.mesh[t].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});class StreamingClient{constructor(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}connect(){if(!this.destroyed){try{this.ws=new WebSocket(this.options.url)}catch(t){return console.error("[StreamingClient] 创建 WebSocket 失败:",t),void this.scheduleRetry()}this.ws.onopen=()=>{this.connected=!0,this.retryCount=0,console.log("[StreamingClient] 已连接"),this.send({type:"join",role:"client"})},this.ws.onmessage=t=>{let e;try{e=JSON.parse(t.data)}catch(t){return}this.handleMessage(e)},this.ws.onclose=()=>{var t,e;this.connected=!1,this.destroyed||(null==(t=(e=this.options).onDisconnect)||t.call(e),this.scheduleRetry())},this.ws.onerror=()=>{var t,e;null==(t=(e=this.options).onError)||t.call(e,"WebSocket 连接错误")}}}handleMessage(t){var e,n,i,r,s,a,o,l,h,d;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(i=(r=this.options).onOffer)||i.call(r,t.sdp);break;case"answer":break;case"ice":null==(s=(a=this.options).onIce)||s.call(a,t.candidate);break;case"event_proxy":null==(o=(l=this.options).onEventProxy)||o.call(l,t.event_type,t.data,t.server_frame);break;case"error":null==(h=(d=this.options).onError)||h.call(d,t.message||"未知错误")}}send(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}sendApiCall(t,e=[]){this.send({type:"api_call",method:t,params:e})}scheduleRetry(){if(this.destroyed)return;var t,e;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(t=(e=this.options).onError)||t.call(e,"连接重试次数已达上限"));const n=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(()=>{this.connect()},n)}isConnected(){return this.connected}destroy(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}}class VideoPlayer{constructor(t){this.video=null,this.canvas=null,this.canvasCtx=null,this.pc=null,this.stream=null,this.destroyed=!1,this.animFrameId=0,this.tempCanvas=null,this.tempCtx=null,this.options=t,t.useAlphaMask?this.createCanvasElement():this.createVideoElement()}createVideoElement(){const t=document.createElement("video");t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.video=t,this.options.container.appendChild(t)}createCanvasElement(){const t=document.createElement("canvas");t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.canvas=t,this.canvasCtx=t.getContext("2d",{willReadFrequently:!0}),this.tempCanvas=document.createElement("canvas"),this.tempCtx=this.tempCanvas.getContext("2d",{willReadFrequently:!0}),this.options.container.appendChild(t);const e=document.createElement("video");e.autoplay=!0,e.playsInline=!0,e.muted=!0,e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.pointerEvents="none",e.style.zIndex="-1",this.video=e,this.options.container.appendChild(e)}async handleOffer(t){this.destroyPeer(),this.pc=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:openrelay.metered.ca:80",username:"openrelayproject",credential:"openrelayproject"},{urls:"turn:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"},{urls:"turns:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"}]}),this.pc.onicecandidate=t=>{t.candidate&&this.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},this.pc.ontrack=t=>{console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),this.stream||(this.stream=new MediaStream,this.video&&(this.video.srcObject=this.stream)),this.stream.addTrack(t.track),"audio"===t.track.kind&&this.video&&(this.video.muted=!1,this.video.play().catch(()=>{})),"video"===t.track.kind&&this.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),this.startAlphaRendering())},this.pc.onconnectionstatechange=()=>{var t,e;if(this.pc)if(console.log("[VideoPlayer] WebRTC 状态:",this.pc.connectionState),"connected"===this.pc.connectionState)null==(t=(e=this.options).onConnected)||t.call(e);else if("disconnected"===this.pc.connectionState||"failed"===this.pc.connectionState){var n,i;null==(n=(i=this.options).onDisconnected)||n.call(i)}},await this.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}));const e=await this.pc.createAnswer();await this.pc.setLocalDescription(e),this.options.streamingClient.send({type:"answer",sdp:e.sdp})}startAlphaRendering(){if(!(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx))return;const t=this.video,e=this.canvas,n=this.canvasCtx,i=this.tempCanvas,r=this.tempCtx;let s=0,a=0,o=0,l=null;l=setInterval(()=>{this.destroyed?l&&clearInterval(l):console.log(`[VideoPlayer] Alpha 渲染调试: frames=${o}, videoReadyState=${t.readyState}, videoSize=${t.videoWidth}x${t.videoHeight}, currentTime=${t.currentTime.toFixed(2)}s, paused=${t.paused}`)},2e3);const h=()=>{if(this.destroyed)l&&clearInterval(l);else{if(t.readyState>=2&&t.videoWidth>0){const l=t.videoWidth,h=t.videoHeight,d=l/2,c=h;l===s&&h===a||(e.width=d,e.height=c,i.width=l,i.height=c,s=l,a=h,console.log(`[VideoPlayer] Alpha Mask: 检测到双流 ${l}x${h} → 原始 ${d}x${c}`)),r.clearRect(0,0,2*d,c),r.drawImage(t,0,0),n.clearRect(0,0,d,c),n.drawImage(i,0,0,d,c,0,0,d,c);try{const t=n.getImageData(0,0,d,c),e=r.getImageData(d,0,d,c),i=t.data,s=e.data;if(0===o){let t=0,e=0;const n=Math.min(1e3,i.length/4);for(let r=0;r<4*n;r+=4)(i[r]>0||i[r+1]>0||i[r+2]>0)&&t++,s[r]>0&&e++;console.log(`[VideoPlayer] 首帧像素检查: RGB非零=${t}/${n}, Alpha非零=${e}/${n}`),0===t&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(let t=0;t<i.length;t+=4)i[t+3]=s[t];n.putImageData(t,0,0),o++}catch(e){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",e),n.drawImage(t,0,0,d,c,0,0,d,c),o++}}this.animFrameId=requestAnimationFrame(h)}};this.animFrameId=requestAnimationFrame(h)}async addIceCandidate(t){this.pc&&await this.pc.addIceCandidate(t).catch(t=>{console.warn("[VideoPlayer] addIceCandidate 失败:",t)})}getVideoElement(){return this.video}getCanvasElement(){return this.canvas}isConnected(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)}destroyPeer(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)}destroy(){this.destroyed=!0,this.destroyPeer(),this.video&&this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.video=null,this.canvas=null,this.canvasCtx=null,this.tempCanvas=null,this.tempCtx=null}}class EventDispatcher{constructor(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}dispatch(t,e,n){var i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x,T,A,R,B;switch(t){case"state_change":null==(i=(r=this.callbacks).onStateChange)||i.call(r,e.state||e);break;case"speak_state_change":null==(s=(a=this.callbacks).onSpeakStateChange)||s.call(a,e.state,e.client_speak_id);break;case"voice_state_change":null==(o=(l=this.callbacks).onVoiceStateChange)||o.call(l,e.state,e.duration,e.client_speak_id||"");break;case"status_change":null==(h=(d=this.callbacks).onStatusChange)||h.call(d,e.status);break;case"render_change":null==(c=(u=this.callbacks).onRenderChange)||c.call(u,e.state);break;case"walk_state_change":null==(f=(p=this.callbacks).onWalkStateChange)||f.call(p,e.state||e);break;case"widget_event":null==(_=(m=this.callbacks).onWidgetEvent)||_.call(m,e);break;case"message":case"error":null==(g=(y=this.callbacks).onMessage)||g.call(y,e);break;case"network_info":null==(v=(b=this.callbacks).onNetworkInfo)||v.call(b,e);break;case"fps_update":null==(S=(E=this.callbacks).onFPSUpdate)||S.call(E,e);break;case"download_progress":null==(w=(x=this.callbacks).onDownloadProgress)||w.call(x,e.progress);break;case"session_id":null==(T=(A=this.callbacks).onSessionId)||T.call(A,e.session_id);break;case"frame_data_update":null==(R=(B=this.callbacks).onFrameDataUpdate)||R.call(B,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}}getSubtitleText(){return this.subtitleText}isSubtitleVisible(){return this.subtitleVisible}}class APIForwarder{constructor(t){this.client=t}speak(t,e=!0,n=!0,i={}){this.client.sendApiCall("speak",[t,e,n,i])}idle(){this.client.sendApiCall("idle",[])}listen(){this.client.sendApiCall("listen",[])}think(){this.client.sendApiCall("think",[])}interactiveidle(){this.client.sendApiCall("interactiveidle",[])}interrupt(t){this.client.sendApiCall("interrupt",[t])}changeLayout(t){this.client.sendApiCall("changeLayout",[t])}changeWalkConfig(t){this.client.sendApiCall("changeWalkConfig",[t])}setVolume(t){this.client.sendApiCall("setVolume",[t])}changeAvatarVisible(t){this.client.sendApiCall("changeAvatarVisible",[t])}switchInvisibleMode(){this.client.sendApiCall("switchInvisibleMode",[])}destroy(t="user"){this.client.sendApiCall("destroy",[t])}init(t){this.client.send({type:"init",config:t})}}function checkSecureContextSync(){const t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{const t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};const e=t.getExtension("WEBGL_debug_renderer_info");return{name:"webgl2",supported:!0,severity:"fatal",detail:{version:t.getParameter(t.VERSION),vendor:t.getParameter(t.VENDOR),renderer:t.getParameter(t.RENDERER),gpuVendor:e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):void 0,gpuRenderer:e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):void 0}}}catch(t){return{name:"webgl2",supported:!1,severity:"fatal",reason:"WebGL2 初始化失败",detail:t}}}function checkAudioSystemSync(){const t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,i=void 0!==window.MediaSource,r={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:i,hasMediaSource:i}};return n||i?{name:"audio",supported:!0,severity:"fatal",detail:r}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:r}}function checkWebCodecsSync(){const t=void 0!==window.VideoDecoder,e=(navigator.userAgent||"").toLowerCase(),n=/android/.test(e)||/openharmony|arkweb/.test(e);return{name:"webcodecs",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t,isAndroid:n,hardwareAcceleration:n?"prefer-software":"default"}}}function checkWorkerSync(){const t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}function checkCapabilitySync(t=!1){const e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkWorkerSync());const n=e.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(t=>"warn"===t.severity&&!t.supported).length,items:e}}async function checkWebCodecsDetailed(){try{const t=void 0!==window.VideoDecoder;if(!t)return{name:"webcodecs",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t}};const e=(navigator.userAgent||"").toLowerCase(),n=/android/.test(e)||/openharmony|arkweb/.test(e),i=2160,r=1920;let s={};const a=["avc1.42E01E","avc1.4D001F","avc1.64001F"];let o=!1,l=!1,h=!1;for(const t of a)try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:i,codedHeight:r}),a=!(null==e||!e.supported);a&&(l=!0);let h=null;if(n){try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:i,codedHeight:r,hardwareAcceleration:"prefer-software"});h=!(null==e||!e.supported)}catch(t){h=!1}h&&(o=!0)}else a&&(o=!0);s[t]={default:a,software:h}}catch(e){h=!0,s[t]={default:!1,software:null,error:"probe-failed"}}const d=o||l,c=h&&!d?"warn":"fatal";return{name:"webcodecs",supported:d,severity:c,reason:d?void 0:"warn"===c?"WebCodecs 探测异常(运行时将以实际视频配置二次确认)":"浏览器不支持 H.264 解码(默认/软解配置均不可用)",detail:{hasVideoDecoder:t,isAndroid:n,hardwareAcceleration:n?"prefer-software":"default",codecSupport:s}}}catch(t){return{name:"webcodecs",supported:!1,severity:"fatal",reason:"WebCodecs 探测失败",detail:t}}}const WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(t=>{let e=null,n=null,i=!1,r=null;const s=s=>{var a;i||(i=!0,null!==r&&clearTimeout(r),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{const t=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(t),e=new Worker(n),e.onmessage=t=>{s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=t=>{s({status:"failed",reason:"Web Worker 创建失败",detail:t})},r=setTimeout(()=>{s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}async function checkWorkerDetailed(){if("undefined"==typeof Worker)return{name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"};for(let t=1;t<=WORKER_CHECK_MAX_ATTEMPTS;t+=1){const e=await probeWorkerExecution();if("supported"===e.status)return{name:"worker",supported:!0,severity:"fatal",detail:{attempts:t}};if("failed"===e.status)return{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}}return{name:"worker",supported:!1,severity:"warn",reason:`Web Worker 创建超时(已重试 ${WORKER_CHECK_MAX_ATTEMPTS} 次)`,detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}}async function checkCapability(t=!1){const e=checkCapabilitySync(t);if(t){const t=await Promise.all([Promise.resolve(e.items.find(t=>"secureContext"===t.name)),Promise.resolve(e.items.find(t=>"audio"===t.name)),checkWorkerDetailed()]),n=t.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:t.filter(t=>"warn"===t.severity&&!t.supported).length,items:t}}const n=await Promise.all([Promise.resolve(e.items.find(t=>"secureContext"===t.name)),Promise.resolve(e.items.find(t=>"webgl2"===t.name)),Promise.resolve(e.items.find(t=>"audio"===t.name)),checkWebCodecsDetailed(),checkWorkerDetailed()]),i=n.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===i,fatalCount:i,warnCount:n.filter(t=>"warn"===t.severity&&!t.supported).length,items:n}}const OPUS_FRAME_DURATION_US=2e4,ENCODE_TIMEOUT_MS=2e3;function buildAudioEncoderConfig(t){return{codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.channels,bitrate:t.bitrate,opus:{format:"opus",frameDuration:OPUS_FRAME_DURATION_US}}}class WebCodecOpusEncoder{constructor(t={}){this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=_extends({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},t)}static async isSupported(){if("undefined"==typeof AudioEncoder)return!1;try{var t;const e=await AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}));return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===OPUS_FRAME_DURATION_US}catch(t){return!1}}async init(){this.isInitialized||(this.encoder=this.createEncoder(),this.isInitialized=!0)}async encode(t){if(!this.isInitialized||!this.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(this.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));const e=new Int16Array(t),n=this.timestamp,i=Math.round(1e6*t.length/this.config.sampleRate),r=n+i,s=i/OPUS_FRAME_DURATION_US;if(!Number.isInteger(s))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));const a=new AudioData({format:"s16",sampleRate:this.config.sampleRate,numberOfFrames:e.length,numberOfChannels:this.config.channels,timestamp:n,data:e}),o=new Promise((t,e)=>{const i=globalThis.setTimeout(()=>{this.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);this.pendingEncode={startTimestampUs:n,endTimestampUs:r,expectedFrameCount:s,chunks:[],resolve:t,reject:e,timeoutId:i}});try{this.encoder.encode(a),this.timestamp=r}catch(t){this.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{a.close()}return o}reset(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}}async destroy(){const t=this.encoder;if(t){try{await t.flush()}catch(t){}this.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{t.close()}catch(t){}}this.encoder=null,this.isInitialized=!1}createEncoder(){let t;return t=new AudioEncoder({output:e=>{this.encoder===t&&this.handleOutput(e)},error:e=>{if(this.encoder!==t)return;const n=e instanceof Error?e:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",n),this.failPending(n)}}),t.configure(buildAudioEncoderConfig(this.config)),t}handleOutput(t){const e=this.pendingEncode;if(!e)return;if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.length<e.expectedFrameCount)return;const n=e.chunks.map((t,n)=>{var i,r;const s=new Uint8Array(t.byteLength);t.copyTo(s);const a=null!=(i=null==(r=e.chunks[n+1])?void 0:r.timestamp)?i:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),i=n.reduce((t,e)=>t+e.durationMs,0);n.some(t=>t.durationMs!==OPUS_FRAME_DURATION_US/1e3)||i!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}failPending(t){const e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))}}const EBML_ID={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SegmentInfo:357149030,TimecodeScale:2807729,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,Language:2274716,CodecID:134,CodecPrivate:25506,CodecDelay:22186,SeekPreRoll:22203,Audio:225,SamplingFrequency:181,Channels:159,Cluster:524531317,Timecode:231,SimpleBlock:163};class WebMMuxer{constructor(t=16e3){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}writeHeader(){if(this.hasHeader)return;const t=this.buildEBMLHeader(),e=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(t),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(e),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}feedOpusFrame(t,e=this.frameDuration){this.hasHeader||this.writeHeader();const n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e}flush(){if(0===this.chunks.length)return new ArrayBuffer(0);const t=this.chunks.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const t of this.chunks)e.set(t,n),n+=t.length;return this.chunks=[],e.buffer}reset(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0}encodeVINT(t,e){if(void 0!==e){const n=new Uint8Array(e);for(let i=e-1;i>=0;i--)n[i]=255&t,t>>>=8;return n[0]|=1<<8-e,n}if(t<127)return new Uint8Array([128|t]);if(t<16383)return new Uint8Array([64|t>>8,255&t]);if(t<2097151)return new Uint8Array([32|t>>16,t>>8&255,255&t]);if(t<268435455)return new Uint8Array([16|t>>24,t>>16&255,t>>8&255,255&t]);throw new Error(`VINT value too large: ${t}`)}encodeID(t){return t<=255?new Uint8Array([t]):t<=65535?new Uint8Array([t>>8,255&t]):t<=16777215?new Uint8Array([t>>16,t>>8&255,255&t]):new Uint8Array([t>>>24,t>>16&255,t>>8&255,255&t])}encodeUint(t){if(0===t)return new Uint8Array([0]);const e=[];let n=t;for(;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)}encodeString(t){return(new TextEncoder).encode(t)}encodeFloat32(t){const e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)}encodeElement(t,e){const n=this.encodeID(t),i=this.encodeVINT(e.length),r=new Uint8Array(n.length+i.length+e.length);return r.set(n,0),r.set(i,n.length),r.set(e,n.length+i.length),r}encodeUintElement(t,e){return this.encodeElement(t,this.encodeUint(e))}encodeStringElement(t,e){return this.encodeElement(t,this.encodeString(e))}encodeFloat32Element(t,e){return this.encodeElement(t,this.encodeFloat32(e))}concatArrays(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let i=0;for(const e of t)n.set(e,i),i+=e.length;return n}buildEBMLHeader(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.EBMLVersion,1),this.encodeUintElement(EBML_ID.EBMLReadVersion,1),this.encodeUintElement(EBML_ID.EBMLMaxIDLength,4),this.encodeUintElement(EBML_ID.EBMLMaxSizeLength,8),this.encodeStringElement(EBML_ID.DocType,"webm"),this.encodeUintElement(EBML_ID.DocTypeVersion,4),this.encodeUintElement(EBML_ID.DocTypeReadVersion,2)]);return this.encodeElement(EBML_ID.EBML,t)}buildSegmentInfo(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.TimecodeScale,1e6),this.encodeStringElement(EBML_ID.MuxingApp,"xmov-avatar-sdk"),this.encodeStringElement(EBML_ID.WritingApp,"xmov-avatar-sdk")]);return this.encodeElement(EBML_ID.SegmentInfo,t)}buildOpusTracks(){const t=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),e=this.concatArrays([this.encodeFloat32Element(EBML_ID.SamplingFrequency,this.sampleRate),this.encodeUintElement(EBML_ID.Channels,1)]),n=this.concatArrays([this.encodeUintElement(EBML_ID.TrackNumber,1),this.encodeUintElement(EBML_ID.TrackUID,1),this.encodeUintElement(EBML_ID.TrackType,2),this.encodeUintElement(EBML_ID.FlagLacing,0),this.encodeStringElement(EBML_ID.Language,"und"),this.encodeStringElement(EBML_ID.CodecID,"A_OPUS"),this.encodeElement(EBML_ID.CodecPrivate,t),this.encodeUintElement(EBML_ID.CodecDelay,0),this.encodeUintElement(EBML_ID.SeekPreRoll,8e7),this.encodeElement(EBML_ID.Audio,e)]),i=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,i)}buildCluster(t,e){const n=this.encodeUintElement(EBML_ID.Timecode,t),i=this.encodeVINT(1),r=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([i,r,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)}}class PcmWebMEncoder{constructor(){this.opusEncoder=new WebCodecOpusEncoder({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new WebMMuxer(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}static isSupported(){return WebCodecOpusEncoder.isSupported()}async init(){await this.opusEncoder.init()}async encode(t){var e=this;if(1600!==t.length)throw new Error(`PCM 音频块必须为 1600 samples,实际为 ${t.length}`);if(this.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");this.pendingBlocks+=1;const n=this.generation,i=new Int16Array(t),r=this.queue.then(async function(){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);const t=await e.opusEncoder.encode(i);if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(const n of t)e.muxer.feedOpusFrame(n.data,n.durationMs);return e.muxer.flush()}).finally(()=>{this.pendingBlocks-=1});return this.queue=r.then(()=>{},()=>{}),r}reset(){const t=++this.generation;this.queue=this.queue.then(()=>{this.destroyed||t!==this.generation||(this.opusEncoder.reset(),this.muxer.reset())})}async destroy(){this.destroyed=!0,this.generation+=1,await this.opusEncoder.destroy(),await this.queue,this.muxer.reset()}}class MediaRecorderEncoder{constructor(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}static isSupported(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")}async init(){const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=new t({sampleRate:16e3});const e=new Blob(["\n class PCMInjectorProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(0);\n this.port.onmessage = (e) => {\n if (e.data.type === 'pcm') {\n const int16 = new Int16Array(e.data.pcm);\n const float32 = new Float32Array(int16.length);\n for (let i = 0; i < int16.length; i++) {\n float32[i] = int16[i] / 32768;\n }\n const newBuffer = new Float32Array(this.buffer.length + float32.length);\n newBuffer.set(this.buffer);\n newBuffer.set(float32, this.buffer.length);\n this.buffer = newBuffer;\n }\n };\n }\n process(inputs, outputs) {\n const output = outputs[0][0];\n if (!output) return true;\n const len = Math.min(output.length, this.buffer.length);\n for (let i = 0; i < len; i++) {\n output[i] = this.buffer[i];\n }\n this.buffer = this.buffer.slice(len);\n for (let i = len; i < output.length; i++) {\n output[i] = 0;\n }\n return true;\n }\n }\n registerProcessor('pcm-injector-processor', PCMInjectorProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(e);await this.audioCtx.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-injector-processor"),this.destination=this.audioCtx.createMediaStreamDestination(),this.workletNode.connect(this.destination);const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";this.recorder=new MediaRecorder(this.destination.stream,{mimeType:i,audioBitsPerSecond:24e3}),this.recorder.ondataavailable=t=>{t.data&&t.data.size>0&&t.data.arrayBuffer().then(t=>{if(this.nextResolve){const e=this.nextResolve;this.nextResolve=null,e(t)}else this.dataQueue.push(t)})},"suspended"===this.audioCtx.state&&await this.audioCtx.resume()}async feedPCM(t){return this.workletNode&&this.recorder?(this.isRecording||(this.recorder.start(100),this.isRecording=!0),this.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),this.dataQueue.length>0?this.dataQueue.shift():new Promise(t=>{const e=setTimeout(()=>{this.nextResolve=null,t(null)},200);this.nextResolve=n=>{clearTimeout(e),t(n)}})):null}reset(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}destroy(){var t,e;if(this.nextResolve=null,this.dataQueue=[],this.recorder)try{"inactive"!==this.recorder.state&&this.recorder.stop()}catch(t){}null==(t=this.workletNode)||t.disconnect(),null==(e=this.destination)||e.disconnect();try{var n;null==(n=this.audioCtx)||n.close()}catch(t){}this.recorder=null,this.workletNode=null,this.destination=null,this.audioCtx=null}}class XmovAvatar{constructor(t){if(this.TAG="[XMOV AVATAR]",this.el=null,this.status=-1,this.networkMonitor=null,this.ttsa=null,this.debugOverlay=null,this._offlineTimer=-1,this._offlineInterval=300,this._env="production",this.avatarCanvasVisible=!0,this.pendingInvisibleMode=!1,this.isInitialized=!1,this.onStateChange=()=>{},this.onDownloadProgress=null,this.replayData=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.enableClientInterrupt=!1,this.retryCount=1,this.retryTimer=-1,this.maxRetryCount=9,this.retryRound=1,this.maxRetryRound=3,this.isRetrying=!1,this.isStartRetry=!1,this.destroyed=!1,this.incompleteInitializationCleanupPromise=null,this.captureAudioCtx=null,this.captureWorklet=null,this.captureSource=null,this.captureSetupPromise=null,this.captureLastSpeechId=-2,this.restartPlaybackCaptureImpl=null,this.captureEncodeQueue=Promise.resolve(),this.captureGeneration=0,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmWebMEncoder=null,this.mediaRecorderEncoder=null,this.pcmCaptureMode="none",this.pcmEncodeId=0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this._isClientMode=!1,this._streamingClient=null,this._videoPlayer=null,this._eventDispatcher=null,this._apiForwarder=null,this._clientOnDownloadProgress=null,this._pendingInit=!1,this._pendingInitConfig=null,this._clientSessionId="",this.handleBeforeUnload=()=>{this.destroy("beforeunload")},window.avatarSDKLogger.setEnabled(t.enableLogger),this.options=t,this._env=t.env||"production",this.enableClientInterrupt=t.enableClientInterrupt||!1,this.boundVisibilityChange=this.visibilitychange.bind(this),"client"===t.renderMode)return this._isClientMode=!0,void this.initializeClient(t);this.initializeSDK(t),this.networkMonitor=new NetworkMonitor({offlineCallback:t=>{if(this.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_offline_before_init");this.status!==AvatarStatus.offline&&this.offlineHandle()},onlineCallback:t=>{var e;if(this.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_online_before_init");null==(e=this.ttsa)||e.clearReconnectTimer(),this.isStartRetry&&this.triggerReconnect()}})}getStatus(){return this.status}getIsInitialized(){return this.isInitialized}get businessENV(){return this._env}getUniqueSpeakId(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||`0-${this.getSessionId()}`}async initializeSDK(t){var e,n,i;if(!navigator.onLine)return void this.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"});const r=this,s=t,{containerId:a,container:o,appId:l,appSecret:h,gatewayServer:d,cacheServer:c,config:u}=t,{scale:f=1}=null!=(e=null==u||null==(n=u.layout)?void 0:n.avatar)?e:{};null!=u&&null!=(i=u.layout)&&null!=(i=i.avatar)&&i.scale&&(u.layout.avatar.scale=validateScaleWithDecimal(f,"initializeSDK"));const p=_extends({},u||{},{raw_audio:!isSupportMES()});if(o&&o instanceof HTMLElement)this.el=o;else{const t=document.querySelector(a);if(!t)return void this.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${a} 不存在`});this.el=t}const _=document.createElement("div");_.setAttribute("id","avatar-bg-container"),_.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),this.el.appendChild(_);const m=this.el.getAttribute("style");this.el.setAttribute("style",m?`position:relative;overflow:hidden;${m}`:"position:relative;overflow:hidden;"),this.resourceManager=new ResourceManager({sdkInstance:this,headers:t.headers,tag:t.tag,gateway_type:t.gateway_type||"default",asr_id:t.asr_id,llm_id:t.llm_id,session_speak_req_id:t.session_speak_req_id,sessionRequestData:s.sessionRequestData,appId:l,appSecret:h,gatewayServer:d,cacheServer:c,config:p,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo(e){r.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:t=>{var e,n;null==(e=(n=this.options).onStartSessionWarning)||e.call(n,t)}}),this.renderScheduler=new RenderScheduler({sdkInstance:this,container:this.el,resourceManager:this.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:this.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:t=>{var e,n,i,s;null==(e=this.onDownloadProgress)||e.call(this,t),null==(n=this.el)||n.setAttribute("style",(null==(i=this.el)?void 0:i.style.cssText)+`opacity:${100===t?"1":"0"};`),this.isInitialized=100===t,100===t&&(this.pendingInvisibleMode||this.status===AvatarStatus.online||this.status===AvatarStatus.invisible||this.onStatusChange(AvatarStatus.online),this.resourceManager._setOfflineCache(),null==(s=this.ttsa)||s.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(()=>{var t,e;null==(t=this.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.1.0",resolution:null==(e=this.resourceManager.getConfig())?void 0:e.resolution,download_speed:r.networkInfo.downlink||0}))},20),this.enableAudioPlaybackCapture())},onStateChange:e=>{this.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:(e,n)=>{null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&this.getStatus()!==AvatarStatus.online||!this.isInitialized||(window.avatarSDKLogger.log(this.TAG,"Status:===== 渲染中,状态: rendering",this.getSessionId()),this.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:(e,n,i)=>{null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,i)},onWalkStateChange:e=>{null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:t=>{var e;null==(e=this.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:(e,n)=>{null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:t=>{var e;null==(e=this.debugOverlay)||e.setAudioInfo(t)},setEventData:t=>{var e;null==(e=this.debugOverlay)||e.setEventData(t)},renderFrameCallback:t=>{this.renderFrameCallback(t),this.handleReplaySend(t)},reportMessage:t=>{this.onMessage(t)},sendSdkPoint:(t,e,n)=>{var i;null==(i=this.ttsa)||i.sendSdkPoint(t,e,n)},sendMessage:(t,e)=>{var n;null==(n=this.ttsa)||n.send(t,e)},onFPSUpdate:e=>{null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:e=>{null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=u&&u.walk_config&&this.changeWalkConfig(u.walk_config),null!=u&&u.layout&&this.changeLayout(u.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{}}initializeClient(t){const{containerId:e,container:n}=t;if(n&&n instanceof HTMLElement)this.el=n;else{const t=document.querySelector(e);var i,r;if(!t)return void(null==(i=(r=this.options).onMessage)||i.call(r,{code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${e} 不存在`}));this.el=t}const s=this.el.getAttribute("style");this.el.setAttribute("style",s?`position:relative;overflow:hidden;${s}`:"position:relative;overflow:hidden;"),this._eventDispatcher=new EventDispatcher({onStateChange:t.onStateChange,onSpeakStateChange:t.onSpeakStateChange,onVoiceStateChange:t.onVoiceStateChange,onStatusChange:t.onStatusChange,onRenderChange:t.onRenderChange,onWalkStateChange:t.onWalkStateChange,onWidgetEvent:t.onWidgetEvent,onMessage:t.onMessage,onNetworkInfo:t.onNetworkInfo,onFPSUpdate:t.onFPSUpdate,onFrameDataUpdate:t.onFrameDataUpdate,onDownloadProgress:t=>{var e;null==(e=this._clientOnDownloadProgress)||e.call(this,t),t>=100&&!this.isInitialized&&(this.isInitialized=!0)},onSessionId:t=>{this._clientSessionId=t,window.avatarSDKLogger.log(this.TAG,"[client] 收到 session_id:",t)}});const a=t.streamingServer||`ws://${location.hostname}:8080`;this._streamingClient=new StreamingClient({url:a,onReady:()=>{if(window.avatarSDKLogger.log(this.TAG,"[client] 双方就绪,等待 Server 推流..."),this._pendingInit){var t;this._pendingInit=!1;const e=this._pendingInitConfig;this._pendingInitConfig=null,window.avatarSDKLogger.log(this.TAG,"[client] 补发 init 命令"),null==(t=this._apiForwarder)||t.init(e)}},onOffer:t=>{var e;null==(e=this._videoPlayer)||e.handleOffer(t)},onIce:t=>{var e;null==(e=this._videoPlayer)||e.addIceCandidate(t)},onEventProxy:(t,e,n)=>{var i;null==(i=this._eventDispatcher)||i.dispatch(t,e,n)},onError:t=>{var e,n;null==(e=(n=this.options).onMessage)||e.call(n,{code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:()=>{window.avatarSDKLogger.log(this.TAG,"[client] WebRTC 已连接"),this.onStatusChange(AvatarStatus.online)},onDisconnected:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)}renderFrameCallback(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()}async init(t){const e=await checkCapability(this.options.audioOnlyMode);if(!e.supported){const t=`浏览器能力检查失败: ${e.items.filter(t=>"fatal"===t.severity&&!t.supported).map(t=>t.reason).join("; ")}`;return void this.onMessage({code:EErrorCode.INIT_ERROR,message:t})}if(this.destroyed=!1,this.isInitialized=!1,this.incompleteInitializationCleanupPromise=null,this.startConnectTime=Date.now(),this._isClientMode){var n;this._clientOnDownloadProgress=t.onDownloadProgress||null;const e={appId:this.options.appId,appSecret:this.options.appSecret,gatewayServer:this.options.gatewayServer,cacheServer:this.options.cacheServer,headers:this.options.headers,tag:this.options.tag,gateway_type:this.options.gateway_type,env:this.options.env,config:this.options.config,hardwareAcceleration:this.options.hardwareAcceleration,enableDebugger:this.options.enableDebugger,initModel:t.initModel,scaleDownBy:this.options.scaleDownBy||1,useAlphaMask:this.options.useAlphaMask};var i;return void(null!=(n=this._streamingClient)&&n.isConnected()?null==(i=this._apiForwarder)||i.init(e):(this._pendingInit=!0,this._pendingInitConfig=e,window.avatarSDKLogger.log(this.TAG,"[client] WebSocket 未连接,init 命令暂存")))}const{onDownloadProgress:r,initModel:s}=t;this.onDownloadProgress=t=>{15===t&&(this.sessionResTime=Date.now()),80===t&&(this.charbinResTime=Date.now()),r(t)},s===InitModel.invisible&&(this.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render);const a=await this.resourceManager.load(this.onDownloadProgress.bind(this));if(this.destroyed)window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after resourceManager load");else{if(null!=a&&a.socket_io_url&&null!=a&&a.token)return this.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),this.debugOverlay=new DebugOverlay(this,a),this.ttsa=this.connectTtsa(a),this.renderScheduler.init(),this.renderScheduler.setAvatarCanvasVisible(this.avatarCanvasVisible),window.performanceTracker.setReportFunc(this.ttsa),window.addEventListener("beforeunload",this.handleBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange),a;window.avatarSDKLogger.error(this.TAG,"init error, socket_io_url or token is empty reload")}}setAudioPlaybackDataHandler(t){this.options.onAudioPlaybackData=t}restartAudioPlaybackCapture(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)}enableAudioPlaybackCapture(){return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(()=>{this.captureSetupPromise=null}):this.setupAudioCapture().finally(()=>{this.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve();var t}async setupAudioCapture(){var t=this;const e=document.getElementById("xmov-avatar-audio");if(e&&this.options.onAudioPlaybackData&&!this.captureAudioCtx&&!this.captureSource)if(void 0!==window.AudioWorkletNode)try{var n;if(!await PcmWebMEncoder.isSupported())return void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"});if(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==this.captureAudioCtx.sampleRate)throw new Error(`浏览器无法创建 16000 Hz AudioContext: ${this.captureAudioCtx.sampleRate}`);this.captureSource=this.captureAudioCtx.createMediaElementSource(e),this.captureSource.connect(this.captureAudioCtx.destination);let i=!1,r=!0,s=0,a=0;const o=t=>{const e=++this.captureGeneration;i=!0,r=!0,s=Date.now()-100,a=0,this.captureLastSpeechId=t,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var t;e===this.captureGeneration&&(null==(t=this.pcmWebMEncoder)||t.reset())})},l=()=>{const t=++this.captureGeneration;i=!1,this.captureLastSpeechId=-2,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var e;t===this.captureGeneration&&(null==(e=this.pcmWebMEncoder)||e.reset())})};this.restartPlaybackCaptureImpl=()=>{i&&o(this.renderScheduler.getSpeechId())};const h=new Blob(["\n class AudioCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms @ 16kHz\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const input = inputs[0];\n if (input && input.length > 0 && input[0] && input[0].length > 0) {\n const frameCount = input[0].length;\n\n for (let i = 0; i < frameCount; i++) {\n let sample = 0;\n for (let channel = 0; channel < input.length; channel++) {\n sample += input[channel][i] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / input.length;\n\n // 缓冲区满 1600 采样点时,检测静音并发送到主线程\n if (this.bufferIndex >= 1600) {\n // 检测是否全是静音(全零或极低值)\n let hasAudio = false;\n for (let j = 0; j < 1600; j++) {\n if (Math.abs(this.buffer[j]) > 0.0001) {\n hasAudio = true;\n break;\n }\n }\n\n const pcm = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const value = Math.max(-1, Math.min(1, this.buffer[j]));\n pcm[j] = value < 0 ? value * 0x8000 : value * 0x7fff;\n }\n this.port.postMessage(\n { hasAudio: hasAudio, pcmData: pcm.buffer },\n [pcm.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n }\n return true;\n }\n }\n registerProcessor('audio-capture-processor', AudioCaptureProcessor);\n "],{type:"application/javascript"}),d=URL.createObjectURL(h);if(await this.captureAudioCtx.audioWorklet.addModule(d),URL.revokeObjectURL(d),this.captureWorklet=new AudioWorkletNode(this.captureAudioCtx,"audio-capture-processor"),this.captureSource.connect(this.captureWorklet),this.captureWorklet.connect(this.captureAudioCtx.destination),this.captureEncodeQueue=Promise.resolve(),this.captureWorklet.port.onmessage=e=>{if(!this.options.onAudioPlaybackData)return;const{hasAudio:n,pcmData:h}=e.data,d=this.renderScheduler.getSpeechId();if(n&&!i||n&&i&&d!==this.captureLastSpeechId?o(d):!n&&i&&l(),!(n&&i&&h instanceof ArrayBuffer))return;const c=this.captureGeneration,u=r;r=!1;const f=s+100*a;a+=1,this.captureEncodeQueue=this.captureEncodeQueue.then(async function(){var e;const n=await(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(h)));n&&0!==n.byteLength&&c===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:n,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:f,speech_id:d}))}).catch(t=>{var e;null==(e=window.avatarSDKLogger)||e.error(this.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",t)})},"suspended"===this.captureAudioCtx.state&&await this.captureAudioCtx.resume(),"running"!==this.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(n=window.avatarSDKLogger)||n.log(this.TAG,"[AudioCapture] 初始化成功,采样率:",this.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}catch(t){var i,r;if(this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}try{var s;null==(s=this.captureSource)||s.disconnect()}catch(t){}this.captureSource=null,this.captureAudioCtx&&"closed"!==this.captureAudioCtx.state&&await this.captureAudioCtx.close().catch(()=>{}),this.captureAudioCtx=null,null==(i=this.pcmWebMEncoder)||i.destroy(),this.pcmWebMEncoder=null,null==(r=window.avatarSDKLogger)||r.error(this.TAG,"[AudioCapture] 初始化失败:",t)}else this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"})}async setupPCMCapture(){var t,e=this;if(!this.options.onAudioPlaybackData)return;const n=null==(t=this.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();var i;if(!n)return void(null==(i=window.avatarSDKLogger)||i.error(this.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"));const r=await PcmWebMEncoder.isSupported(),s=MediaRecorderEncoder.isSupported();var a;if(!r&&!s)return null==(a=window.avatarSDKLogger)||a.warn(this.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});try{var o;r?(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.pcmCaptureMode="webcodec"):(this.mediaRecorderEncoder=new MediaRecorderEncoder,await this.mediaRecorderEncoder.init(),this.pcmCaptureMode="mediarecorder"),this.restartPlaybackCaptureImpl=()=>{var t,e;this.pcmCaptureFirstChunk=!0,this.pcmCaptureLastSpeechId=this.renderScheduler.getSpeechId(),this.pcmEncodeId++,null==(t=this.pcmWebMEncoder)||t.reset(),null==(e=this.mediaRecorderEncoder)||e.reset(),n.resetCaptureBuffer()},await n.attachCapture(async function({pcmData:t,hasAudio:i}){try{if(!e.options.onAudioPlaybackData)return;const d=Date.now()-100;if(!n.isPlaying)return void n.resetCaptureBuffer();const c=e.renderScheduler.getSpeechId();var r,s;if(c!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=c,e.pcmEncodeId++,null==(r=e.pcmWebMEncoder)||r.reset(),null==(s=e.mediaRecorderEncoder)||s.reset(),n.resetCaptureBuffer()),!i)return;const u=e.pcmEncodeId;let f=null;const p=performance.now();if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){const n=new Int16Array(t);var a;if(f=await e.pcmWebMEncoder.encode(n),u!==e.pcmEncodeId)return void(null==(a=window.avatarSDKLogger)||a.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(0===f.byteLength)return;const i=performance.now()-p;var o;i>10&&(null==(o=window.avatarSDKLogger)||o.warn(e.TAG,`[PCMCapture] WebCodecs 编码耗时过长: ${i.toFixed(2)}ms`))}else if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder){var l;if(f=await e.mediaRecorderEncoder.feedPCM(t),u!==e.pcmEncodeId)return void(null==(l=window.avatarSDKLogger)||l.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(!f)return;const n=performance.now()-p;var h;n>10&&(null==(h=window.avatarSDKLogger)||h.warn(e.TAG,`[PCMCapture] MediaRecorder 编码耗时过长: ${n.toFixed(2)}ms`))}if(!f)return;const _=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:f,codec:"opus",isFirstChunk:_,sampleRate:16e3,samples:1600,timestamp:d,speech_id:c})}catch(t){var d;null==(d=window.avatarSDKLogger)||d.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}}),null==(o=window.avatarSDKLogger)||o.log(this.TAG,`[PCMCapture] PCM 捕获初始化成功,编码路径: ${this.pcmCaptureMode}`)}catch(t){var l,h,d;null==(l=window.avatarSDKLogger)||l.error(this.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(h=this.pcmWebMEncoder)||h.destroy(),this.pcmWebMEncoder=null,null==(d=this.mediaRecorderEncoder)||d.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureMode="none"}}visibilitychange(){if(document.hidden){var t;const i=null==(t=this.renderScheduler)?void 0:t.getRenderState();var e,n;i===RenderState.rendering||i===RenderState.resumed?null==(e=this.renderScheduler)||e.pauseRender():null==(n=this.renderScheduler)||n.pauseForBackground()}else{var i,r,s,a;if((null==(i=this.renderScheduler)?void 0:i.getRenderState())===RenderState.paused)null==(a=this.renderScheduler)||a.resumeRender();else if(null!=(r=this.ttsa)&&r.getStatus()){var o;null==(o=this.renderScheduler)||o.forceSyncDecoder()}null!=(s=this.ttsa)&&s.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode()),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(()=>{})}}setReplayData(t){this.replayData=t}handleReplaySend(t){if(!this.replayData)return;const e=this.replayData.filter(e=>Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type);for(const t of e){var n;"state_change"===t.event_type?null==(n=this.ttsa)||n.stateChange(t.event_data.state,t.event_data.params):"send_text"===t.event_type?this.speak(t.event_data.ssml,t.event_data.is_start,t.event_data.is_end,t.event_data.extra):window.avatarSDKLogger.log(this.TAG,`[handleReplaySend] 未知事件类型: ${t}`)}}connectTtsa(t){return window.performanceTracker.markStart(performanceConstant.ttsa_connect),window.performanceTracker.markStart(performanceConstant.ttsa_ready),new Ttsa({sdkInstance:this,url:t.socket_io_url,room:t.room,session_id:t.session_id,token:t.token,framedata_proto_version:this.resourceManager.getConfig().framedata_proto_version,reconnect_client_timeout:(null==t?void 0:t.reconnect_client_timeout)||0,reconnect_timeout:(null==t?void 0:t.reconnect_timeout)||0,appInfo:_extends({},this.resourceManager.getAppInfo(),{env:this._env}),onReady:()=>{var e,n,i,r,s,a;null==(e=this.ttsa)||e.sendSdkPoint("connect_sdk",{timestamp:this.startConnectTime}),null==(n=this.ttsa)||n.sendSdkPoint("connect_sdk_success",{timestamp:this.connectSuccessTime}),null==(i=this.ttsa)||i.sendSdkPoint("session_processing_time",{timestamp:this.sessionResTime}),null==(r=this.ttsa)||r.sendSdkPoint("Char_bin_download_time",{timestamp:this.charbinResTime}),null==(s=this.ttsa)||s.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),this.onTtsaReady(t),null==(a=this.ttsa)||a.syncTimestamp()},handleMessage:(t,e)=>{var n;this.isfirstReceive&&t===EFrameDataType.BODY&&(null==(n=this.ttsa)||n.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),this.isfirstReceive=!1),this.renderScheduler.handleData(t,e)},handleAAFrame:t=>{var e,n;null==(e=(n=this.options).onAAFrameHandle)||e.call(n,t)},runStartFrameIndex:t=>{this.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:t=>{this.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:()=>{this.reloadSuccess()},enterOfflineMode:()=>{this.offlineHandle()},reStartSDK:()=>{this.reStartSession()},sendVoiceEnd:()=>{var t;null==(t=this.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:()=>{var t,e;return null!=(t=null==(e=this.renderScheduler)?void 0:e.getCurrentFrameIndex())?t:0}})}start(){var t;this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online),this.renderScheduler.render(),null==(t=this.ttsa)||t.start()}onTtsaReady(t){this.start()}async _reload(){const t=await this.resourceManager._reload();if(t&&!this.destroyed){if(await this.onSessionReloaded(t),this.destroyed)return null;this.ttsa=this.connectTtsa(t),this.ttsa._setResumeInfoCallback(this.resourceManager._getSessionId(),this.renderScheduler._getResumeInfo.bind(this.renderScheduler))}return t}async onSessionReloaded(t){}onSessionReloadExhausted(t){}async restartSessionForTransport(t){var e;this.renderScheduler.interrupt("in_offline_mode"),await this.resourceManager.stopSession(t),this.destroyed||(null==(e=this.ttsa)||e.close(),this.status!==AvatarStatus.offline&&this.offlineHandle(),this.reStartSession())}cancelSessionRestart(){this.resetRetryState(),this.clearAllRetryTimers()}reloadSuccess(){var t;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(()=>{window.clearInterval(this._offlineTimer)},1e3)}async stop(){await this.renderScheduler.stop()}isDestroyed(){return this.destroyed}async destroyClient(){var t,e,n;if(this.destroyed)return void window.avatarSDKLogger.warn(this.TAG,"SDK 已销毁,忽略重复销毁请求");if(this.destroyed=!0,this._isClientMode)return this._streamingClient&&(this._streamingClient.destroy(),this._streamingClient=null),this._videoPlayer&&(this._videoPlayer.destroy(),this._videoPlayer=null),this._eventDispatcher=null,this._apiForwarder=null,this.el=null,window.removeEventListener("beforeunload",this.handleBeforeUnload),void window.avatarSDKLogger.log(this.TAG,"薄客户端 SDK 已销毁");if(this.cancelSessionRestart(),-1!==this._offlineTimer&&(clearInterval(this._offlineTimer),this._offlineTimer=-1),this.ttsa&&(this.ttsa.close(),this.ttsa=null),this.renderScheduler&&this.renderScheduler.destroy(),this.resourceManager&&this.resourceManager.destroy(),this.debugOverlay&&(this.debugOverlay.destroy(),this.debugOverlay=null),this.networkMonitor)try{this.networkMonitor.destroy(),this.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(this.TAG,"销毁 networkMonitor 时出错",t)}if(this.pcmEncodeId++,this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}if(this.captureSource){try{this.captureSource.disconnect()}catch(t){}this.captureSource=null}if(this.captureAudioCtx){try{this.captureAudioCtx.close()}catch(t){}this.captureAudioCtx=null}const i=null==(t=this.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();i&&i.detachCapture(),null==(e=this.pcmWebMEncoder)||e.destroy(),this.pcmWebMEncoder=null,null==(n=this.mediaRecorderEncoder)||n.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmCaptureMode="none",this.el=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",this.handleBeforeUnload),document.removeEventListener("visibilitychange",this.boundVisibilityChange),window.avatarSDKLogger.log(this.TAG,"SDK 已销毁")}async destroy(t="user"){var e,n;if(this.replayData=null,this._isClientMode)return null==(n=this._apiForwarder)||n.destroy(t),await this.destroyClient(),void this.onStatusChange(AvatarStatus.close);null==(e=this.ttsa)||e.sendSdkPoint("close_session",{reason:t});const i=await this.resourceManager.stopSession(t);return await this.destroyClient(),i&&this.onStatusChange(AvatarStatus.close),i}idle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())}listen(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())}think(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())}interactiveidle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())}speak(t,e=!0,n=!0,i={client_speak_id:"",client_frame:0}){var r,s,a,o;if(this._isClientMode)return void(null==(o=this._apiForwarder)||o.speak(t,e,n,i));this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),i.client_frame=null!=(r=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?r:0;const l=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,i);return this.renderScheduler.resume(),l}setOffsetFrame(t){this.renderScheduler.setOffsetFrame(t)}syncTimestamp(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)}notifyEnterInvisibleMode(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()}notifyExitInvisibleMode(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()}setVolume(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)}getSessionId(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id}showDebugInfo(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())}hideDebugInfo(){var t;null==(t=this.debugOverlay)||t.hide()}changeAvatarVisible(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)}cleanupBeforeInitComplete(t){var e,n=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,`清理初始化未完成的资源,原因: ${t}`),this.isInitialized=!1;const i=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==i||i.catch(t=>{window.avatarSDKLogger.warn(this.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=async function(){try{await i,await n.destroyClient()}catch(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)}}(),this.incompleteInitializationCleanupPromise}reportInitializationFailure(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e})}offlineHandle(){this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(()=>{if(this.status!==AvatarStatus.offline)return clearInterval(this._offlineTimer),void(this._offlineTimer=-1);this.renderScheduler._offlineRun()},this._offlineInterval)}async stopSessionFromSocket(t){await this.resourceManager.stopSession(t)}offlineMode(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()}onlineMode(){NetworkMonitor.ONLINE&&this._reload()}onMessage(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(i){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",i)}const i=Errors(t);t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&this.options.onMessage(i),null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(i)}onStatusChange(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))}switchInvisibleMode(){var t,e;this._isClientMode?null==(t=this._apiForwarder)||t.switchInvisibleMode():this.renderScheduler?this.status===AvatarStatus.visible||this.status===AvatarStatus.online?this.setInvisibleMode():(this.notifyExitInvisibleMode(),this.renderScheduler.switchInvisibleMode(),this.listen()):null==(e=window.avatarSDKLogger)||e.warn(this.TAG,"RenderScheduler 未初始化,无法切换隐身模式")}setInvisibleMode(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)}getPendingInvisibleMode(){return this.pendingInvisibleMode||!1}getRenderState(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init}changeLayout(t){var e,n;if(this._isClientMode)return void(null==(n=this._apiForwarder)||n.changeLayout(t));const{scale:i=1}=t.avatar||{};t.avatar.scale=validateScaleWithDecimal(i,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}changeWalkConfig(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))}interrupt(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)}triggerReconnect(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()}reStartSession(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())}async _retryImpl(){var t=this;if(this.retryRound>this.maxRetryRound||!this.isRetrying)return;let e=1e3;this.retryCount>1&&(e=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(async function(){if(t.retryTimer=-1,t.isRetrying&&!t.destroyed)try{const e=await t._reload();if(!t.isRetrying||t.destroyed)return;if(null===e){if(t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试达最大轮次(${t.maxRetryRound})+每轮最大次数(${t.maxRetryCount}),总次数=${t.maxRetryRound*t.maxRetryCount},停止重试`),t.onSessionReloadExhausted(),void t.resetRetryState();window.avatarSDKLogger.warn(t.TAG,`第${t.retryRound}轮重试次数达上限(${t.maxRetryCount}),进入第${t.retryRound+1}轮重试`),t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t._retryImpl()}else t.renderScheduler.stopAudio(-1),window.avatarSDKLogger.log(t.TAG,`第${t.retryRound}轮第${t.retryCount}次重试成功,停止重试`),t.resetRetryState()}catch(e){if(window.avatarSDKLogger.error(t.TAG,"重试过程异常",e),t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试异常且达总次数上限(${t.maxRetryRound*t.maxRetryCount}),停止重试`),t.onSessionReloadExhausted(e),void t.resetRetryState();t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t.retryRound<=t.maxRetryRound&&t.isRetrying?t._retryImpl():t.resetRetryState()}},e)}clearAllRetryTimers(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)}resetRetryState(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1}seekToFrame(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)}async startRecoder(){try{var t,e;const n=null==(t=this.el)?void 0:t.querySelector("canvas"),i=null==(e=this.el)?void 0:e.querySelector("audio");if(!n||!i)return void console.error("找不到 canvas 或 audio 元素");const r=n.captureStream(60);let s=[];if(this.captureSource&&this.captureAudioCtx){const t=this.captureAudioCtx.createMediaStreamDestination();this.captureSource.connect(t),s=t.stream.getAudioTracks()}else if("function"==typeof i.captureStream)s=i.captureStream().getAudioTracks();else{if("function"!=typeof i.mozCaptureStream)return void window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频");s=i.mozCaptureStream().getAudioTracks()}this.stream=new MediaStream([...r.getVideoTracks(),...s]),this.recordedChunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),this.mediaRecorder.ondataavailable=t=>{t.data&&t.data.size>0&&this.recordedChunks.push(t.data)},this.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}}stopRecoder(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(t=>t.stop()),window.avatarSDKLogger.log("⏹ 停止录制"))}exportVideo(){if(!this.recordedChunks.length)return void window.avatarSDKLogger.error("没有录制到数据");const t=new Blob(this.recordedChunks,{type:"video/mp4"}),e=URL.createObjectURL(t),n=document.createElement("a");n.href=e,n.download=`录制_${(new Date).getTime()}.mp4`,n.click(),window.avatarSDKLogger.log("✅ 下载成功,大小:",t.size)}getOptions(){return this.options}simulateContextLoss(t=5e3,e=!1){this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}getRecoveryStatus(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null}async testStagedRecovery(){if(this.renderScheduler)return this.renderScheduler.testStagedRecovery();window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}restartWebGL(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)}}XmovAvatar.IBRAnimationGeneratorCharInfo_NN=IBRAnimationGeneratorCharInfo_NN,XmovAvatar.unpackIBRAnimation=unpackIBRAnimation,XmovAvatar.formatMJT=formatMJT,XmovAvatar.getVertices=getVertices,XmovAvatar.getPCATextures=getPCATextures,XmovAvatar.getWavefrontObjFromVertices=getWavefrontObjFromVertices,XmovAvatar.GLDevice=GLDevice,XmovAvatar.GLPipeline=GLPipeline,XmovAvatar.checkCapability=checkCapability;export{XmovAvatar as default};
1
+ function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},_extends.apply(null,arguments)}var EErrorCode;!function(t){t[t.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",t[t.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",t[t.START_SESSION_ERROR=10003]="START_SESSION_ERROR",t[t.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",t[t.INIT_ERROR=10005]="INIT_ERROR",t[t.SOCKET_QUIT=10006]="SOCKET_QUIT",t[t.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",t[t.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",t[t.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",t[t.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",t[t.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",t[t.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",t[t.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",t[t.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",t[t.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",t[t.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",t[t.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",t[t.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",t[t.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",t[t.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",t[t.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",t[t.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",t[t.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",t[t.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",t[t.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",t[t.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",t[t.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",t[t.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",t[t.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",t[t.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",t[t.TTSA_ERROR=40006]="TTSA_ERROR",t[t.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",t[t.NETWORK_DOWN=50001]="NETWORK_DOWN",t[t.NETWORK_UP=50002]="NETWORK_UP",t[t.NETWORK_RETRY=50003]="NETWORK_RETRY",t[t.NETWORK_BREAK=50004]="NETWORK_BREAK",t[t.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",t[t.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",t[t.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",t[t.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",t[t.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",t[t.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",t[t.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",t[t.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(EErrorCode||(EErrorCode={}));const ERROR_CODE_MAP={10001:3101,10002:3102,10003:3103,10004:3104,10005:3105,10006:3106,10007:3107,20001:3201,20002:3202,20003:3203,20004:3204,20005:3205,20006:3206,20007:3207,20008:3208,20009:3209,20010:3210,20011:3211,30001:3301,30002:3302,30003:3303,30004:3304,30005:3305,30006:3306,30007:3307,40001:3401,40002:3402,40003:3403,40004:3404,40005:3405,40006:3406,40007:3407,50001:3501,50002:3502,50003:3503,50004:3504,60001:3601,60002:3602,60003:3603,60004:3604,60005:3605,60006:3606,60007:3607,60008:3608},ERROR_NAME_MAP={10001:"CONTAINER_NOT_FOUND",10002:"CONNECT_SOCKET_ERROR",10003:"START_SESSION_ERROR",10004:"STOP_SESSION_ERROR",10005:"INIT_ERROR",10006:"SOCKET_QUIT",10007:"SOCKET_DISCONNECT",20001:"VIDEO_FRAME_EXTRACT_ERROR",20002:"INIT_WORKER_ERROR",20003:"PROCESS_VIDEO_STREAM_ERROR",20004:"FACE_PROCESSING_ERROR",20005:"RENDER_BODY_ERROR",20006:"RENDER_FACE_ERROR",20007:"WebGL_RENDER_ERROR",20008:"RENDER_DATA_MISSING",20009:"RENDER_FACE_DATA_MISSING",20010:"EVENT_WITHOUT_SPEECH_ID",20011:"EVENT_TRIGGERED",30001:"BACKGROUND_IMAGE_LOAD_ERROR",30002:"FACE_BIN_LOAD_ERROR",30003:"INVALID_BODY_NAME",30004:"VIDEO_DOWNLOAD_ERROR",30005:"BODY_DATA_EXPIRED",30006:"EVENT_SPEAK_START_EXPIRED",30007:"EVENT_VOICE_START_EXPIRED",40001:"AUDIO_DECODE_ERROR",40002:"FACE_DECODE_ERROR",40003:"VIDEO_DECODE_ERROR",40004:"EVENT_DECODE_ERROR",40005:"INVALID_DATA_STRUCTURE",40006:"TTSA_ERROR",40007:"AUDIO_DATA_EXPIRED",50001:"NETWORK_DOWN",50002:"NETWORK_UP",50003:"NETWORK_RETRY",50004:"NETWORK_BREAK",60001:"WEBGL_CONTEXT_LOST",60002:"WEBGL_CONTEXT_RESTORED",60003:"WEBGL_CONTEXT_RESTORE_TIMEOUT",60004:"WEBGL_CONTEXT_RECOVERED",60005:"WEBGL_CONTEXT_RECOVERY_FAILED",60006:"WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",60007:"WEBGL_RESOLUTION_RESTORED",60008:"WEBGL_CONTEXT_MANUAL_RESTARTED"};var AvatarStatus,RenderState,InitModel,EFrameDataType;!function(t){t[t.online=0]="online",t[t.offline=1]="offline",t[t.network_on=2]="network_on",t[t.network_off=3]="network_off",t[t.close=4]="close",t[t.visible=5]="visible",t[t.invisible=6]="invisible",t[t.stopped=7]="stopped"}(AvatarStatus||(AvatarStatus={})),function(t){t.init="init",t.rendering="rendering",t.pausing="pausing",t.paused="paused",t.resumed="resumed",t.stopped="stopped"}(RenderState||(RenderState={})),function(t){t.normal="normal",t.invisible="invisible"}(InitModel||(InitModel={})),function(t){t.AUDIO="tts_audio",t.BODY="body_data",t.FACE="face_data",t.EVENT="event_data",t.AA_FRAME="aa_frame",t.SYNC_FRAME="sync_frame"}(EFrameDataType||(EFrameDataType={}));const FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk";class DataCacheQueue{constructor(){this.TAG="[DataCacheQueue]",this._bodyQueue=new Map,this._facialQueue=[],this._realFacialQueue=[],this.audioQueue=[],this.eventQueue=[],this.videoIdList=[],this._currentPlayState="idle",this._currentTtsaState=null,window.__dev_event_queue__=this.eventQueue}set currentPlayState(t){this._currentPlayState=t}get currentPlayState(){return this._currentPlayState}set currentTtsaState(t){this._currentTtsaState=t}get currentTtsaState(){return this._currentTtsaState}get bodyQueue(){return Array.from(this._bodyQueue.values())}_updateBodyImageBitmap(t){const e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(const[e,n]of this._bodyQueue.entries())n.body_id<t.body_id&&n.frameIndex>=t.frameIndex&&(n.frame.close(),this._bodyQueue.delete(e));this._bodyQueue.set(t.frameIndex,t)}clearOldFrames(t){for(const[e,n]of this._bodyQueue.entries())e>=t&&(n.frame.close(),this._bodyQueue.delete(e))}clearOldFaceData(t){this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),this._realFacialQueue=this._realFacialQueue.filter(e=>e.frameIndex>=t)}setVideoIdList(t){this.videoIdList.includes(t)||this.videoIdList.push(t)}getVideoIdList(){return this.videoIdList}_getBodyImageBitmap(t){const e=this._bodyQueue.get(t);for(const[e,n]of this._bodyQueue.entries())e<t&&(n.frame.close(),this._bodyQueue.delete(e));if(e)return e}getBodyVideoNameListLength(){const t=[];return this.bodyQueue.forEach(e=>{t.includes(e.name)||t.push(e.name)}),t.length}_getFaceImageBitmap(t,e){let n=null;for(let i=this._facialQueue.length-1;i>=0;i--){const r=this._facialQueue[i];if(r.frameIndex===t&&r.body_id===e){n=r;break}}return this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),n}_updateFacial(t){this._facialQueue.push(...t)}get facialQueue(){return this._facialQueue}_getRealFaceImageBitmap(t,e){let n=null;for(let i=this._realFacialQueue.length-1;i>=0;i--){const r=this._realFacialQueue[i];if((null==r?void 0:r.frameIndex)===t&&(null==r?void 0:r.body_id)===e){n=r;break}}return this._realFacialQueue=this._realFacialQueue.filter(e=>(null==e?void 0:e.frameIndex)>=t),n}_updateRealFacial(t){this._realFacialQueue.push(...t)}get realFacialQueue(){return this._realFacialQueue}clearAllFaceData(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")}_updateAudio(t){this.audioQueue.push(...t)}_clearAudio(t){this.audioQueue=-1!==t?this.audioQueue.filter(e=>e.sid!==t):[]}_getAudio(t){const e=this.audioQueue.findIndex(e=>e.sf===t);if(-1===e)return;const[n]=this.audioQueue.splice(e,1);return n}_getAudioInterval(t,e){const n=this.audioQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0===n.length)return;const i=n[n.length-1],r=this.audioQueue.findIndex(t=>t.id===i.id);return this.audioQueue.splice(r,1),i}_updateUiEvent(t){this.eventQueue.push(...t)}clearOldEvent(t){this.eventQueue=this.eventQueue.filter(e=>e.sf>=t)}clearSubtitleOn(t){this.eventQueue=this.eventQueue.map(e=>{var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(e=>e.speech_id>t||"subtitle_on"!==e.type)})})}_clearEvent(){this.eventQueue=[]}_getEvent(t){const e=this.eventQueue.filter(e=>e.sf===t);if(0!==e.length)return this.eventQueue=this.eventQueue.filter(e=>e.sf!==t),this._mergeEventsBySf(e)}_getEventInterval(t,e){const n=this.eventQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0!==n.length)return this.eventQueue=this.eventQueue.filter(n=>!(n.sf>=t&&n.sf<=e)),this._mergeEventsBySf(n)}_mergeEventsBySf(t){const e={};for(const n of t){const t=n.sf;e[t]||(e[t]=_extends({},n,{e:[]})),e[t].e.push(...n.e)}const n=Object.values(e);if(0===n.length)return null;if(n.length>1){const t=[];return n.forEach(e=>t.push(...e.e)),_extends({},n[0],{mergeFrameFlag:1,e:t})}return n[0]}checkValidData(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,i;if(0===this.audioQueue.length||0===t.length)return;if((null==(n=this.audioQueue[this.audioQueue.length-1])?void 0:n.ef)<t[0].sf||t[0].sf<(null==(i=this.audioQueue[0])?void 0:i.sf)){const e=this.audioQueue.findIndex(e=>e.sf>=t[0].sf);-1!==e&&(this.audioQueue.length=e)}}}destroy(){this._bodyQueue.forEach(t=>{t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]}}class GLDevice{constructor(t){this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;const e=()=>{const t=this.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");this.gl=t,this._lost_context_sim=this.gl.getExtension("WEBGL_lose_context"),this.shaderStage={vertex:this.gl.VERTEX_SHADER,fragment:this.gl.FRAGMENT_SHADER},this._ElementTypeMap_JS2GL={Uint8Array:this.gl.UNSIGNED_BYTE,Uint8ClampedArray:this.gl.UNSIGNED_BYTE,Int8Array:this.gl.BYTE,Uint16Array:this.gl.UNSIGNED_SHORT,Int16Array:this.gl.SHORT,Uint32Array:this.gl.UNSIGNED_INT,Int32Array:this.gl.INT,Float16Array:this.gl.HALF_FLOAT,Float32Array:this.gl.FLOAT};const e=[[this.gl.UNSIGNED_BYTE,[[this.gl.RED,this.gl.R8],[this.gl.RED_INTEGER,this.gl.R8UI],[this.gl.RG,this.gl.RG8],[this.gl.RG_INTEGER,this.gl.RG8UI],[this.gl.RGB,this.gl.RGB8],[this.gl.RGB_INTEGER,this.gl.RGB8UI],[this.gl.RGBA,this.gl.RGBA8],[this.gl.RGBA_INTEGER,this.gl.RGBA8UI]]],[this.gl.BYTE,[[this.gl.RED,this.gl.R8_SNORM],[this.gl.RED_INTEGER,this.gl.R8I],[this.gl.RG,this.gl.RG8_SNORM],[this.gl.RG_INTEGER,this.gl.RG8I],[this.gl.RGB,this.gl.RGB8_SNORM],[this.gl.RGB_INTEGER,this.gl.RGB8I],[this.gl.RGBA,this.gl.RGBA8_SNORM],[this.gl.RGBA_INTEGER,this.gl.RGBA8I]]],[this.gl.UNSIGNED_SHORT,[[this.gl.RED_INTEGER,this.gl.R16UI],[this.gl.RG_INTEGER,this.gl.RG16UI],[this.gl.RGB_INTEGER,this.gl.RGB16UI],[this.gl.RGBA_INTEGER,this.gl.RGBA16UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT16]]],[this.gl.SHORT,[[this.gl.RED_INTEGER,this.gl.R16I],[this.gl.RG_INTEGER,this.gl.RG16I],[this.gl.RGB_INTEGER,this.gl.RGB16I],[this.gl.RGBA_INTEGER,this.gl.RGBA16I]]],[this.gl.UNSIGNED_INT,[[this.gl.RED_INTEGER,this.gl.R32UI],[this.gl.RG_INTEGER,this.gl.RG32UI],[this.gl.RGB_INTEGER,this.gl.RGB32UI],[this.gl.RGBA_INTEGER,this.gl.RGBA32UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT24]]],[this.gl.INT,[[this.gl.RED_INTEGER,this.gl.R32I],[this.gl.RG_INTEGER,this.gl.RG32I],[this.gl.RGB_INTEGER,this.gl.RGB32I],[this.gl.RGBA_INTEGER,this.gl.RGBA32I]]],[this.gl.HALF_FLOAT,[[this.gl.RED,this.gl.R16F],[this.gl.RG,this.gl.RG16F],[this.gl.RGB,this.gl.RGB16F],[this.gl.RGBA,this.gl.RGBA16F]]],[this.gl.FLOAT,[[this.gl.RED,this.gl.R32F],[this.gl.RG,this.gl.RG32F],[this.gl.RGB,this.gl.RGB32F],[this.gl.RGBA,this.gl.RGBA32F],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT32F]]],[this.gl.UNSIGNED_SHORT_5_6_5,[[this.gl.RGB,this.gl.RGB565]]],[this.gl.UNSIGNED_SHORT_4_4_4_4,[[this.gl.RGBA,this.gl.RGBA4]]],[this.gl.UNSIGNED_SHORT_5_5_5_1,[[this.gl.RGBA,this.gl.RGB5_A1]]],[this.gl.UNSIGNED_INT_2_10_10_10_REV,[[this.gl.RGBA,this.gl.RGB10_A2]]],[this.gl.UNSIGNED_INT_10F_11F_11F_REV,[[this.gl.RGB,this.gl.R11F_G11F_B10F]]],[this.gl.UNSIGNED_INT_5_9_9_9_REV,[[this.gl.RGB,this.gl.RGB9_E5]]],[this.gl.UNSIGNED_INT_24_8,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH24_STENCIL8]]],[this.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH32F_STENCIL8]]]];this._FormatTypeMap_Ext2Int=new Map;for(const[t,n]of e){const e=new Map;for(const[t,i]of n)e.set(t,i);this._FormatTypeMap_Ext2Int.set(t,e)}const n={GL_RED:this.gl.RED,GL_RED_INTEGER:this.gl.RED_INTEGER,GL_RG:this.gl.RG,GL_RG_INTEGER:this.gl.RG_INTEGER,GL_RGB:this.gl.RGB,GL_RGB_INTEGER:this.gl.RGB_INTEGER,GL_RGBA:this.gl.RGBA,GL_RGBA_INTEGER:this.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:this.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:this.gl.DEPTH_STENCIL};this._FormatTypeMap_Ext2Str=new Map;for(const[t,e]of Object.entries(n))this._FormatTypeMap_Ext2Str.set(e,t)};this.frameID=null,this.cbRender=()=>{},this._onContextLost=t=>{t.preventDefault(),this.stop()},this._onContextRestored=e,this._onContextCreationError=t=>{console.error(t.statusMessage||"WebGL context creation error: unknown error.")},this.canvas.addEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.addEventListener("webglcontextcreationerror",this._onContextCreationError,!1),e()}compileShaderProgram(t){let e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(const[n,i]of Object.entries(t)){const t=this.gl.createShader(this.shaderStage[n]);if(!t)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(t,i),this.gl.compileShader(t),!this.gl.getShaderParameter(t,this.gl.COMPILE_STATUS)){const e=this.gl.getShaderInfoLog(t);throw this.gl.deleteShader(t),new Error("WebGL shader compile failed:"+e)}this.gl.attachShader(e,t)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const t=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+t)}return e}getShaderProgramUniformLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getUniformLocation(t,i);return n}getShaderProgramUniformBlockLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getUniformBlockIndex(t,i);return n}getShaderProgramAttribLocation(t,e){let n={};for(const i of e)n[i]=this.gl.getAttribLocation(t,i);return n}getGLArrayElementType(t){const e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null}getGLTexInternalFormat(t,e){const n=this._FormatTypeMap_Ext2Int.get(e);if(n){const e=n.get(t);if(e)return e}return null}texImage2D(t,e,n,i,r,s){var a;const o=this.getGLArrayElementType(s);if(!o)throw new Error(`Unsupported data format: ${s[Symbol.toStringTag]}`);const l=this.getGLTexInternalFormat(r,o);if(!l)throw new Error(`No available internal format for ${s[Symbol.toStringTag]} and ${null!=(a=this._FormatTypeMap_Ext2Str.get(r))?a:"unknown"}.`);this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,i,0,r,o,s)}texImage3D(t,e,n,i,r,s,a){var o;const l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);const h=this.getGLTexInternalFormat(s,l);if(!h)throw new Error(`No available internal format for ${a[Symbol.toStringTag]} and ${null!=(o=this._FormatTypeMap_Ext2Str.get(s))?o:"unknown"}.`);this.gl.HALF_FLOAT==l&&(a=new Uint16Array(a.buffer)),this.gl.texImage3D(t,e,h,n,i,r,0,s,l,a)}run(t,e){if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;const t=(n,i)=>{this.running&&(this.syncMediaTime=i.mediaTime,this.cbRender(this),this.frameID=e.requestVideoFrameCallback(t))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(t)}else{const t=()=>{this.running&&(this.cbRender(this),this.frameID=requestAnimationFrame(t))};t()}}refresh(){this.cbRender(this)}getSyncMediaTime(){return this.syncMediaTime}stop(){null!==this.frameID&&(this.syncMedia?(this.syncMedia.cancelVideoFrameCallback(this.frameID),this.syncMedia=null,this.syncMediaTime=null):cancelAnimationFrame(this.frameID),this.frameID=null),this.running=!1}simulateContextFault(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())}captureFrame(){const t=this.canvas.width,e=this.canvas.height,n=new Uint8ClampedArray(t*e*4);return this.gl.readPixels(0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),{width:t,height:e,data:n}}destroy(){if(this._isDestroyed||!this.gl)return;const t=this.gl;try{const e=t.getExtension("WEBGL_lose_context");if(e&&e.loseContext(),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),t.flush(),this.canvas){const t=this.canvas.getContext("2d");t&&t.clearRect(0,0,this.canvas.width,this.canvas.height)}this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.removeEventListener("webglcontextcreationerror",this._onContextCreationError,!1)),this.gl=null,this._isDestroyed=!0}catch(t){this._isDestroyed=!0}}}function length(t){return Math.sqrt(t.reduce((t,e)=>t+e*e,0))}function normalize(t){let e=length(t);return t.map(t=>t/e)}function mvmul(t,e){const n=t.length,i=e.length;let r=Array(n);for(let s=0;s<n;s++){r[s]=0;for(let n=0;n<i;n++)r[s]+=t[s][n]*e[n]}return r}function mmul(t,e){const n=t.length,i=e.length,r=e[0].length;let s=Array(n);for(let a=0;a<n;a++){let n=Array(r);for(let s=0;s<r;s++){n[s]=0;for(let r=0;r<i;r++)n[s]+=t[a][r]*e[r][s]}s[a]=n}return s}function transpose(t){const e=t.length,n=t[0].length;let i=Array(n);for(let r=0;r<n;r++){let n=Array(e);for(let i=0;i<e;i++)n[i]=t[i][r];i[r]=n}return i}function identity(t){let e=Array(t);for(let n=0;n<t;n++){let i=Array(t);for(let e=0;e<t;e++)i[e]=n==e?1:0;e[n]=i}return e}function det3(t){let e=0;return e+=t[0][0]*t[1][1]*t[2][2],e+=t[0][1]*t[1][2]*t[2][0],e+=t[0][2]*t[1][0]*t[2][1],e-=t[0][2]*t[1][1]*t[2][0],e-=t[0][1]*t[1][0]*t[2][2],e-=t[0][0]*t[1][2]*t[2][1],e}function inv3(t){const e=1/det3(t);return[[(t[1][1]*t[2][2]-t[2][1]*t[1][2])*e,(t[0][2]*t[2][1]-t[0][1]*t[2][2])*e,(t[0][1]*t[1][2]-t[0][2]*t[1][1])*e],[(t[1][2]*t[2][0]-t[1][0]*t[2][2])*e,(t[0][0]*t[2][2]-t[0][2]*t[2][0])*e,(t[1][0]*t[0][2]-t[0][0]*t[1][2])*e],[(t[1][0]*t[2][1]-t[2][0]*t[1][1])*e,(t[2][0]*t[0][1]-t[0][0]*t[2][1])*e,(t[0][0]*t[1][1]-t[1][0]*t[0][1])*e]]}function inv4(t){let e=[[...t[0]],[...t[1]],[...t[2]],[...t[3]]],n=[0,0,0,0],i=[0,0,0,0],r=0;for(let t=0;t<4;t++){let s=0;for(let r=t;r<4;r++)for(let a=t;a<4;a++)Math.abs(e[r][a])>s&&(s=Math.abs(e[r][a]),n[t]=r,i[t]=a);if(s<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[t]!=t)for(let i=0;i<4;i++)r=e[t][i],e[t][i]=e[n[t]][i],e[n[t]][i]=r;if(i[t]!=t)for(let n=0;n<4;n++)r=e[n][t],e[n][t]=e[n][i[t]],e[n][i[t]]=r;e[t][t]=1/e[t][t];for(let n=0;n<4;n++)n!=t&&(e[t][n]*=e[t][t]);for(let n=0;n<4;n++)if(n!=t)for(let i=0;i<4;i++)i!=t&&(e[n][i]-=e[n][t]*e[t][i]);for(let n=0;n<4;n++)n!=t&&(e[n][t]*=-e[t][t])}for(let t=3;t>=0;t--){if(i[t]!=t)for(let n=0;n<4;n++)r=e[t][n],e[t][n]=e[i[t]][n],e[i[t]][n]=r;if(n[t]!=t)for(let i=0;i<4;i++)r=e[i][t],e[i][t]=e[i][n[t]],e[i][n[t]]=r}return e}function quaternion_conj(t){return[t[0],-t[1],-t[2],-t[3]]}function quaternion_mul(t,e){return[t[0]*e[0]-t[1]*e[1]-t[2]*e[2]-t[3]*e[3],t[0]*e[1]+t[1]*e[0]+t[2]*e[3]-t[3]*e[2],t[0]*e[2]-t[1]*e[3]+t[2]*e[0]+t[3]*e[1],t[0]*e[3]+t[1]*e[2]-t[2]*e[1]+t[3]*e[0]]}function quaternion_to_mat(t){const[e,n,i,r]=t;return[[e*e+n*n-i*i-r*r,2*(n*i-r*e),2*(n*r+i*e)],[2*(n*i+r*e),e*e-n*n+i*i-r*r,2*(i*r-n*e)],[2*(n*r-i*e),2*(i*r+n*e),e*e-n*n-i*i+r*r]]}function GivensTransform(t,e,n,i){const r=Math.sin(i),s=Math.cos(i),a=t[0].length;for(let i=0;i<a;i++){const a=r*t[e][i]+s*t[n][i];t[e][i]=s*t[e][i]-r*t[n][i],t[n][i]=a}}function Euler_to_mat(t,e="xyz"){let n=identity(3);switch(e){case"xyz":case"zxy":GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]),GivensTransform(n,0,1,t[2]);break;case"yzx":GivensTransform(n,0,1,t[2]),GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]);break;case"xzy":GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]);break;case"yxz":GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]);break;case"zyx":GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]);break;default:throw Error("Unrecognizable rotation order.")}return n}function make_homogeneous(t,e){return[[t[0][0],t[0][1],t[0][2],e[0]],[t[1][0],t[1][1],t[1][2],e[1]],[t[2][0],t[2][1],t[2][2],e[2]],[0,0,0,1]]}function flatten(t){const e=t.length,n=t[0].length;let i=Array(e*n);for(let r=0;r<e;r++)for(let e=0;e<n;e++)i[r*n+e]=t[r][e];return i}const performanceConstant={load_resource:"load_resource",ttsa_connect:"ttsa_connect",ttsa_ready:"ttsa_ready",first_avatar_render:"first_avatar_render",first_webgl_render:"first_webgl_render",ttsa_body_res:"ttsa_body_res",start_action_res:"start_action_res",start_action_render:"start_action_render",load_video:"load_video",decode_video:"decode_video",voice_response_play:"voice_response_play",first_decode_video:"first_decode_video",first_render:"first_render"};class PerformanceTracker{constructor(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=()=>{},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}getFirstInfo(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}}markStart(t,e){this.marks.set(t,{state:e,time:performance.now()})}markEnd(t,e){const n=this.marks.get(t);if(!n)return;if(e&&"string"==typeof e&&e!==(null==n?void 0:n.state))return;const i=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:i}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,i),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=i),t===performanceConstant.first_render&&(this.firstRenderTime=i),i}getAllMetrics(){return Object.fromEntries(this.measures.entries())}getVideoMetrics(){const t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(([t])=>[performanceConstant.decode_video,performanceConstant.load_video].includes(t)))}setReportFunc(t){this.reportFunc=t}reportMetric(){var t;const e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){const t=Object.fromEntries(Object.entries(e).filter(([t])=>![performanceConstant.load_video,performanceConstant.decode_video].includes(t)));var n;Object.keys(t).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(t));for(const e in t)e!==performanceConstant.decode_video&&e!==performanceConstant.load_video&&this.measures.delete(e)}}setOnStateRenderChange(t){this.onStateRenderChange=t}}window.performanceTracker=new PerformanceTracker;const shadow_sample_count=4,shader_common="\n float randFloat(vec2 p) {\n // generate a uniformely distributed float in [0, 1).\n return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);\n }\n bool isMaskedBitSet(uint value, uint mask){\n return bool(value & mask);\n }\n vec4 RGB2sRGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.0031308)color[i] *= 12.92;\n else color[i] = 1.055 * pow(color[i], 1.0 / 2.4) - 0.055;\n }\n return color;\n }\n vec4 sRGB2RGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.04045)color[i] /= 12.92;\n else color[i] = pow((color[i] + 0.055) / 1.055, 2.4);\n }\n return color;\n }\n",vs_background="#version 300 es\n layout(location = 0) in vec2 pos;\n layout(location = 1) in vec2 texCoord;\n out vec2 v_texCoord;\n void main() {\n gl_Position = vec4(pos, 0, 1);\n v_texCoord = texCoord;\n }\n",fs_background=`#version 300 es\n precision mediump float;\n uniform sampler2D u_image_bg, u_image_char_body, u_image_mesh_color, u_image_mesh_alpha;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint flags; // 1 - has background, 2 - with multisample coverage, 4 - shadow fx\n\n layout (std140) uniform ub_shadow_fx_info {\n mat3 transform[2];\n vec4 color;\n vec4 sampleParams; // sample radius, unused, unused, unused \n } ub_shadow_fx;\n\n in vec2 v_texCoord;\n out vec4 fragColor;\n\n ${shader_common}\n\n vec2 tex2scr(vec2 coord){\n return vec2(coord.x * 2.0 - 1.0, 1.0 - coord.y * 2.0);\n }\n vec2 scr2tex(vec2 coord){\n return vec2(coord.x * 0.5 + 0.5, 0.5 - coord.y * 0.5);\n }\n vec2 randomUnitVec2D(float seed) {\n float theta = seed * 2.0 * 3.14159265359;\n return vec2(cos(theta), sin(theta));\n }\n float sampleOpacity(vec2 texCoord, mat2 u_transform_2d){\n float result = texture(u_image_mesh_color, vec2(texCoord.x, 1.0 - texCoord.y)).a;\n texCoord = texCoord * u_transform_2d[0] + u_transform_2d[1];\n texCoord.x = texCoord.x * 0.5 + 0.5;\n result += (1.0 - result) * texture(u_image_char_body, texCoord).r;\n return result;\n }\n float PI = 3.14159265359;\n\n void main() {\n float randSeed = randFloat(vec2(gl_FragCoord.xy));\n\n vec2 texcoord_transformed = v_texCoord * u_transform_2d[0] + u_transform_2d[1];\n texcoord_transformed = clamp(texcoord_transformed, 0.0, 1.0);\n vec2 texCoord_char_color = vec2(texcoord_transformed.x * 0.5, texcoord_transformed.y);\n vec2 texCoord_char_alpha = vec2(texcoord_transformed.x * 0.5 + 0.5, texcoord_transformed.y);\n vec2 texCoord_mesh = vec2(v_texCoord.x, 1.0 - v_texCoord.y);\n\n vec4 char_color = texture(u_image_char_body, texCoord_char_color);\n vec4 char_alpha = texture(u_image_char_body, texCoord_char_alpha);\n char_color = sRGB2RGB(char_color);\n char_alpha = sRGB2RGB(char_alpha);\n float char_alpha_back = char_alpha.r;\n float char_alpha_front = max(char_alpha.r - char_alpha.b, 0.0);\n\n vec4 mesh_color_srgb = texture(u_image_mesh_color, texCoord_mesh);\n float mesh_alpha = mesh_color_srgb.a;\n if(isMaskedBitSet(flags, 2u)){\n float mesh_coverage = texture(u_image_mesh_alpha, texCoord_mesh).r;\n mesh_color_srgb.rgb /= max(mesh_coverage, 9e-5); // epsilon for float16\n }\n\n vec3 final_rgb = char_alpha_back * char_color.rgb;\n float final_alpha = char_alpha_back;\n\n if(isMaskedBitSet(flags, 4u)){ // fake shadow\n vec3 pos_shadow = vec3(tex2scr(v_texCoord), 1.0);\n pos_shadow = ub_shadow_fx.transform[1] * pos_shadow;\n if(pos_shadow.z > 0.0 && pos_shadow.y > 0.0){\n // simple and noisy blur\n pos_shadow /= pos_shadow.z;\n float radius = ub_shadow_fx.sampleParams.x * pos_shadow.y;\n vec2 randVec = randomUnitVec2D(randSeed);\n mat2 randMat = mat2(randVec.x, randVec.y, -randVec.y, randVec.x);\n float shadow_opacity = 0.0;\n\n int sampleCount = radius > 0.0 ? ${shadow_sample_count} : 1;\n for(int i=0;i<sampleCount;i++){\n float sampleDist = (float(i) + 0.5) / float(sampleCount);\n float angle = 26.0 * PI * sampleDist; // prime number * 2pi\n sampleDist = radius * sqrt(sampleDist);\n vec2 sampleVec = sampleDist * randMat * vec2(cos(angle), sin(angle));\n\n vec3 pos_shadow_proj = ub_shadow_fx.transform[0] * (pos_shadow + vec3(sampleVec, 0.0));\n vec2 texCoord_shadow = clamp(pos_shadow_proj.xy / pos_shadow_proj.z, -1.0, 1.0);\n texCoord_shadow = scr2tex(texCoord_shadow);\n shadow_opacity += sampleOpacity(texCoord_shadow, u_transform_2d);\n }\n shadow_opacity /= float(sampleCount);\n float shadow_alpha = shadow_opacity * ub_shadow_fx.color.a;\n\n final_rgb = final_rgb + (1.0 - final_alpha) * shadow_alpha * ub_shadow_fx.color.rgb;\n final_alpha = final_alpha + (1.0 - final_alpha) * shadow_alpha;\n }\n }\n final_rgb = mesh_alpha * mesh_color_srgb.rgb + (1.0 - mesh_alpha) * final_rgb;\n final_alpha = mesh_alpha + (1.0 - mesh_alpha) * final_alpha;\n final_rgb = char_alpha_front * char_color.rgb + (1.0 - char_alpha_front) * final_rgb;\n final_alpha = char_alpha_front + (1.0 - char_alpha_front) * final_alpha;\n\n if(isMaskedBitSet(flags, 1u)){\n vec4 bg_color = sRGB2RGB(texture(u_image_bg, v_texCoord));\n final_rgb += bg_color.rgb * (1.0 - final_alpha);\n final_alpha = 1.0;\n }\n final_rgb = RGB2sRGB(vec4(final_rgb, 1.0)).rgb;\n fragColor = vec4(final_rgb, final_alpha);\n }\n`,uniform_var_list_bg=["u_image_bg","u_image_char_body","u_image_mesh_color","u_image_mesh_alpha","u_transform_2d","flags"],uniform_block_list_bg=["ub_shadow_fx_info"];function generateMeshPipelineShader(t){return{vertex:`#version 300 es\n precision highp float;\n\n layout (std140) uniform ub_rig_info {\n mat4 joint_matrices[${t.max_bones}];\n vec4 bs_weights[${t.max_bs_count/4}];\n } ub_rig;\n \n uniform sampler2D u_image_bs; // used for blendshape deformation\n uniform mat4 u_proj_mat;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint u_bs_count; // number of bs weight vectors (divided by 4)\n uniform uint flags; // 1 - has opacity\n\n layout(location = 0) in vec3 pos;\n layout(location = 1) in vec2 tex_coord;\n layout(location = 2) in float opacity;\n layout(location = 3) in uvec4 bone_index_0_4;\n layout(location = 4) in uvec4 bone_index_4_8;\n layout(location = 5) in vec4 bone_weight_0_4;\n layout(location = 6) in vec4 bone_weight_4_8;\n\n out vec4 v_pos;\n out vec2 v_tex_coord;\n out float v_opacity;\n\n ${shader_common}\n\n vec4 lbs_transform(vec3 pos){\n float total_weight = 0.0;\n vec4 aug_pos = vec4(pos, 1.0);\n vec4 result = vec4(0.0);\n uint index;\n for(index = 0u;index < 8u;index++){\n uint joint_index;\n float joint_weight;\n if(index < 4u) {\n joint_index = bone_index_0_4[index];\n joint_weight = bone_weight_0_4[index];\n }\n else {\n joint_index = bone_index_4_8[index - 4u];\n joint_weight = bone_weight_4_8[index - 4u];\n }\n if(255u == joint_index)break;\n else result += joint_weight * (ub_rig.joint_matrices[joint_index] * aug_pos);\n }\n result /= result.w;\n return vec4(result.xyz, 1.0);\n }\n\n vec3 bs_accumulate(uint vertex_id){\n uint texWidth = uint(textureSize(u_image_bs, 0).x);\n vec3 pos = vec3(0.0);\n\n uint vertex_offset = vertex_id * u_bs_count * 3u;\n for(uint i = 0u; i < u_bs_count; i++){\n vec4 bs_weight_vec = ub_rig.bs_weights[i];\n for (uint j = 0u; j < 3u; j++){\n uint texel_offset = j * u_bs_count + vertex_offset + i;\n uint texel_x = texel_offset % texWidth;\n uint texel_y = texel_offset / texWidth;\n vec4 data = texelFetch(u_image_bs, ivec2(texel_x, texel_y), 0);\n pos[j] += dot(data, bs_weight_vec);\n }\n }\n return pos;\n }\n \n void main() {\n if(isMaskedBitSet(flags, 1u))v_opacity = opacity; else v_opacity = 1.0;\n \n vec3 bs_pos = vec3(0.0);\n if(u_bs_count > 0u)bs_pos = bs_accumulate(uint(gl_VertexID)) * v_opacity;\n v_pos = u_proj_mat * lbs_transform(pos + bs_pos);\n v_pos /= v_pos.w;\n v_pos.xy = u_transform_2d[0] * v_pos.xy + u_transform_2d[1];\n v_tex_coord = tex_coord;\n gl_Position = v_pos;\n }\n`,fragment_mask:"#version 300 es\n precision highp float;\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing)fragColor = vec4(1.0);\n else fragColor = vec4(0.0);\n }\n",fragment:`#version 300 es\n precision highp int;\n precision highp float;\n precision highp sampler2DArray;\n precision highp sampler3D;\n layout (std140) uniform ub_pca_info {\n vec4 weights[${t.max_pca_component_count/4}];\n } ub_pca;\n uniform sampler2DArray u_image_pca;\n uniform sampler3D u_image_lut;\n uniform uint flags; // 2 - has LUT, 4 - unsigned PCA component\n uniform vec3 u_gamma;\n uniform vec3 u_color_balance; // r/c, g/m, b/y\n\n ${shader_common}\n \n vec4 pca_accumulate(vec2 tex_coord, bool _unsigned){\n ivec3 texSize = textureSize(u_image_pca, 0);\n vec4 result = vec4(0.0);\n for(int i = 0; i < texSize.z; i++){\n int vec_index = i / 4;\n int elem_index = i % 4;\n vec4 pca_sample = texture(u_image_pca, vec3(tex_coord, float(i)));\n if(_unsigned)pca_sample = 2.0 * pca_sample - 1.0;\n result += ub_pca.weights[vec_index][elem_index] * pca_sample;\n }\n return result;\n }\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing){\n vec2 fragTexCoord = v_tex_coord;\n vec4 sample_color = pca_accumulate(v_tex_coord, isMaskedBitSet(flags, 4u));\n if(isMaskedBitSet(flags, 2u))sample_color = texture(u_image_lut, sample_color.rgb);\n // Apply gamma correction\n vec3 final_color = pow(sample_color.rgb, u_gamma);\n\n // Apply color balance\n // Convert -100 to 100 range to -0.5 to 0.5 range\n vec3 balance_adjusted = u_color_balance / 200.0; // Map -100..100 to -0.5..0.5\n\n // Red/Cyan adjustment\n final_color.r += balance_adjusted.x;\n final_color.g -= balance_adjusted.x; // Cyan is opposite of Red\n\n // Green/Magenta adjustment\n final_color.g += balance_adjusted.y;\n final_color.b -= balance_adjusted.y; // Magenta is opposite of Green\n\n // Blue/Yellow adjustment\n final_color.b += balance_adjusted.z;\n final_color.r -= balance_adjusted.z; // Yellow is opposite of Blue\n\n // Clamp values to [0, 1]\n final_color = clamp(final_color, 0.0, 1.0);\n fragColor = sRGB2RGB(vec4(final_color.bgr, v_opacity));\n }\n else fragColor = vec4(0.0);\n }\n`}}const uniform_var_list_mesh=["u_proj_mat","u_transform_2d","u_image","u_image_bs","u_image_pca","u_image_lut","u_bs_count","flags","u_gamma","u_color_balance"],uniform_block_list_mesh=["ub_pca_info","ub_rig_info"];class GLPipeline{assembleBackgroundPipeline(){this._ub_shadow_fx_data=new Float32Array(32);const t=this.device.compileShaderProgram({vertex:vs_background,fragment:fs_background}),e=this.device.getShaderProgramUniformLocation(t,uniform_var_list_bg),n=this.device.getShaderProgramUniformBlockLocation(t,uniform_block_list_bg);this.backgroundPipelineInfo={program:t,progUniforms:e,progUniformBlocks:n},this.device.gl.uniformBlockBinding(this.backgroundPipelineInfo.program,this.backgroundPipelineInfo.progUniformBlocks.ub_shadow_fx_info,0),this.backgroundVAO=this.device.gl.createVertexArray(),this.device.gl.bindVertexArray(this.backgroundVAO);const i=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,2,this.device.gl.FLOAT,!1,16,0),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.gl.FLOAT,!1,16,8),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null);let r={};r.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW),this.backgroundBuffers=r,this.device.gl.bindVertexArray(null);let s={};if(s.u_image_bg=this.device.gl.createTexture(),!s.u_image_bg)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_bg),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),s.u_image_char_body=this.device.gl.createTexture(),!s.u_image_char_body)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_char_body),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.backgroundTextures=s}assembleMeshPipelines(t){if(t.char){const e=t.char;let n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)};for(let t=0;t<e.mesh.length;t++){const i=e.mesh[t].textureModels;let r=0;for(let t of i){let e=t.data.size[0]+3;e-=e%4,r=Math.max(r,e)}n.max_pca_component_count=Math.max(n.max_pca_component_count,r);let s=e.mesh[t].blendshapes.size[2]+3;s-=s%4,n.max_bs_count=Math.max(n.max_bs_count,s)}this.meshStatistics=n,this._ub_rig_info_data=new Float32Array(16*this.meshStatistics.max_bones+this.meshStatistics.max_bs_count),this._ub_pca_info_data=new Float32Array(this.meshStatistics.max_pca_component_count);const i=generateMeshPipelineShader(this.meshStatistics);let r=this.device.compileShaderProgram({vertex:i.vertex,fragment:i.fragment}),s=this.device.getShaderProgramUniformLocation(r,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(r,uniform_block_list_mesh);this.meshPipelineInfo={program:r,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_rig_info,0),this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_pca_info,1),r=this.device.compileShaderProgram({vertex:i.vertex,fragment:i.fragment_mask}),s=this.device.getShaderProgramUniformLocation(r,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(r,uniform_block_list_mesh),this.maskPipelineInfo={program:r,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(let t=0;t<e.mesh.length;t++){let i={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(i.VAO),null===this.device.getGLArrayElementType(e.mesh[t].blendshapes.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].blendshapes.data}`);if(i.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[t].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[t].UVCoord.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].UVCoord.data}`);if(i.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[t].UVCoord.data),!0,0,0),e.mesh[t].opacity){if(null===this.device.getGLArrayElementType(e.mesh[t].opacity.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].opacity.data}`);i.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[t].opacity.data),!0,0,0)}if(i.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointIndex,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(3),this.device.gl.vertexAttribIPointer(3,4,this.device.gl.UNSIGNED_BYTE,8,0),this.device.gl.enableVertexAttribArray(4),this.device.gl.vertexAttribIPointer(4,4,this.device.gl.UNSIGNED_BYTE,8,4),i.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,i.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointWeight,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(5),this.device.gl.vertexAttribPointer(5,4,this.device.gl.FLOAT,!1,32,0),this.device.gl.enableVertexAttribArray(6),this.device.gl.vertexAttribPointer(6,4,this.device.gl.FLOAT,!1,32,16),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null),null===this.device.getGLArrayElementType(e.mesh[t].triangles.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].triangles.data}`);if(i.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[t].triangles.data,this.device.gl.STATIC_DRAW),i.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(n.max_pca_component_count),this.device.gl.DYNAMIC_DRAW),i.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(16*n.max_bones+n.max_bs_count),this.device.gl.DYNAMIC_DRAW),this.device.gl.bindVertexArray(null),e.mesh[t].blendshapes.size[2]>0){let n=[Math.ceil(e.mesh[t].blendshapes.size[2]/4),e.mesh[t].blendshapes.size[0]*e.mesh[t].blendshapes.size[1]],r=Math.ceil(Math.sqrt(n[0]*n[1])),s=4*n[0],a=new Float32Array(r*r*4);for(let i=0;i<n[1];i++){for(let n=0;n<e.mesh[t].blendshapes.size[2];n++)a[i*s+n]=e.mesh[t].blendshapes.data[i*e.mesh[t].blendshapes.size[2]+n];for(let n=e.mesh[t].blendshapes.size[2];n<s;n++)a[i*s+n]=0}if(i.textures.u_image_bs=this.device.gl.createTexture(),!i.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.texImage2D(this.device.gl.TEXTURE_2D,0,r,r,this.device.gl.RGBA,a),i.uniformUInts.u_bs_count=n[0]}else i.uniformUInts.u_bs_count=0;for(let n of e.mesh[t].textureModels){let t=this.device.gl.createTexture();if(!t)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,t),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR);let e=this.device.getGLArrayElementType(n.data.data),r={texture:t,unsigned:this.device.gl.UNSIGNED_BYTE===e||this.device.gl.UNSIGNED_SHORT===e||this.device.gl.UNSIGNED_INT===e},s=n.data.data;if("Float64Array"===n.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===e&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===e&&!this.compat_features.OES_texture_half_float_linear){const t=n.data.size[1]*n.data.size[2]*3,e=new Uint8Array(n.data.size[0]*t);let i=new Float32Array(n.data.size[0]);for(let r=0;r<n.data.size[0];r++){let s=1e-6;for(let e=0;e<t;e++)s=Math.max(s,Math.abs(n.data.data[r*t+e]));let a=1/s;for(let i=0;i<t;i++)e[r*t+i]=Math.round(255*(n.data.data[r*t+i]*a*.5+.5));i[r]=s}s=e,r.unsigned=!0,r.scalingFactor=i}n.scalingFactor&&(r.scalingFactor=n.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,n.data.size[1],n.data.size[2],n.data.size[0],this.device.gl.RGB,s),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),i.texturePCAModels.push(r)}this.meshInfos.push(i)}this.initSkeletonStatus=e.evalSkeleton()}if(this.FrameTexture_meshColor=this.device.gl.createTexture(),!this.FrameTexture_meshColor)throw Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),t.multisample){if(this.FrameTexture_meshAlpha=this.device.gl.createTexture(),!this.FrameTexture_meshAlpha)throw Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),this.FrameBuffer_meshColor=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.FrameBuffer_meshAlpha=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha,0);const e=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,e),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);const n=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,n),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);const i=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,i),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.R8,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.RENDERBUFFER,n),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,i),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,e)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;const t=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,t),this.device.gl.renderbufferStorage(this.device.gl.RENDERBUFFER,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,t)}if(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),null===t.LUT)this.LUTTexture=null;else{if(this.LUTTexture=this.device.gl.createTexture(),!this.LUTTexture)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR),this.compat_features.OES_texture_float_linear)this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,t.LUT.data);else{const e=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3);for(let n=0;n<e.length;n++)e[n]=Math.round(255*t.LUT.data[n]);this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,e)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null}getProjMat(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())}initFrame(){this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight),this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData&&(this.charData.multisample?(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT)):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT))),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT)}renderBackground(t){this.device.gl.disable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);let e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);let n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){const n=t.fx.shadow,i=this.getBillboardShadowGeometryInfo(n.refPos,n.light,"point"===n.lightType);e+=4;for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e]=i.Mat_World2ObjImage[e][t];for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e+12]=i.Mat_ShadowImage2World[e][t];for(let t=0;t<3;t++)this._ub_shadow_fx_data[24+t]=n.tint[t];this._ub_shadow_fx_data[27]=n.intensity,this._ub_shadow_fx_data[28]=n.blurRadius,this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW)}this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.uniformMatrix2fv(this.backgroundPipelineInfo.progUniforms.u_transform_2d,!1,n?new Float32Array([1/n.scaleX,1/n.scaleY,-n.offsetX/n.scaleX,-n.offsetY/n.scaleY]):new Float32Array([1,1,0,0])),this.device.gl.uniform1ui(this.backgroundPipelineInfo.progUniforms.flags,e),this.device.gl.bindVertexArray(this.backgroundVAO),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_bg,0),null!==t.backgroundTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_bg),this.backgroundTextureSrc!==t.backgroundTexture&&(this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.backgroundTexture),this.backgroundTextureSrc=t.backgroundTexture)),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_char_body,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_char_body),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.charBodyTexture),this.charData&&(this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_color,2),this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_alpha,3),this.charData.multisample&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+3),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha))),this.device.gl.drawArrays(this.device.gl.TRIANGLES,0,6)}renderMesh(t,e){this.device.gl.enable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);const n=t.char;let i,r=new Float32Array(flatten(this.getProjMat(n.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),i=s?new Float32Array([s.scaleX,s.scaleY,s.scaleX-1+2*s.offsetX,1-s.scaleY-2*s.offsetY]):new Float32Array([1,1,0,0]);let a=n.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=a[t].apply(this.initSkeletonStatus[t].inv());o[t]=e.homogeneous_matrix()}let l=0;for(let t=0;t<Math.min(this.meshStatistics.max_bones,n.skeleton.length);t++){for(let e=0;e<4;e++)for(let n=0;n<4;n++)this._ub_rig_info_data[l+4*e+n]=o[t][n][e];l+=16}if(this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData.multisample){this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.maskPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.maskPipelineInfo.progUniforms.u_proj_mat,!0,r),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,i);for(let t=0;t<n.mesh.length;t++)if(n.mesh[t].genMask){const i=this.meshInfos[t];if(n.mesh[t].blendshapes.size[2]>0){l=16*this.meshStatistics.max_bones;let i=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let r=0;r<i;r++)this._ub_rig_info_data[l+r]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[r]];for(let t=i;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let r=0;n.mesh[t].opacity&&(r+=1);for(const t in i.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[t],i.uniformUInts[t]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,r),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,i.buffers.ub_rig_info),this.device.gl.bindVertexArray(i.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.uniform1i(this.maskPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)}this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.meshPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.meshPipelineInfo.progUniforms.u_proj_mat,!0,r),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,i);let h=!0;for(let t=0;t<n.mesh.length;t++){const i=this.meshInfos[t];let r=i.texturePCAModels[e.data.mesh[t].textureModelIndex];if(n.mesh[t].blendshapes.size[0]>0){l=16*this.meshStatistics.max_bones;let i=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let r=0;r<i;r++)this._ub_rig_info_data[l+r]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[r]];for(let t=i;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let s=0;n.mesh[t].opacity&&(s+=1),null!==this.LUTTexture&&(s+=2),r.unsigned&&(s+=4),h!=n.mesh[t].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!n.mesh[t].genMask),h=n.mesh[t].genMask);for(const t in i.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[t],i.uniformUInts[t]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,s),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_gamma,this.currentGamma.r,this.currentGamma.g,this.currentGamma.b),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_color_balance,this.currentColorBalance.rc,this.currentColorBalance.gm,this.currentColorBalance.by),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,i.buffers.ub_rig_info);let a=Math.min(e.data.mesh[t].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(let n=1;n<a;n++)this._ub_pca_info_data[n]=e.data.mesh[t].texturePCAWeights[n-1];if(r.scalingFactor)for(let t=0;t<a;t++)this._ub_pca_info_data[t]*=r.scalingFactor[t];for(let t=a;t<this.meshStatistics.max_pca_component_count;t++)this._ub_pca_info_data[t]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_pca_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,1,i.buffers.ub_pca_info),this.device.gl.bindVertexArray(i.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,i.buffers.indices),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,i.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),r.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,r.texture),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_lut,2),this.LUTTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture)),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}h||this.device.gl.colorMask(!0,!0,!0,!0),this.charData.multisample&&(this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)}constructor(t,e){this.compat_features={},this.charData=null,this.backgroundBuffers={},this.backgroundTextures={},this.backgroundTextureSrc=null,this.meshPipelineInfo=null,this.maskPipelineInfo=null,this.meshInfos=[],this.meshStatistics={max_pca_component_count:4,max_bs_count:4,max_bones:1},this.FrameTexture_meshColor=null,this.FrameTexture_meshAlpha=null,this.LUTTexture=null,this.FrameBuffer_mesh=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null,this.initSkeletonStatus=[],this.frameDataCallback=()=>null,this.currentGamma={r:1,g:1,b:1},this.currentColorBalance={rc:0,gm:0,by:0},this._ub_shadow_fx_data=null,this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,this.sendSdkPoint=()=>{},this.device=t,this.sendSdkPoint=e,this.reinitialize()}reinitialize(){this.compat_features={},this.compat_features.OES_texture_float_linear=this.device.gl.getExtension("OES_texture_float_linear"),this.compat_features.OES_texture_half_float_linear=this.device.gl.getExtension("OES_texture_half_float_linear"),this.assembleBackgroundPipeline(),this.charData&&this.assembleMeshPipelines(this.charData)}setSyncMedia(t){this.device.run(t=>this.render(),t)}setCharData(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null}setFrameDataCallback(t){this.frameDataCallback=t}setGamma(t,e,n){this.currentGamma={r:t,g:e,b:n}}setColorBalance(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}}getBillboardTransform2D(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};{const n=this.getProjMat(this.charData.char.cameraConfig),i=inv4(n),r=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=r[3][0]/r[3][1],a=[i[0][0]-e[0]*i[3][0],i[1][0]-e[1]*i[3][0],i[2][0]-e[2]*i[3][0]],o=[i[0][1]-t[0]*i[3][1],i[1][1]-t[1]*i[3][1],i[2][1]-t[2]*i[3][1]],l=[i[0][1]-e[0]*i[3][1],i[1][1]-e[1]*i[3][1],i[2][1]-e[2]*i[3][1]],h=s*Math.sqrt([i[0][0]-t[0]*i[3][0],i[1][0]-t[1]*i[3][0],i[2][0]-t[2]*i[3][0]].reduce((t,e)=>t+e*e,0)/a.reduce((t,e)=>t+e*e,0)),d=s*Math.sqrt(o.reduce((t,e)=>t+e*e,0)/l.reduce((t,e)=>t+e*e,0));return{offsetX:.5*(r[0][1]/r[3][1]-r[0][0]/r[3][0]-(h-1)),offsetY:.5*(1-d-(r[1][1]/r[3][1]-r[1][0]/r[3][0])),scaleX:h,scaleY:d}}}getBillboardShadowGeometryInfo(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};{const i=this.getProjMat(this.charData.char.cameraConfig),r=inv4(i),s=[[1,0,0],[0,t[1],1],[0,0,0]],a=[[1,0,0],[0,t[2],1],[0,0,0]];n?(s[2]=[e[0],e[1],1],a[2]=[t[0],-e[2],0]):(s[2]=[e[0],e[1],0],a[2]=[0,-e[2],0]);const o=transpose(mmul(inv3(a),s)),l=mvmul(i,[t[0],t[1],t[2],1]),h=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[i[0][0],i[0][2],i[0][1]*t[1]+i[0][3]],[i[1][0],i[1][2],i[1][1]*t[1]+i[1][3]],[i[3][0],i[3][2],i[3][1]*t[1]+i[3][3]]])),Mat_World2ObjImage:inv3([[r[0][0],r[0][1],r[0][2]*h+r[0][3]],[r[1][0],r[1][1],r[1][2]*h+r[1][3]],[r[3][0],r[3][1],r[3][2]*h+r[3][3]]])}}}render(){var t;const e=this.frameDataCallback();null!==e&&(this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==e.data?this.renderMesh(this.charData,e):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)),this.renderBackground(e),null!==e.onPostRender&&e.onPostRender(this)),null==(t=this.device.gl)||t.flush()}renderFrame(t){this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==t.data&&this.renderMesh(this.charData,t),this.renderBackground(t),this.first_webgl_render&&(window.performanceTracker.markEnd(performanceConstant.first_render),window.performanceTracker.markEnd(performanceConstant.first_webgl_render),this.first_webgl_render=!1,this.sendSdkPoint("render_success_time",{timestamp:Date.now()})),this.device.gl.flush()}destroy(){var t,e,n,i;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(t=>{t.VAO&&this.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(t=>{t&&this.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(t=>{t&&this.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(t=>{t.texture&&this.device.gl.deleteTexture(t.texture)})}),this.meshInfos=[]),this.FrameBuffer_MSAA&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_MSAA),this.FrameBuffer_MSAA=null),this.FrameBuffer_meshColor&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshColor),this.FrameBuffer_meshColor=null),this.FrameBuffer_meshAlpha&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshAlpha),this.FrameBuffer_meshAlpha=null),this.FrameTexture_meshColor&&(this.device.gl.deleteTexture(this.FrameTexture_meshColor),this.FrameTexture_meshColor=null),this.FrameTexture_meshAlpha&&(this.device.gl.deleteTexture(this.FrameTexture_meshAlpha),this.FrameTexture_meshAlpha=null),this.LUTTexture&&(this.device.gl.deleteTexture(this.LUTTexture),this.LUTTexture=null),null!=(n=this.meshPipelineInfo)&&n.program&&(this.device.gl.deleteProgram(this.meshPipelineInfo.program),this.meshPipelineInfo.program=null),null!=(i=this.maskPipelineInfo)&&i.program&&(this.device.gl.deleteProgram(this.maskPipelineInfo.program),this.maskPipelineInfo.program=null)),this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,null==(t=(e=this.device).destroy)||t.call(e)}}const containerWidgetMaps=new Map;let containerIdCounter=0;function getContainerElement(t){return t&&t.el&&t.el instanceof HTMLElement?t.el:null}function getContainerId(t){if(t.id)return t.id;const e=t.getAttribute("data-widget-container-id");if(e)return e;const n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){const e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}const subtitleStyle="bottom: 50px;\nleft: 50%;\ntransform: translateX(-50%);\nbackground: rgba(0, 0, 0, 0.8);\ncolor: white;\npadding: 12px 20px;\nborder-radius: 8px;\nfont-size: 16px;\nfont-weight: 500;\nz-index: 1000;\nmax-width: 80%;\nmin-width: 200px;\nword-break: break-word;\nbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\ntext-align: center;",WidgetDefaultRenderer={_el(t){const{axis_id:e,x_location:n,y_location:i,width:r,height:s}=t,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");let o="position:absolute;";return o+=void 0!==e?`z-index:${e};`:"z-index:1;",void 0!==n&&void 0!==i&&(o+=`top:${100*i}%;left:${100*n}%;`),void 0!==r&&void 0!==s&&(o+=`width:${100*r}%;height:${100*s}%;`),a.setAttribute("style",o),a},_getWidgetKey:(t,e)=>`${t}-${null!=e?e:"default"}`,_replaceWidget(t,e,n,i){const r=this._getWidgetKey(t,e),s=getContainerElement(i||this._currentInstance);if(!s)return;const a=getContainerWidgetMap(s);if(a.has(r)){const t=a.get(r);t&&t.parentNode&&t.remove()}a.set(r,n)},WIDGET_PIC(t,e){const n=this._el(t),i=document.createElement("img");return i.crossOrigin="anonymous",i.setAttribute("style","width:100%;height:100%;"),i.src=t.image,n.appendChild(i),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE(t,e){const{type:n,text:i,axis_id:r}=t,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){const t=getContainerWidgetMap(s),e=this._getWidgetKey("WIDGET_SUBTITLE",r);if(t.has(e)){const n=t.get(e);n&&n.parentNode&&n.remove(),t.delete(e)}}return null}const a=this._el(t);return a.innerHTML=i,a.setAttribute("style",a.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",r,a,e),a},destroy(t){const e=getContainerElement(t||this._currentInstance);if(e){const t=getContainerId(e);if(containerWidgetMaps.has(t)){const e=containerWidgetMaps.get(t);e.forEach((t,e)=>{(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),e.clear(),containerWidgetMaps.delete(t)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(t=>{t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=[0,0,0];for(let e=0;e<3;e++)n[e]=t.dataview.getUint8(t.offset),t.offset+=1;const i=e.split(".").map(t=>parseInt(t));if(i[0]<n[0])throw new Error(`Data version (${n[0]}.${n[1]}.${n[2]}) is incompatible with the version of current data interface (${i[0]}.${i[1]}.${i[2]}).`);return n}function decodeStr(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset);let n=0;for(;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;const i=e.slice(0,n);return new TextDecoder("utf-8").decode(i)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=0,n=0;for(;;){let i=t.dataview.getUint8(t.offset);t.offset++;let r=e|(127&i)<<n;if(r<e)throw new Error("Integer too large to decode.");if(e=r,!(128&i))break;n+=7}return e}const TensorDataTypeMap={B:Uint8Array,b:Int8Array,H:Uint16Array,h:Int16Array,I:Uint32Array,i:Int32Array,L:BigUint64Array,l:BigInt64Array,f:Float32Array,d:Float64Array};"undefined"!=typeof Float16Array&&(TensorDataTypeMap.e=Float16Array);class Tensor{constructor(t,e){this.size=t,this.data=e}itemSize(){let t=1;for(let e of this.size)t*=e;return t}byteSize(){return this.itemSize()*this.data.BYTES_PER_ELEMENT}static zeros(t,e=Float32Array){let n=1;for(let e=0;e<t.length;e++)n*=t[e];const i=new e(n);for(let t=0;t<n;t++)i[t]=0;return new Tensor(t,i)}part(...t){if(t.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");let e=[],n=1;for(let i=t.length;i<this.size.length;i++)e.push(this.size[i]),n*=this.size[i];let i=0;t.length>0&&(i+=t[0]);for(let e=1;e<t.length;e++)i*=this.size[e],i+=t[e];return i*=n,new Tensor(e,this.data.slice(i,i+n))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=t.dataview.getUint8(t.offset);t.offset++;const n=new Array(e);let i=1;for(let r=0;r<e;r++)n[r]=decodeLongInt(t),i*=n[r];const r=String.fromCodePoint(t.dataview.getUint8(t.offset));t.offset++;const s=TensorDataTypeMap[r];if(void 0===s)throw new Error(`Unsupported tensor element type "${r}".`);const a=i*s.BYTES_PER_ELEMENT,o=new s(t.dataview.buffer.slice(t.offset,t.offset+a));return t.offset+=a,new Tensor(n,o)}}function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[null];for(;;){const n=decodeStr(t);if(""==n)break;{let i=null;if("text/plain;charset=UTF-8"===n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e,i=new TextDecoder("utf-8").decode(n)}else if("application/json;charset=UTF-8"==n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e;const r=new TextDecoder("utf-8");i=JSON.parse(r.decode(n))}else if("application/octet-stream"===n)i=Tensor.deserialize(t);else{const e=decodeLongInt(t),r=t.dataview.buffer.slice(t.offset,t.offset+e);t.offset+=e,i=new Blob([r],{type:n})}e.push(i)}}return e}class CameraConfig{constructor(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}getIntrinsicMatrix(t){const[e,n]=t;let i=25.4*this.filmAperture[0];return[[this.focalLength/(i/e),0,t[0]/2],[0,this.focalLength/(i*t[1]/t[0]/n),t[1]/2],[0,0,1]]}getProjMatrix(t,e=.01,n=Infinity){const[i,r]=t,s=this.getIntrinsicMatrix(t);let a,o;return Infinity===n?(a=-1,o=-2*e):(a=-(n+e)/(n-e),o=-2*n*e/(n-e)),[[2*s[0][0]/i,0,(i-2*s[0][2])/i,0],[0,2*s[1][1]/r,(r-2*s[1][2])/r,0],[0,0,a,o],[0,0,-1,0]]}getExtrinsicMatrix(){const t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(e=>e*t),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(t=>-t)))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=new CameraConfig;e.focalLength=t.dataview.getFloat32(t.offset,!0);for(let n=0;n<2;n++)e.filmAperture[n]=t.dataview.getFloat32(t.offset+4*(n+1),!0);for(let n=0;n<3;n++)e.translation[n]=t.dataview.getFloat32(t.offset+4*(n+3),!0);for(let n=0;n<3;n++)e.rotation[n]=t.dataview.getFloat32(t.offset+4*(n+6),!0);return t.offset+=36,e}}class RigidTransform{constructor(t=[0,0,0],e=[1,0,0,0]){this.translation=t,this.rotQuaternion=e}apply(t){if(t instanceof RigidTransform){let e=quaternion_mul(this.rotQuaternion,t.rotQuaternion);e=normalize(e);let n=mvmul(quaternion_to_mat(this.rotQuaternion),t.translation);for(let t=0;t<3;t++)n[t]+=this.translation[t];return new RigidTransform(n,e)}{let e=mvmul(this.matrix(),t);for(let t=0;t<3;t++)e[t]+=this.translation[t];return e}}inv(){let t=quaternion_conj(this.rotQuaternion),e=mvmul(quaternion_to_mat(t),this.translation.map(t=>-t));return new RigidTransform(e,t)}matrix(){return quaternion_to_mat(this.rotQuaternion)}homogeneous_matrix(){return make_homogeneous(this.matrix(),this.translation)}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[0,0,0],n=[1,0,0,0];for(let n=0;n<3;n++)e[n]=t.dataview.getFloat32(t.offset+4*n,!0);let i=0;for(let e=0;e<3;e++)n[e+1]=t.dataview.getFloat32(t.offset+4*(e+3),!0),i+=n[e+1]*n[e+1];return n[0]=Math.sqrt(Math.max(1-i,0)),t.offset+=24,new RigidTransform(e,n)}}class IBRMeshInfo{constructor(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){let n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;let i=[],r=[],s=!0;for(;;){let e=decodeLongInt(t);if(0===e){if(!s)break}else i.push(e-1);s=!1;let n=[],a=!0,o=0;for(;;){let e=decodeLongInt(t);if(a)for(let t=0;t<e;t++)n.push(o+t);if(a=!a,o+=e,0===e&&o>0)break}r.push(n)}let a=r[0].length;this.blendshapeIndices=i;let o=e.archivedItems[decodeLongInt(t)],l=Tensor.zeros([a,o.size[1]],o.data.constructor),h=Tensor.zeros([a,o.size[1],this.blendshapeIndices.length],o.data.constructor),d=0;const c=r[0];for(let t of c){for(let e=0;e<o.size[1];e++)l.data[t*o.size[1]+e]=o.data[d*o.size[1]+e];d++}const u=this.blendshapeIndices.length;for(let t=1;t<r.length;t++){const e=r[t];for(let n of e){for(let e=0;e<o.size[1];e++)h.data[(n*o.size[1]+e)*u+t-1]=o.data[d*o.size[1]+e];d++}}this.vertices=l,this.blendshapes=h,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(a*e.maxJointsPerVertex),this.jointWeight=new Float32Array(a*e.maxJointsPerVertex);for(let n=0;n<a;n++){for(let i=0;i<e.maxJointsPerVertex;i++)this.jointIndex[n*e.maxJointsPerVertex+i]=t.dataview.getUint8(t.offset),t.offset+=1;for(let i=0;i<e.maxJointsPerVertex;i++)this.jointWeight[n*e.maxJointsPerVertex+i]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const f=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(f);for(let n=0;n<f;n++)this.textureModels[n]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;let n=t.dataview.getUint16(t.offset,!0);t.offset+=2;const i=new Float32Array(n);for(let e=0;e<n;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([n],i);let r=t.dataview.getUint16(t.offset,!0);t.offset+=2;const s=new Uint16Array(3*r);for(let e=0;e<r;e++)for(let n=0;n<3;n++)s[3*e+n]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([r,3],s);const a=new Float32Array(2*n);for(let e=0;e<n;e++)for(let n=0;n<2;n++)a[2*e+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([n,2],a);const o=t.dataview.getUint16(t.offset,!0);t.offset+=2;const l=new Float32Array(3*n);for(let e=0;e<3*n;e++)l[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;const h=new Float32Array((o-1)*n*3);for(let e=0;e<o-1;e++)for(let i=0;i<3*n;i++)h[i*(o-1)+e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([n,3],l),this.blendshapes=new Tensor([n,3,o-1],h),this.blendshapeIndices=[];for(let t of e.blendshapeIndices)this.blendshapeIndices.push(t);this.jointIndex=new Uint8Array(n*e.maxJointsPerVertex),this.jointWeight=new Float32Array(n*e.maxJointsPerVertex);for(let i=0;i<n;i++){for(let n=0;n<e.maxJointsPerVertex;n++)this.jointIndex[i*e.maxJointsPerVertex+n]=t.dataview.getUint8(t.offset),t.offset+=1;for(let n=0;n<e.maxJointsPerVertex;n++)this.jointWeight[i*e.maxJointsPerVertex+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const d=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(d);for(let e=0;e<d;e++){const n=[0,0,0,3];for(let e=0;e<3;e++)n[e]=t.dataview.getUint16(t.offset,!0),t.offset+=2;const i=new Float32Array(n[0]*n[1]*n[2]*3);for(let e=0;e<i.length;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[e]={data:new Tensor(n,i)}}}}}class IBRMeshFrameInfo{constructor(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}static deserialize(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let n=t.dataview.getUint8(t.offset);t.offset+=1;let i=new Float32Array(e.textureModels[n].data.size[0]-1);for(let e=0;e<i.length;e++)i[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;return new IBRMeshFrameInfo(n,i)}}class IBRAnimationGeneratorCharInfo_NN{constructor(t,e={}){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__);let i=[];if(n[0]>2&&(i=loadArchives(t)),this.cameraConfig=CameraConfig.deserialize(t),n[0]>2)this.blendshapeCount=decodeLongInt(t);else{if(!e.blendshapeMap)throw new Error("A blendshape map is required to load the character information of v2.0 format.");let t=new Set;for(const n of e.blendshapeMap)for(const e of n)t.add(e);this.blendshapeCount=t.size}let r=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Array(s);for(let e=0;e<s;e++)a[e]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=a,this.skeleton=new Array(r);for(let e=0;e<r;e++){let n=t.dataview.getUint8(t.offset);n>=this.skeleton.length&&(n=null),t.offset+=1;let i=RigidTransform.deserialize(t);this.skeleton[e]={parent:n,local_transform:i}}this.jointEvalOrder=new Array(r);for(let e=0;e<r;e++)this.jointEvalOrder[e]=t.dataview.getUint8(t.offset),t.offset+=1;let o={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(o.archivedItems=i);let l=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(l);for(let i=0;i<l;i++)n[0]<=2&&(o.blendshapeIndices=e.blendshapeMap[i]),this.mesh[i]=new IBRMeshInfo(t,o)}evalSkeleton(){let t=Array(this.skeleton.length);for(let e of this.jointEvalOrder)t[e]=null==this.skeleton[e].parent?this.skeleton[e].local_transform:t[this.skeleton[e].parent].apply(this.skeleton[e].local_transform);return t}evalSkeletonFromMovable(t){let e=Array(this.skeleton.length);for(let n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(let t of this.jointEvalOrder)null!=this.skeleton[t].parent&&(e[t]=e[this.skeleton[t].parent].apply(this.skeleton[t].local_transform));return e}}class IBRAnimationFrameData_NN{constructor(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}static deserialize(t,e,n){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let i=new IBRAnimationFrameData_NN;const r=e.mesh.length;if(i.mesh=new Array(r),i.blendshapeWeights=new Float32Array(e.blendshapeCount),n[0]>2){for(let n=0;n<r;n++)i.mesh[n]=IBRMeshFrameInfo.deserialize(t,e.mesh[n]);for(let e=0;e<i.blendshapeWeights.length;e++)i.blendshapeWeights[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}else for(let n=0;n<r;n++){const r=e.mesh[n].blendshapeIndices;for(let e=0;e+1<r.length;e++)i.blendshapeWeights[r[e+1]-1]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Float32Array(e.mesh[n].textureModels[s].data.size[0]-1);for(let e=0;e<a.length;e++)a[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;i.mesh[n]=new IBRMeshFrameInfo(s,a)}i.movableJointTransforms=new Array(e.movableJoints.length);for(let n=0;n<e.movableJoints.length;n++)i.movableJointTransforms[n]=RigidTransform.deserialize(t);return i}static interp(t,e,n,i,r){let s=new IBRAnimationFrameData_NN;s.blendshapeWeights=new Float32Array(t.blendshapeWeights.length);for(let n=0;n<s.blendshapeWeights.length;n++)s.blendshapeWeights[n]=i*e.blendshapeWeights[n]+(1-i)*t.blendshapeWeights[n];s.mesh=[];for(let n=0;n<t.mesh.length;n++){let r=new IBRMeshFrameInfo(t.mesh[n].textureModelIndex,new Float32Array(t.mesh[n].texturePCAWeights.length));for(let s=0;s<t.mesh[n].texturePCAWeights.length;s++)r.texturePCAWeights[s]=i*e.mesh[n].texturePCAWeights[s]+(1-i)*t.mesh[n].texturePCAWeights[s];s.mesh.push(r)}s.movableJointTransforms=new Array(n.movableJointTransforms.length);for(let t=0;t<n.movableJointTransforms.length;t++){let e=!0;for(let[n,i]of r)if(n===t){e=!1;break}e&&(s.movableJointTransforms[t]=n.movableJointTransforms[t])}for(let[a,o]of r){let r=t.movableJointTransforms[o].inv().apply(t.movableJointTransforms[a]),l=e.movableJointTransforms[o].inv().apply(e.movableJointTransforms[a]),h=[],d=[];for(let t=0;t<3;t++)h.push(i*l.translation[t]+(1-i)*r.translation[t]);for(let t=0;t<4;t++)d.push(i*l.rotQuaternion[t]+(1-i)*r.rotQuaternion[t]);d=normalize(d);let c=new RigidTransform(h,d);c=n.movableJointTransforms[o].apply(c),s.movableJointTransforms[a]=c}return s}}function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__),i=t.dataview.getUint32(t.offset,!0);t.offset+=4;let r=Array(i);for(let s=0;s<i;s++)r[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return r}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){const t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),i=/Google Inc/.test(e),r=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(i||r)&&s}function getStyleStr(t){return Object.entries(t).map(([t,e])=>{const n="number"==typeof e?e.toString():e;return`${t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}:${n};`}).join("")}function updateCanvasXOffset(t,e){const n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+` translateX(${e}px)`;t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){const t=`${screen.width}x${screen.height}`,e=navigator.userAgent,n=navigator.language,i=Intl.DateTimeFormat().resolvedOptions().timeZone,r=encodeURIComponent(`${t}|${e}|${n}|${i}`);return btoa(r)}function getDeviceInfo(){const t=navigator.userAgent;let e="Unknown Brand",n="Unknown Model",i="Unknown Version",r="Unknown Browser",s="Unknown Version";const a=t.match(/Windows NT (\d+\.\d+)/),o=t.match(/Android (\d+\.\d+(\.\d+)?)/),l=t.match(/OS (\d+_\d+(\._\d+)?) like Mac OS X/);a?i=`Windows NT ${a[1]}`:o?i=`Android ${o[1]}`:l?i=`iOS ${l[1].replace(/_/g,".")}`:t.includes("Macintosh")?i="Macintosh":t.includes("Linux")&&(i="Linux"),t.includes("iPhone")||t.includes("iPad")||t.includes("iPod")?(e="Apple",t.includes("iPhone")?n="iPhone":t.includes("iPad")?n="iPad":t.includes("iPod")&&(n="iPod")):t.includes("Android")?(e="Android",n="Android"):t.includes("Windows")?(e="Windows",n=t.includes("Windows Phone")?"Windows Phone":"Windows Desktop"):t.includes("Linux")&&(e="Linux",n="Linux");const h=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),d=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),c=t.match(/Firefox\/(\d+\.\d+(\.\d+)?)\b/),u=t.match(/Edg\/(\d+\.\d+\.\d+\.\d+)/),f=t.match(/Opera\/(\d+\.\d+)/),p=t.match(/MSIE (\d+\.\d+)/);return h?(r="Chrome",s=h[1]):d?(r="Safari",s=d[1]):c?(r="Firefox",s=c[1]):u?(r="Edge",s=u[1]):f?(r="Opera",s=f[1]):p&&(r="IE",s=p[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:i,browser:r,browser_version:s,browser_ua:t}}function validateScaleWithDecimal(t,e){var n;return"number"==typeof t||"string"==typeof t&&(/^\d+(\.\d+)?vh$/.test(t)||/^\d+(\.\d+)?$/.test(t))?t:(null==(n=window.avatarSDKLogger)||n.warn(e,'scale 必须是数字、带小数的数字字符串或者"xxxvh"格式(xxx为数字/小数)'),1)}function isharmony(){const t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}class AvatarRender{constructor(t){this.TAG="[AvatarRender]",this.canvas=document.createElement("canvas"),this.currentBodyFrame=null,this.lastFaceFrame=null,this.isInit=!1,this.isFirstRender=!0,this.lastFrameState="",this.lastRenderState=RenderState.init,this.onStateChange=()=>{},this.onRenderChange=()=>{},this.sendVideoInfo=()=>{},this.lostHandler=()=>{},this.restoreHandler=()=>{},this.avatarCanvasVisible=!0,this.lastRealFaceFrameData=null,this.lastRealFaceFrame=-1,this.lastWeight=0,this.lastFrameIndex=-1,this.canvasOffsetX=-1,this.baseWalkOffset=0,this.lastBodyOffset=0,this.pendingCharData=null,this.interrupt=!1,this.walkConfig=null,this.layout=null,this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.maxLostFrameCount=300,this.forceSyncDecoder=()=>{},this.createPipelineLock=!1,this.restoreTimeout=null,this.isRecovering=!1,this.recoverStartTime=0,this.recoveryStage="light",this.recoveryMaxAttempts={light:2,medium:3,full:2},this.recoveryBaseDelays={light:300,medium:4e3,full:5e3},this.recoveryMaxDelay=3e4,this.currentStageAttempts=0,this.isUsingReducedResolution=!1,this.resolutionRestoreTimer=null,this.RESOLUTION_RESTORE_DELAY=3e4,this.scale=1,this.sendSdkPoint=()=>{},this.options=t,this.onDownloadProgress=t.onDownloadProgress,this.onStateChange=t.onStateChange,this.onRenderChange=t.onRenderChange,this.sendVideoInfo=t.sendVideoInfo,this.saveAndDownload=t.saveAndDownload,this.forceSyncDecoder=t.forceSyncDecoder,this.lostHandler=this._lostHandler.bind(this),this.restoreHandler=this._restoreHandler.bind(this),this.setCanvasVisibility(this.avatarCanvasVisible),this.sendSdkPoint=t.sendSdkPoint,this.device=null,this.pipeline=null,this.copyCanvas=document.createElement("canvas"),this.copyCtx=this.copyCanvas.getContext("2d")}resetFaceFrameState(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")}createPipeline(){this.pipeline||!this.device||this.createPipelineLock||(this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()))}_lostHandler(t){if(t.preventDefault(),window.avatarSDKLogger.error("Context lost.",t),this.device)try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler)}catch(t){}if(this.device)try{this.device.destroy()}catch(t){}if(this.pipeline)try{this.pipeline.destroy()}catch(t){}this.device=null,this.pipeline=null,this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_LOST,message:"Context lost.",e:{event:t,timestamp:Date.now()}}),this.isRecovering?window.avatarSDKLogger.warn("Context recovery already in progress, skipping."):(this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null,window.avatarSDKLogger.log("[Recovery] Cancelled resolution restore due to context loss")),this.isRecovering=!0,this.recoverStartTime=Date.now(),this.recoveryStage="light",this.currentStageAttempts=0,this._scheduleNextAttempt())}_restoreHandler(t){this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering?window.avatarSDKLogger.warn("Context restore event received during recovery, skipping duplicate recovery."):(this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RESTORED,message:"Context restored event received.",e:{event:t,timestamp:Date.now()}}),this.isRecovering=!0,this.recoveryStage="light",this.currentStageAttempts=0,this._recoverContext())}_recoverContext(){if(this.device&&this.pipeline&&this.device.gl&&!this.device.gl.isContextLost())return window.avatarSDKLogger.log("[Recovery] Already recovered, skipping."),void(this.isRecovering=!1);window.avatarSDKLogger.log(`[Recovery] stage=${this.recoveryStage}, attempt=${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[this.recoveryStage]}`),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null);let t=!1;try{switch(this.recoveryStage){case"light":t=this._tryLightRecovery();break;case"medium":t=this._tryMediumRecovery();break;case"full":t=this._tryFullRecovery()}}catch(t){window.avatarSDKLogger.error(`[Recovery] stage=${this.recoveryStage} threw:`,t)}t?this._onRecoverySuccess():(this.currentStageAttempts++,this.isRecovering=!1,this.currentStageAttempts<this.recoveryMaxAttempts[this.recoveryStage]?this._scheduleNextAttempt():this._advanceStage())}_tryLightRecovery(){try{if(window.avatarSDKLogger.log("[Recovery] Trying light recovery (reuse canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after light recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Light recovery failed:",t),this._reportRecoveryFailure("light",t),!1}}_tryMediumRecovery(){try{var t;if(window.avatarSDKLogger.log("[Recovery] Trying medium recovery (replace canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after medium recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Medium recovery failed:",t),this._reportRecoveryFailure("medium",t),!1}}_tryFullRecovery(){try{var t,e,n;if(window.avatarSDKLogger.log("[Recovery] Trying full recovery (reduced resolution)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,l=.75,h=Math.round((null!=(e=null==o?void 0:o.width)?e:1080)*l),d=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=h,a.height=d,a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,window.avatarSDKLogger.log(`[Recovery] Using reduced resolution: ${h}x${d} (scale=${l})`),this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after full recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Full recovery failed:",t),this._reportRecoveryFailure("full",t),!1}}_onRecoverySuccess(){const t=Date.now()-this.recoverStartTime,e="full"===this.recoveryStage;window.avatarSDKLogger.log(`[Recovery] Success! stage=${this.recoveryStage}, time=${t}ms${e?" (reduced resolution)":""}`),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERED,message:`Context recovered via ${this.recoveryStage} recovery in ${t}ms.`,e:{timestamp:Date.now(),recoveryTime:t,stage:this.recoveryStage,attempts:this.currentStageAttempts+1,reducedResolution:e}}),e&&(this.isUsingReducedResolution=!0,this._scheduleResolutionRestore()),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0}_scheduleResolutionRestore(){this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log(`[Recovery] Scheduling resolution restore in ${this.RESOLUTION_RESTORE_DELAY}ms`),this.resolutionRestoreTimer=setTimeout(()=>{this._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)}_restoreOriginalResolution(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");const i=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,r=null!=(e=null==i?void 0:i.width)?e:1080,s=null!=(n=null==i?void 0:i.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=r,l.height=s,l.setAttribute("style",a),o&&o.replaceChild(l,this.canvas),this.canvas=l,this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("Context lost after resolution restore");this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isUsingReducedResolution=!1,window.avatarSDKLogger.log(`[Recovery] Resolution restored to ${r}x${s}`),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:`Resolution restored to ${r}x${s}.`,e:{timestamp:Date.now(),resolution:{width:r,height:s}}})}catch(t){window.avatarSDKLogger.warn("[Recovery] Failed to restore resolution, keeping reduced:",t)}finally{this.resolutionRestoreTimer=null}else window.avatarSDKLogger.warn("[Recovery] Cannot restore resolution: not in reduced mode or context lost")}_advanceStage(){const t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){const n=t[e+1];window.avatarSDKLogger.log(`[Recovery] Stage "${this.recoveryStage}" exhausted, upgrading to "${n}"`),this.recoveryStage=n,this.currentStageAttempts=0,this._scheduleNextAttempt()}else window.avatarSDKLogger.error("[Recovery] All recovery stages exhausted. Giving up."),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS,message:"All WebGL recovery stages exhausted. SDK restart required.",e:{timestamp:Date.now(),elapsedTime:Date.now()-this.recoverStartTime,stagesAttempted:{light:this.recoveryMaxAttempts.light,medium:this.recoveryMaxAttempts.medium,full:this.recoveryMaxAttempts.full}}}),this.isRecovering=!1}_scheduleNextAttempt(){const t=this.recoveryBaseDelays[this.recoveryStage],e=this.recoveryMaxAttempts[this.recoveryStage],n=t*Math.pow(2,this.currentStageAttempts),i=Math.min(n,this.recoveryMaxDelay);window.avatarSDKLogger.log(`[Recovery] Scheduling ${this.recoveryStage} attempt ${this.currentStageAttempts+1}/${e} in ${i}ms (base=${t}ms, exp=${n}ms)`),this.restoreTimeout=setTimeout(()=>{this.isRecovering=!0,this._recoverContext()},i)}_reportRecoveryFailure(t,e){this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_FAILED,message:`[${t}] recovery attempt ${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[t]} failed.`,e:{error:e,stage:t,attempt:this.currentStageAttempts+1,timestamp:Date.now()}})}init(t){var e,n,i,r,s;let a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(i=null==(r=this.options.resourceManager.getConfig())||null==(r=r.resolution)?void 0:r.height)?i:1920),this.setCharacterCanvasAnchor(),null!=(s=a)&&s.char||(a={char:this.options.resourceManager.getMouthShapeLib().char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4}),this.pendingCharData=a,this.isInit=!0,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),this.createPipeline()}style(t=0,e=0){t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)}setCanvasStyle(t){var e,n,i,r,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;const h=null!=(e=null!=(n=null==(i=this.walkConfig)?void 0:i.init_point)?n:null==(r=this.options.resourceManager.getConfig())||null==(r=r.walk_config)?void 0:r.init_point)?e:null,{width:d=1080,height:c=1920}=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},[u,f]=null!=(o=null==(l=t.container)?void 0:l.size)?o:[d,c];let{v_align:p="center",h_align:_="center",scale:m=1,offset_x:g=0,offset_y:y=0}=t.avatar||{};if(null!=h&&(_="left",g=0),"string"==typeof m&&m.includes("vh")){const t=parseFloat(m.replace("vh",""));m=isNaN(t)?1:t/100*f/c}this.scale=Number(m);const v=c*Number(m),b=d*Number(m),S=b/2,E=v/2,w={position:"absolute",zIndex:100,height:`${v}px`,width:`${b}px`,objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(_){case"left":w.left=null!=h?h-S+"px":"0",w.marginLeft=`${g}px`;break;case"right":w.right=`-${S}px`,w.marginLeft=`${g}px`;break;default:w.position="absolute",w.left="50%",w.marginLeft=`${-S+g}px`}switch(p){case"top":w.top="0",w.marginTop=`${y}px`;break;case"bottom":w.bottom="0",w.marginTop=`${y}px`;break;default:w.position="absolute",w.top="50%",w.marginTop=`${-E+y}px`}const x=getStyleStr(w);this.canvas.setAttribute("style",x)}setWalkConfig(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)}setCharacterCanvasAnchor(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n;const t=(null==(n=this.options.resourceManager.getConfig())?void 0:n.layout)||{avatar:{v_align:"default",h_align:"default",scale:1,offset_x:0,offset_y:0}};this.setCanvasStyle(t)}else{var i;const t=getStyleStr({position:"absolute",zIndex:100,height:"100%",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0"});this.canvas.setAttribute("style",t);const e=(null==(i=this.options.resourceManager.getConfig())||null==(i=i.init_events)?void 0:i.find(t=>"SetCharacterCanvasAnchor"===t.type))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1},{x_location:n,y_location:r,width:s,height:a}=e;this.canvas.setAttribute("style",this.canvas.style.cssText+`left: calc(${n} * 100%); top: calc(${r} * 100%); transform: scale(${s}, ${a}); transform-origin: top left;`)}}computeWeight(t){const e=t-this.lastFrameIndex;return this.lastWeight=t>this.lastRealFaceFrame?Math.min(this.lastWeight+e,12):Math.max(this.lastWeight-e,0),this.lastWeight/12}render(t){var e,n,i,r,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};const l=this.options.dataCacheQueue._getBodyImageBitmap(t);let h=this.options.dataCacheQueue._getFaceImageBitmap(t,null!=(e=null!=(n=null==l?void 0:l.body_id)?n:null==l?void 0:l.id)?e:0),d=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(i=null!=(r=null==l?void 0:l.body_id)?r:null==l?void 0:l.id)?i:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)h=d;else if(null!=(s=h)&&s.FaceFrameData&&null!=(a=h)&&a.face_frame_type){if(this.lastRealFaceFrameData=h.FaceFrameData,this.lastRealFaceFrame=t,-1!==this.lastRealFaceFrame&&this.lastWeight>0&&d){var c,u;const e=this.computeWeight(t);h={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(c=h)?void 0:c.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)h=d;else if(null!=d&&d.FaceFrameData)if(null===this.lastRealFaceFrameData)h=d;else{var f,p;const e=this.computeWeight(t);h={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(f=h)?void 0:f.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(p=this.options.resourceManager.resource_pack)?void 0:p.interpolate_joints)||[])}}if(this._setCurrentBodyFrame(l),!(l&&h||null==l)&&l.hfd||!(null!=l&&l.hfd||null!=l&&l.frame))return l?h||(this.allLostFaceFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_FACE_ERROR,message:`Error: 第${t}帧 faceFrame为空`,e:{bodyFrame:l,faceFrame:h}})):(this.allLostFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_BODY_ERROR,message:`Error: 第${t}帧 bodyFrame为空`,e:{bodyFrame:l,faceFrame:h}})),this.allLostFrameCount===this.maxLostFrameCount&&(this.options.reportMessage({code:EErrorCode.RENDER_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 身体渲染数据缺失`,e:{bodyFrame:l,faceFrame:h}}),this.forceSyncDecoder(),this.allLostFrameCount=0),this.allLostFaceFrameCount===this.maxLostFrameCount&&this.options.reportMessage({code:EErrorCode.RENDER_FACE_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 渲染表情数据缺失.`,e:{bodyFrame:l,frameIndex:t}}),window.avatarSDKLogger.log(this.TAG,"render第",t,"丢帧,bodyFrame",l,"faceFrame",h),{canvas:this.canvas,rendered:!1};if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,(l&&null!=(o=h)&&o.FaceFrameData&&null!=l&&l.hfd||(null==l||!l.hfd)&&null!=l&&l.frame)&&this.device){var _,m;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(_=this.onStateChange)||_.call(this,null==l?void 0:l.frameState),"speak"!==l.frameState&&window.performanceTracker.markEnd(performanceConstant.start_action_render,l.frameState),this.lastFrameState=null==l?void 0:l.frameState),this.isFirstRender&&(window.performanceTracker.markEnd(performanceConstant.first_avatar_render),this.isFirstRender=!1,this.renderBackground(),window.performanceTracker.markStart(performanceConstant.first_render),null==(m=this.onDownloadProgress)||m.call(this,100));let e=!1;if(this.pipeline){var g;try{var y,v,b,S,E,w,x;const n=this.options.resourceManager.getIsEnableRobotExpression()?null!=(y=null==(v=h)?void 0:v.FaceFrameData)?y:null:null!=l&&l.hfd&&null!=(b=null==(S=h)?void 0:S.FaceFrameData)?b:null;n&&this.saveAndDownload.appendMultipleToArray("render_faceData",[h]),this.lastFaceFrame=h;let i=l.frame;var T;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(T=this.copyCtx)||T.drawImage(l.frame,0,0),i=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:i,data:n,backgroundTexture:null,fx:null!=(E=null==(w=this.options.resourceManager.getConfig())?void 0:w.fx)?E:{},onPostRender:()=>null});let r=[0,0,0],s=[...r];const a=null!=(x=null==l?void 0:l.offset)?x:0;this.lastBodyOffset=a,s[0]+=a-this.baseWalkOffset;const o=this.pipeline.getBillboardTransform2D([r[0],r[1],r[2]],[s[0],s[1],s[2]]).offsetX*this.canvas.width*this.scale;o!==this.canvasOffsetX&&(this.canvasOffsetX=o,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:o}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(o):updateCanvasXOffset(this.canvas,o)),this.lastFrameIndex=t,e=!0}catch(e){window.avatarSDKLogger.error(this.TAG,"渲染帧失败:",e),this.options.reportMessage({code:EErrorCode.WebGL_RENDER_ERROR,message:`Error: 第${t}帧 webgl渲染异常`,e:{bodyFrame:l,faceFrame:h,error:e}})}finally{l.frame&&"function"==typeof l.frame.close&&l.frame.close()}null==(g=this.onRenderChange)||g.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:e}}return{canvas:this.canvas,rendered:!1}}renderBackground(){const t=this.options.resourceManager.getBackgroundImageElement();if(!t)return;const e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage=`url(${t.src})`,e.style.backgroundSize="cover",e.style.backgroundPosition="center")}_setCurrentBodyFrame(t){t&&(this.currentBodyFrame=t)}_getCurrentBodyFrameInfo(t){return this.currentBodyFrame&&t>0?{client_frame:t,current_ani:this.currentBodyFrame.name,current_ani_frame:this.currentBodyFrame.frameIndex-this.currentBodyFrame.sf,next_state:this.lastFrameState||"idle"}:{client_frame:0,current_ani:"",current_ani_frame:0,next_state:"idle"}}_getCurrentFrameData(t){var e,n,i,r,s;const a=this.currentBodyFrame,o=this.lastFaceFrame;return{body:a?{body_id:null!=(e=null!=(n=a.body_id)?n:a.id)?e:0,name:a.name,video_frame:a.frameIndex-a.sf,sf:a.sf,state:a.frameState}:null,face:o?{body_id:null!=(i=null!=(r=o.body_id)?r:o.id)?i:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}}setCanvasVisibility(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")}getCanvasVisibility(){return this.avatarCanvasVisible}destroy(){if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0,this.device)if(this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.pipeline&&(this.pipeline.destroy(),this.pipeline=null),this.device.gl){const t=this.device;this.device=null,requestAnimationFrame(()=>{try{t&&t.destroy()}catch(t){var e;null==(e=window.avatarSDKLogger)||null==e.warn||e.warn("[AvatarRenderer] 销毁 device 时出错:",t)}})}else this.device=null;this.isInit=!1,this.isFirstRender=!0,this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,this.onStateChange=void 0,this.lastFrameState="",this.pipeline=null,this.pendingCharData=null,this.scale=1;const t=document.getElementById("avatar-bg-container");t&&t.parentNode&&t.parentNode.removeChild(t),this.canvas&&this.canvas.parentNode&&this.canvas.remove()}setInterrupt(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)}simulateContextLoss(t=5e3,e=!1){if(!this.device||!this.device.gl)return void window.avatarSDKLogger.warn("[Test] No WebGL device available for testing");const n=this.device.gl.getExtension("WEBGL_lose_context");n?(window.avatarSDKLogger.log("[Test] Simulating WebGL context loss..."),e&&window.avatarSDKLogger.warn("[Test] Force fail mode enabled - will not auto-restore"),n.loseContext(),t>0&&!e&&setTimeout(()=>{window.avatarSDKLogger.log(`[Test] Auto-restoring context after ${t}ms...`),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}getRecoveryStatus(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}}async testStagedRecovery(){window.avatarSDKLogger.log("[Test] Starting staged recovery test...");const t=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}];for(let e=0;e<t.length;e++){const n=t[e];window.avatarSDKLogger.log(`[Test] Step ${e+1}: ${n.desc}`),await new Promise(t=>{setTimeout(()=>{this.simulateContextLoss(n.delay,n.forceFail),t()},n.delay)}),await new Promise(t=>setTimeout(t,n.delay+2e3));const i=this.getRecoveryStatus();window.avatarSDKLogger.log(`[Test] After step ${e+1}:`,i)}window.avatarSDKLogger.log("[Test] Staged recovery test completed!")}restartWebGL(){window.avatarSDKLogger.log("[restartWebGL] Starting manual WebGL restart..."),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0;try{var t;if(this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const i=this.canvas,r=i.style.cssText,s=i.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",r),s&&s.replaceChild(a,i),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after creating new canvas");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,window.avatarSDKLogger.log("[restartWebGL] WebGL restart successful!"),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_MANUAL_RESTARTED,message:"WebGL context recovered via manual restart.",e:{timestamp:Date.now(),method:"manual_restart"}}),!0}catch(t){return window.avatarSDKLogger.error("[restartWebGL] Failed:",t),this._reportRecoveryFailure("manual",t),!1}}}class BaseTrack{render(){}stop(){}}class ImageTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null}}class SubtitleTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)}}class TrackRenderer{constructor(t,e){this.TAG="[TrackRenderer]",this.instance=e;const{type:n,data:i,text:r=""}=t;var s;"widget_pic"===n&&(this.tracker=new ImageTrack(i,e)),("subtitle_on"===n||"subtitle_off"===n)&&(this.tracker=new SubtitleTrack({type:n,text:r,axis_id:null!=(s=null==i?void 0:i.axis_id)?s:1e3},e))}render(){var t;return null==(t=this.tracker)?void 0:t.render()}stop(){this.tracker.stop()}destroy(){WidgetDefaultRenderer.destroy(this.instance)}}class UIRenderer{constructor(t){this.TAG="[UIRenderer]",this.trackerRenderer=[],this.root=document.createElement("div"),this.lastFrameIndex=-1,this.initEventsRendered=!1,this.lastSpeechId=-1,this.interruptSpeechId=-1,this.enableClientInterrupt=!1,this.options=t,this.root.setAttribute("style","position:absolute;"),this.onVoiceStart=t.onVoiceStart,this.onVoiceEnd=t.onVoiceEnd,this.initEventsRendered=!1,this.onWalkStateChange=t.onWalkStateChange,this.enableClientInterrupt=t.enableClientInterrupt,this.onSpeakStateChange=t.onSpeakStateChange}render(t){var e,n,i,r,s,a,o,l,h;let d=[];if(-1===this.lastFrameIndex){const t=this.options.resourceManager.getConfig();t.init_events&&t.init_events.length>0&&(d=t.init_events.map(t=>_extends({},t,{speech_id:0})))}let c=null;if(c=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,c?c.e=c.e.concat(d):c={e:d}),null==(e=c)||!e.e)return;window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(c));const u=null==(n=c.e)?void 0:n.filter(t=>null==(null==t?void 0:t.speech_id));if(null!=u&&u.length){const t=u.map(t=>t.type).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:`Error: 事件中存在不包含speech_id的事件${t}`,e:u})}var f,p;if(this.enableClientInterrupt&&(c.e=null==(f=c.e)?void 0:f.filter(t=>t.speech_id>this.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type)),-1!==this.lastSpeechId&&this.lastSpeechId&&(c.e=null==(p=c.e)?void 0:p.filter(t=>(null==t?void 0:t.speech_id)>=this.lastSpeechId)),null!=(i=c.e)&&i.some(t=>"speak_start"===t.type)){const t=c.e.find(t=>"speak_start"===t.type);this.lastSpeechId=null==t?void 0:t.speech_id,this.onSpeakStateChange("speak_start",t.client_speak_id,(null==t?void 0:t.speech_id)||0)}if((null!=(r=c.e)&&r.some(t=>"walk_start"===t.type)||null!=(s=c.e)&&s.some(t=>"speak_walk_start"===t.type))&&this.onWalkStateChange("walk_start"),null!=(a=c.e)&&a.some(t=>"voice_start"===t.type)){const t=c.e.find(t=>"voice_start"===t.type),e=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==t?void 0:t.multi_turn_conversation_id}),this.onVoiceStart(e,null==t?void 0:t.client_speak_id)}if((null!=(o=c.e)&&o.some(t=>"walk_end"===t.type)||null!=(l=c.e)&&l.some(t=>"speak_walk_end"===t.type))&&this.onWalkStateChange("walk_end"),null!=(h=c.e)&&h.some(t=>"voice_end"===t.type)){const t=c.e.find(t=>"voice_end"===t.type);this.onVoiceEnd((null==t?void 0:t.client_speak_id)||"",(null==t?void 0:t.speech_id)||0)}["speak_end","speak_error"].forEach(t=>{const e=c.e.find(e=>e.type===t);e&&this.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});const _=[...c.e];for(let t=0;t<c.e.length;t++){const e=c.e[t];if(!Object.prototype.hasOwnProperty.call(e,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(e);const t=_.indexOf(e);t>-1&&_.splice(t,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[e.type]){WidgetDefaultRenderer.PROXY_WIDGET[e.type](e);const t=_.indexOf(e);t>-1&&_.splice(t,1)}}if(_.length>0)for(const t of _){const e=new TrackRenderer(t,this.options.sdk);this.trackerRenderer.push(e)}return this.trackerRenderer}clearTrackerRenderer(){this.trackerRenderer=[]}setInterrupt(t){this.interruptSpeechId=t}destroy(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(t=>t.destroy())}}class FPSTracker{constructor(t=60){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0,this.maxSamples=t}tick(t=!0){const e=performance.now();if(this.lastFrameTime>0){const n=e-this.lastFrameTime;this.frameTimestamps.push(n),this.frameTimestamps.length>this.maxSamples&&this.frameTimestamps.shift(),this.totalFrames++,this.totalTime+=n,t?(this.frameCount++,this.totalRenderedFrames++):this.droppedFrames++,e-this.lastUpdateTime>=1e3&&(this.currentFPS=Math.round(1e3*this.frameCount/(e-this.lastUpdateTime)),this.frameCount=0,this.lastUpdateTime=e)}this.lastFrameTime=e}getStats(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};const t=this.frameTimestamps.reduce((t,e)=>t+e,0)/this.frameTimestamps.length,e=Math.min(...this.frameTimestamps),n=Math.max(...this.frameTimestamps);return{current:this.currentFPS,average:this.frameTimestamps.length>0?Math.round(1e3/t):0,min:e>0?Math.round(1e3/n):0,max:n>0?Math.round(1e3/e):0,droppedFrames:this.droppedFrames,totalFrames:this.totalFrames}}getCurrentFPS(){return this.currentFPS}getAverageFPS(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)}reset(){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0}getDroppedFrames(){return this.droppedFrames}}class Composition{constructor(t){this.TAG="[Composition]",this.container=t.container,this.avatarRenderer=t.avatarRenderer,this.restRenderers=t.restRenderers,this.audioRenderer=t.audioRenderer,this.onFPSUpdate=t.onFPSUpdate,this.audioOnlyMode=t.audioOnlyMode||!1,this.fpsTracker=new FPSTracker,this.audioOnlyMode||this.container.appendChild(t.avatarRenderer.canvas)}compose(t){if(!this.audioOnlyMode){const e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);const n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(const e of this.restRenderers){const n=e.render(t);if(e.clearTrackerRenderer(),n)for(const t of n){const e=null==t?void 0:t.render();e&&this.container.appendChild(e)}}}getFPSStats(){return this.fpsTracker.getStats()}stop(){this.audioRenderer.stop(-1)}destroy(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(t=>t.destroy())}}const mp4boxSource='\nvar Log = function() {\n\tvar i = new Date,\n\tr = 4;\n\treturn {\n\t\tsetLogLevel: function(t) {\n\t\t\tr = t == this.debug ? 1 : t == this.info ? 2 : t == this.warn ? 3 : (this.error, 4)\n\t\t},\n\t\tdebug: function(t, e) {\n\t\t\tvoid 0 === console.debug && (console.debug = console.log),\n\t\t\tr <= 1 && console.debug("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\tlog: function(t, e) {\n\t\t\tthis.debug(t.msg)\n\t\t},\n\t\tinfo: function(t, e) {\n\t\t\tr <= 2 && console.info("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\twarn: function(t, e) {\n\t\t\tr <= 3 && console.warn("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\terror: function(t, e) {\n\t\t\tr <= 4 && console.error("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t}\n\t}\n} ();\nLog.getDurationString = function(t, e) {\n\tvar i;\n\tfunction r(t, e) {\n\t\tfor (var i = ("" + t).split("."); i[0].length < e;) i[0] = "0" + i[0];\n\t\treturn i.join(".")\n\t}\n\tt < 0 ? (i = !0, t = -t) : i = !1;\n\tvar s = t / (e || 1),\n\ta = Math.floor(s / 3600);\n\ts -= 3600 * a;\n\tt = Math.floor(s / 60),\n\te = 1e3 * (s -= 60 * t);\n\treturn e -= 1e3 * (s = Math.floor(s)),\n\te = Math.floor(e),\n\t(i ? "-": "") + a + ":" + r(t, 2) + ":" + r(s, 2) + "." + r(e, 3)\n},\nLog.printRanges = function(t) {\n\tvar e = t.length;\n\tif (0 < e) {\n\t\tfor (var i = "",\n\t\tr = 0; r < e; r++) 0 < r && (i += ","),\n\t\ti += "[" + Log.getDurationString(t.start(r)) + "," + Log.getDurationString(t.end(r)) + "]";\n\t\treturn i\n\t}\n\treturn "(empty)"\n},\n"undefined" != typeof exports && (exports.Log = Log);\nvar MP4BoxStream = function(t) {\n\tif (! (t instanceof ArrayBuffer)) throw "Needs an array buffer";\n\tthis.buffer = t,\n\tthis.dataview = new DataView(t),\n\tthis.position = 0\n};\nMP4BoxStream.prototype.getPosition = function() {\n\treturn this.position\n},\nMP4BoxStream.prototype.getEndPosition = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.getLength = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.buffer.byteLength, t));\n\treturn this.position = isNaN(t) || !isFinite(t) ? 0 : t,\n\t!0\n},\nMP4BoxStream.prototype.isEos = function() {\n\treturn this.getPosition() >= this.getEndPosition()\n},\nMP4BoxStream.prototype.readAnyInt = function(t, e) {\n\tvar i = 0;\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tswitch (t) {\n\t\tcase 1:\n\t\t\ti = e ? this.dataview.getInt8(this.position) : this.dataview.getUint8(this.position);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ti = e ? this.dataview.getInt16(this.position) : this.dataview.getUint16(this.position);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tif (e) throw "No method for reading signed 24 bits values";\n\t\t\ti = this.dataview.getUint8(this.position) << 16,\n\t\t\ti |= this.dataview.getUint8(this.position + 1) << 8,\n\t\t\ti |= this.dataview.getUint8(this.position + 2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ti = e ? this.dataview.getInt32(this.position) : this.dataview.getUint32(this.position);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tif (e) throw "No method for reading signed 64 bits values";\n\t\t\ti = this.dataview.getUint32(this.position) << 32,\n\t\t\ti |= this.dataview.getUint32(this.position + 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "readInt method not implemented for size: " + t\n\t\t}\n\t\treturn this.position += t,\n\t\ti\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readUint8 = function() {\n\treturn this.readAnyInt(1, !1)\n},\nMP4BoxStream.prototype.readUint16 = function() {\n\treturn this.readAnyInt(2, !1)\n},\nMP4BoxStream.prototype.readUint24 = function() {\n\treturn this.readAnyInt(3, !1)\n},\nMP4BoxStream.prototype.readUint32 = function() {\n\treturn this.readAnyInt(4, !1)\n},\nMP4BoxStream.prototype.readUint64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readString = function(t) {\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tfor (var e = "",\n\t\ti = 0; i < t; i++) e += String.fromCharCode(this.readUint8());\n\t\treturn e\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readCString = function() {\n\tfor (var t = [];;) {\n\t\tvar e = this.readUint8();\n\t\tif (0 === e) break;\n\t\tt.push(e)\n\t}\n\treturn String.fromCharCode.apply(null, t)\n},\nMP4BoxStream.prototype.readInt8 = function() {\n\treturn this.readAnyInt(1, !0)\n},\nMP4BoxStream.prototype.readInt16 = function() {\n\treturn this.readAnyInt(2, !0)\n},\nMP4BoxStream.prototype.readInt32 = function() {\n\treturn this.readAnyInt(4, !0)\n},\nMP4BoxStream.prototype.readInt64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readUint8Array = function(t) {\n\tfor (var e = new Uint8Array(t), i = 0; i < t; i++) e[i] = this.readUint8();\n\treturn e\n},\nMP4BoxStream.prototype.readInt16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readInt16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readUint16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint32Array = function(t) {\n\tfor (var e = new Uint32Array(t), i = 0; i < t; i++) e[i] = this.readUint32();\n\treturn e\n},\nMP4BoxStream.prototype.readInt32Array = function(t) {\n\tfor (var e = new Int32Array(t), i = 0; i < t; i++) e[i] = this.readInt32();\n\treturn e\n},\n"undefined" != typeof exports && (exports.MP4BoxStream = MP4BoxStream);\nvar DataStream = function(t, e, i) {\n\tthis._byteOffset = e || 0,\n\tt instanceof ArrayBuffer ? this.buffer = t: "object" == typeof t ? (this.dataView = t, e && (this._byteOffset += e)) : this.buffer = new ArrayBuffer(t || 0),\n\tthis.position = 0,\n\tthis.endianness = null == i ? DataStream.LITTLE_ENDIAN: i\n};\nDataStream.prototype = {},\nDataStream.prototype.getPosition = function() {\n\treturn this.position\n},\nDataStream.prototype._realloc = function(t) {\n\tif (this._dynamicSize) {\n\t\tvar e = this._byteOffset + this.position + t,\n\t\ti = this._buffer.byteLength;\n\t\tif (e <= i) e > this._byteLength && (this._byteLength = e);\n\t\telse {\n\t\t\tfor (i < 1 && (i = 1); i < e;) i *= 2;\n\t\t\tvar r = new ArrayBuffer(i),\n\t\t\tt = new Uint8Array(this._buffer);\n\t\t\tnew Uint8Array(r, 0, t.length).set(t),\n\t\t\tthis.buffer = r,\n\t\t\tthis._byteLength = e\n\t\t}\n\t}\n},\nDataStream.prototype._trimAlloc = function() {\n\tvar t, e, i;\n\tthis._byteLength != this._buffer.byteLength && (t = new ArrayBuffer(this._byteLength), e = new Uint8Array(t), i = new Uint8Array(this._buffer, 0, e.length), e.set(i), this.buffer = t)\n},\nDataStream.BIG_ENDIAN = !1,\nDataStream.LITTLE_ENDIAN = !0,\nDataStream.prototype._byteLength = 0,\nObject.defineProperty(DataStream.prototype, "byteLength", {\n\tget: function() {\n\t\treturn this._byteLength - this._byteOffset\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "buffer", {\n\tget: function() {\n\t\treturn this._trimAlloc(),\n\t\tthis._buffer\n\t},\n\tset: function(t) {\n\t\tthis._buffer = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "byteOffset", {\n\tget: function() {\n\t\treturn this._byteOffset\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "dataView", {\n\tget: function() {\n\t\treturn this._dataView\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t.byteOffset,\n\t\tthis._buffer = t.buffer,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._byteOffset + t.byteLength\n\t}\n}),\nDataStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.byteLength, t));\n\tthis.position = isNaN(t) || !isFinite(t) ? 0 : t\n},\nDataStream.prototype.isEof = function() {\n\treturn this.position >= this._byteLength\n},\nDataStream.prototype.mapUint8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Uint8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.readInt32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Int32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Int16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Int8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readUint32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Uint32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Uint16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Uint8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readFloat64Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 8 : t;\n\tvar i = new Float64Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readFloat32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Float32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt32 = function(t) {\n\tt = this._dataView.getInt32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readInt16 = function(t) {\n\tt = this._dataView.getInt16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readInt8 = function() {\n\tvar t = this._dataView.getInt8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readUint32 = function(t) {\n\tt = this._dataView.getUint32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readUint16 = function(t) {\n\tt = this._dataView.getUint16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readUint8 = function() {\n\tvar t = this._dataView.getUint8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readFloat32 = function(t) {\n\tt = this._dataView.getFloat32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readFloat64 = function(t) {\n\tt = this._dataView.getFloat64(this.position, null == t ? this.endianness: t);\n\treturn this.position += 8,\n\tt\n},\nDataStream.endianness = 0 < new Int8Array(new Int16Array([1]).buffer)[0],\nDataStream.memcpy = function(t, e, i, r, s) {\n\te = new Uint8Array(t, e, s),\n\ts = new Uint8Array(i, r, s);\n\te.set(s)\n},\nDataStream.arrayToNative = function(t, e) {\n\treturn e == this.endianness ? t: this.flipArrayEndianness(t)\n},\nDataStream.nativeToEndian = function(t, e) {\n\treturn this.endianness == e ? t: this.flipArrayEndianness(t)\n},\nDataStream.flipArrayEndianness = function(t) {\n\tfor (var e = new Uint8Array(t.buffer, t.byteOffset, t.byteLength), i = 0; i < t.byteLength; i += t.BYTES_PER_ELEMENT) for (var r = i + t.BYTES_PER_ELEMENT - 1,\n\ts = i; s < r; r--, s++) {\n\t\tvar a = e[s];\n\t\te[s] = e[r],\n\t\te[r] = a\n\t}\n\treturn t\n},\nDataStream.prototype.failurePosition = 0,\nString.fromCharCodeUint8 = function(t) {\n\tfor (var e = [], i = 0; i < t.length; i++) e[i] = t[i];\n\treturn String.fromCharCode.apply(null, e)\n},\nDataStream.prototype.readString = function(t, e) {\n\treturn null == e || "ASCII" == e ? String.fromCharCodeUint8.apply(null, [this.mapUint8Array(null == t ? this.byteLength - this.position: t)]) : new TextDecoder(e).decode(this.mapUint8Array(t))\n},\nDataStream.prototype.readCString = function(t) {\n\tvar e = this.byteLength - this.position,\n\ti = new Uint8Array(this._buffer, this._byteOffset + this.position),\n\tr = e;\n\tnull != t && (r = Math.min(t, e));\n\tfor (var s = 0; s < r && 0 !== i[s]; s++);\n\tvar a = String.fromCharCodeUint8.apply(null, [this.mapUint8Array(s)]);\n\treturn null != t ? this.position += r - s: s != e && (this.position += 1),\n\ta\n};\nvar MAX_SIZE = Math.pow(2, 32);\nDataStream.prototype.readInt64 = function() {\n\treturn this.readInt32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readInt64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint24 = function() {\n\treturn (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8()\n},\n"undefined" != typeof exports && (exports.DataStream = DataStream),\nDataStream.prototype.save = function(t) {\n\tvar e = new Blob([this.buffer]);\n\tif (!window.URL || !URL.createObjectURL) throw "DataStream.save: Can\'t create object URL.";\n\tvar i = window.URL.createObjectURL(e),\n\te = document.createElement("a");\n\tdocument.body.appendChild(e),\n\te.setAttribute("href", i),\n\te.setAttribute("download", t),\n\te.setAttribute("target", "_self"),\n\te.click(),\n\twindow.URL.revokeObjectURL(i)\n},\nDataStream.prototype._dynamicSize = !0,\nObject.defineProperty(DataStream.prototype, "dynamicSize", {\n\tget: function() {\n\t\treturn this._dynamicSize\n\t},\n\tset: function(t) {\n\t\tt || this._trimAlloc(),\n\t\tthis._dynamicSize = t\n\t}\n}),\nDataStream.prototype.shift = function(t) {\n\tvar e = new ArrayBuffer(this._byteLength - t),\n\ti = new Uint8Array(e),\n\tr = new Uint8Array(this._buffer, t, i.length);\n\ti.set(r),\n\tthis.buffer = e,\n\tthis.position -= t\n},\nDataStream.prototype.writeInt32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Int32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt32(t[i], e)\n},\nDataStream.prototype.writeInt16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Int16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt16(t[i], e)\n},\nDataStream.prototype.writeInt8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Int8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeInt8(t[e])\n},\nDataStream.prototype.writeUint32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Uint32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint32(t[i], e)\n},\nDataStream.prototype.writeUint16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Uint16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint16(t[i], e)\n},\nDataStream.prototype.writeUint8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Uint8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeUint8(t[e])\n},\nDataStream.prototype.writeFloat64Array = function(t, e) {\n\tif (this._realloc(8 * t.length), t instanceof Float64Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat64Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat64(t[i], e)\n},\nDataStream.prototype.writeFloat32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Float32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat32(t[i], e)\n},\nDataStream.prototype.writeInt32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setInt32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeInt16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setInt16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeInt8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setInt8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeUint32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setUint32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeUint16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setUint16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeUint8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setUint8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeFloat32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setFloat32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeFloat64 = function(t, e) {\n\tthis._realloc(8),\n\tthis._dataView.setFloat64(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 8\n},\nDataStream.prototype.writeUCS2String = function(t, e, i) {\n\tnull == i && (i = t.length);\n\tfor (var r = 0; r < t.length && r < i; r++) this.writeUint16(t.charCodeAt(r), e);\n\tfor (; r < i; r++) this.writeUint16(0)\n},\nDataStream.prototype.writeString = function(t, e, i) {\n\tvar r = 0;\n\tif (null == e || "ASCII" == e) if (null != i) {\n\t\tfor (var s = Math.min(t.length, i), r = 0; r < s; r++) this.writeUint8(t.charCodeAt(r));\n\t\tfor (; r < i; r++) this.writeUint8(0)\n\t} else for (r = 0; r < t.length; r++) this.writeUint8(t.charCodeAt(r));\n\telse this.writeUint8Array(new TextEncoder(e).encode(t.substring(0, i)))\n},\nDataStream.prototype.writeCString = function(t, e) {\n\tvar i = 0;\n\tif (null != e) {\n\t\tfor (var r = Math.min(t.length, e), i = 0; i < r; i++) this.writeUint8(t.charCodeAt(i));\n\t\tfor (; i < e; i++) this.writeUint8(0)\n\t} else {\n\t\tfor (i = 0; i < t.length; i++) this.writeUint8(t.charCodeAt(i));\n\t\tthis.writeUint8(0)\n\t}\n},\nDataStream.prototype.writeStruct = function(t, e) {\n\tfor (var i = 0; i < t.length; i += 2) {\n\t\tvar r = t[i + 1];\n\t\tthis.writeType(r, e[t[i]], e)\n\t}\n},\nDataStream.prototype.writeType = function(t, e, i) {\n\tvar r;\n\tif ("function" == typeof t) return t(this, e);\n\tif ("object" == typeof t && !(t instanceof Array)) return t.set(this, e, i);\n\tvar s = null,\n\ta = "ASCII",\n\ti = this.position;\n\tswitch ("string" == typeof t && /:/.test(t) && (t = (r = t.split(":"))[0], s = parseInt(r[1])), "string" == typeof t && /,/.test(t) && (t = (r = t.split(","))[0], a = parseInt(r[1])), t) {\n\tcase "uint8":\n\t\tthis.writeUint8(e);\n\t\tbreak;\n\tcase "int8":\n\t\tthis.writeInt8(e);\n\t\tbreak;\n\tcase "uint16":\n\t\tthis.writeUint16(e, this.endianness);\n\t\tbreak;\n\tcase "int16":\n\t\tthis.writeInt16(e, this.endianness);\n\t\tbreak;\n\tcase "uint32":\n\t\tthis.writeUint32(e, this.endianness);\n\t\tbreak;\n\tcase "int32":\n\t\tthis.writeInt32(e, this.endianness);\n\t\tbreak;\n\tcase "float32":\n\t\tthis.writeFloat32(e, this.endianness);\n\t\tbreak;\n\tcase "float64":\n\t\tthis.writeFloat64(e, this.endianness);\n\t\tbreak;\n\tcase "uint16be":\n\t\tthis.writeUint16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int16be":\n\t\tthis.writeInt16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint32be":\n\t\tthis.writeUint32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int32be":\n\t\tthis.writeInt32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float32be":\n\t\tthis.writeFloat32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float64be":\n\t\tthis.writeFloat64(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint16le":\n\t\tthis.writeUint16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int16le":\n\t\tthis.writeInt16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "uint32le":\n\t\tthis.writeUint32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int32le":\n\t\tthis.writeInt32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float32le":\n\t\tthis.writeFloat32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float64le":\n\t\tthis.writeFloat64(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "cstring":\n\t\tthis.writeCString(e, s);\n\t\tbreak;\n\tcase "string":\n\t\tthis.writeString(e, a, s);\n\t\tbreak;\n\tcase "u16string":\n\t\tthis.writeUCS2String(e, this.endianness, s);\n\t\tbreak;\n\tcase "u16stringle":\n\t\tthis.writeUCS2String(e, DataStream.LITTLE_ENDIAN, s);\n\t\tbreak;\n\tcase "u16stringbe":\n\t\tthis.writeUCS2String(e, DataStream.BIG_ENDIAN, s);\n\t\tbreak;\n\tdefault:\n\t\tif (3 == t.length) {\n\t\t\tfor (var n = t[1], o = 0; o < e.length; o++) this.writeType(n, e[o]);\n\t\t\tbreak\n\t\t}\n\t\tthis.writeStruct(t, e)\n\t}\n\tnull != s && (this.position = i, this._realloc(s), this.position = i + s)\n},\nDataStream.prototype.writeUint64 = function(t) {\n\tvar e = Math.floor(t / MAX_SIZE);\n\tthis.writeUint32(e),\n\tthis.writeUint32(4294967295 & t)\n},\nDataStream.prototype.writeUint24 = function(t) {\n\tthis.writeUint8((16711680 & t) >> 16),\n\tthis.writeUint8((65280 & t) >> 8),\n\tthis.writeUint8(255 & t)\n},\nDataStream.prototype.adjustUint32 = function(t, e) {\n\tvar i = this.position;\n\tthis.seek(t),\n\tthis.writeUint32(e),\n\tthis.seek(i)\n},\nDataStream.prototype.mapInt32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Int32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapInt16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Int16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapInt8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Int8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.mapUint32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Uint32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapUint16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Uint16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapFloat64Array = function(t, e) {\n\tthis._realloc(8 * t);\n\tvar i = new Float64Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 8 * t,\n\ti\n},\nDataStream.prototype.mapFloat32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Float32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n};\nvar MultiBufferStream = function(t) {\n\tthis.buffers = [],\n\tthis.bufferIndex = -1,\n\tt && (this.insertBuffer(t), this.bufferIndex = 0)\n};\nMultiBufferStream.prototype = new DataStream(new ArrayBuffer, 0, DataStream.BIG_ENDIAN),\nMultiBufferStream.prototype.initialized = function() {\n\tvar t;\n\treturn - 1 < this.bufferIndex || (0 < this.buffers.length ? 0 === (t = this.buffers[0]).fileStart ? (this.buffer = t, this.bufferIndex = 0, Log.debug("MultiBufferStream", "Stream ready for parsing"), !0) : (Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0"), this.logBufferLevel(), !1) : (Log.warn("MultiBufferStream", "No buffer to start parsing from"), this.logBufferLevel(), !1))\n},\nArrayBuffer.concat = function(t, e) {\n\tLog.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (t.byteLength + e.byteLength));\n\tvar i = new Uint8Array(t.byteLength + e.byteLength);\n\treturn i.set(new Uint8Array(t), 0),\n\ti.set(new Uint8Array(e), t.byteLength),\n\ti.buffer\n},\nMultiBufferStream.prototype.reduceBuffer = function(t, e, i) {\n\tvar r = new Uint8Array(i);\n\treturn r.set(new Uint8Array(t, e, i)),\n\tr.buffer.fileStart = t.fileStart + e,\n\tr.buffer.usedBytes = 0,\n\tr.buffer\n},\nMultiBufferStream.prototype.insertBuffer = function(t) {\n\tfor (var e = !0,\n\ti = 0; i < this.buffers.length; i++) {\n\t\tvar r = this.buffers[i];\n\t\tif (t.fileStart <= r.fileStart) {\n\t\t\tif (t.fileStart === r.fileStart) {\n\t\t\t\tif (t.byteLength > r.byteLength) {\n\t\t\t\t\tthis.buffers.splice(i, 1),\n\t\t\t\t\ti--;\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tLog.warn("MultiBufferStream", "Buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ") already appended, ignoring")\n\t\t\t} else t.fileStart + t.byteLength <= r.fileStart || (t = this.reduceBuffer(t, 0, r.fileStart - t.fileStart)),\n\t\t\tLog.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"),\n\t\t\tthis.buffers.splice(i, 0, t),\n\t\t\t0 === i && (this.buffer = t);\n\t\t\te = !1;\n\t\t\tbreak\n\t\t}\n\t\tif (t.fileStart < r.fileStart + r.byteLength) {\n\t\t\tvar s = r.fileStart + r.byteLength - t.fileStart,\n\t\t\tr = t.byteLength - s;\n\t\t\tif (! (0 < r)) {\n\t\t\t\te = !1;\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt = this.reduceBuffer(t, s, r)\n\t\t}\n\t}\n\te && (Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"), this.buffers.push(t), 0 === i && (this.buffer = t))\n},\nMultiBufferStream.prototype.logBufferLevel = function(t) {\n\tfor (var e, i, r = [], s = "", a = 0, n = 0, o = 0; o < this.buffers.length; o++) e = this.buffers[o],\n\t0 === o ? (i = {},\n\tr.push(i), i.start = e.fileStart, i.end = e.fileStart + e.byteLength, s += "[" + i.start + "-") : i.end === e.fileStart ? i.end = e.fileStart + e.byteLength: ((i = {}).start = e.fileStart, s += r[r.length - 1].end - 1 + "], [" + i.start + "-", i.end = e.fileStart + e.byteLength, r.push(i)),\n\ta += e.usedBytes,\n\tn += e.byteLength;\n\t0 < r.length && (s += i.end - 1 + "]");\n\tt = t ? Log.info: Log.debug;\n\t0 === this.buffers.length ? t("MultiBufferStream", "No more buffer in memory") : t("MultiBufferStream", this.buffers.length + " stored buffer(s) (" + a + "/" + n + " bytes), continuous ranges: " + s)\n},\nMultiBufferStream.prototype.cleanBuffers = function() {\n\tfor (var t, e = 0; e < this.buffers.length; e++)(t = this.buffers[e]).usedBytes === t.byteLength && (Log.debug("MultiBufferStream", "Removing buffer #" + e), this.buffers.splice(e, 1), e--)\n},\nMultiBufferStream.prototype.mergeNextBuffer = function() {\n\tvar t;\n\tif (this.bufferIndex + 1 < this.buffers.length) {\n\t\tif ((t = this.buffers[this.bufferIndex + 1]).fileStart !== this.buffer.fileStart + this.buffer.byteLength) return ! 1;\n\t\tvar e = this.buffer.byteLength,\n\t\ti = this.buffer.usedBytes,\n\t\tr = this.buffer.fileStart;\n\t\treturn this.buffers[this.bufferIndex] = ArrayBuffer.concat(this.buffer, t),\n\t\tthis.buffer = this.buffers[this.bufferIndex],\n\t\tthis.buffers.splice(this.bufferIndex + 1, 1),\n\t\tthis.buffer.usedBytes = i,\n\t\tthis.buffer.fileStart = r,\n\t\tLog.debug("ISOFile", "Concatenating buffer for box parsing (length: " + e + "->" + this.buffer.byteLength + ")"),\n\t\t!0\n\t}\n\treturn ! 1\n},\nMultiBufferStream.prototype.findPosition = function(t, e, i) {\n\tfor (var r = null,\n\ts = -1,\n\ta = !0 === t ? 0 : this.bufferIndex; a < this.buffers.length && (r = this.buffers[a]).fileStart <= e;) s = a,\n\ti && (r.fileStart + r.byteLength <= e ? r.usedBytes = r.byteLength: r.usedBytes = e - r.fileStart, this.logBufferLevel()),\n\ta++;\n\treturn - 1 !== s && (r = this.buffers[s]).fileStart + r.byteLength >= e ? (Log.debug("MultiBufferStream", "Found position in existing buffer #" + s), s) : -1\n},\nMultiBufferStream.prototype.findEndContiguousBuf = function(t) {\n\tvar e, i, t = void 0 !== t ? t: this.bufferIndex,\n\tr = this.buffers[t];\n\tif (this.buffers.length > t + 1) for (e = t + 1; e < this.buffers.length && (i = this.buffers[e]).fileStart === r.fileStart + r.byteLength; e++) r = i;\n\treturn r.fileStart + r.byteLength\n},\nMultiBufferStream.prototype.getEndFilePositionAfter = function(t) {\n\tvar e = this.findPosition(!0, t, !1);\n\treturn - 1 !== e ? this.findEndContiguousBuf(e) : t\n},\nMultiBufferStream.prototype.addUsedBytes = function(t) {\n\tthis.buffer.usedBytes += t,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.setAllUsedBytes = function() {\n\tthis.buffer.usedBytes = this.buffer.byteLength,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.seek = function(t, e, i) {\n\ti = this.findPosition(e, t, i);\n\treturn - 1 !== i ? (this.buffer = this.buffers[i], this.bufferIndex = i, this.position = t - this.buffer.fileStart, Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position), !0) : (Log.debug("MultiBufferStream", "Position " + t + " not found in buffered data"), !1)\n},\nMultiBufferStream.prototype.getPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.position\n},\nMultiBufferStream.prototype.getLength = function() {\n\treturn this.byteLength\n},\nMultiBufferStream.prototype.getEndPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.byteLength\n},\n"undefined" != typeof exports && (exports.MultiBufferStream = MultiBufferStream);\nvar MPEG4DescriptorParser = function() {\n\tvar s = [];\n\ts[3] = "ES_Descriptor",\n\ts[4] = "DecoderConfigDescriptor",\n\ts[5] = "DecoderSpecificInfo",\n\ts[6] = "SLConfigDescriptor",\n\tthis.getDescriptorName = function(t) {\n\t\treturn s[t]\n\t};\n\tvar r = this,\n\ta = {};\n\treturn this.parseOneDescriptor = function(t) {\n\t\tvar e, i = 0,\n\t\tr = t.readUint8();\n\t\tfor (e = t.readUint8(), 0; 128 & e;) i = (i << 7) + (127 & e),\n\t\te = t.readUint8(),\n\t\t0;\n\t\treturn i = (i << 7) + (127 & e),\n\t\tLog.debug("MPEG4DescriptorParser", "Found " + (s[r] || "Descriptor " + r) + ", size " + i + " at position " + t.getPosition()),\n\t\t(r = new(s[r] ? a[s[r]] : a.Descriptor)(i)).parse(t),\n\t\tr\n\t},\n\ta.Descriptor = function(t, e) {\n\t\tthis.tag = t,\n\t\tthis.size = e,\n\t\tthis.descs = []\n\t},\n\ta.Descriptor.prototype.parse = function(t) {\n\t\tthis.data = t.readUint8Array(this.size)\n\t},\n\ta.Descriptor.prototype.findDescriptor = function(t) {\n\t\tfor (var e = 0; e < this.descs.length; e++) if (this.descs[e].tag == t) return this.descs[e];\n\t\treturn null\n\t},\n\ta.Descriptor.prototype.parseRemainingDescriptors = function(t) {\n\t\tfor (var e = t.position; t.position < e + this.size;) {\n\t\t\tvar i = r.parseOneDescriptor(t);\n\t\t\tthis.descs.push(i)\n\t\t}\n\t},\n\ta.ES_Descriptor = function(t) {\n\t\ta.Descriptor.call(this, 3, t)\n\t},\n\ta.ES_Descriptor.prototype = new a.Descriptor,\n\ta.ES_Descriptor.prototype.parse = function(t) {\n\t\tvar e;\n\t\tthis.ES_ID = t.readUint16(),\n\t\tthis.flags = t.readUint8(),\n\t\tthis.size -= 3,\n\t\t128 & this.flags ? (this.dependsOn_ES_ID = t.readUint16(), this.size -= 2) : this.dependsOn_ES_ID = 0,\n\t\t64 & this.flags ? (e = t.readUint8(), this.URL = t.readString(e), this.size -= e + 1) : this.URL = "",\n\t\t32 & this.flags ? (this.OCR_ES_ID = t.readUint16(), this.size -= 2) : this.OCR_ES_ID = 0,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.ES_Descriptor.prototype.getOTI = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\treturn e ? e.oti: 0\n\t},\n\ta.ES_Descriptor.prototype.getAudioConfig = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\tif (!e) return null;\n\t\tvar i = e.findDescriptor(5);\n\t\tif (i && i.data) {\n\t\t\te = (248 & i.data[0]) >> 3;\n\t\t\treturn 31 === e && 2 <= i.data.length && (e = 32 + ((7 & i.data[0]) << 3) + ((224 & i.data[1]) >> 5)),\n\t\t\te\n\t\t}\n\t\treturn null\n\t},\n\ta.DecoderConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 4, t)\n\t},\n\ta.DecoderConfigDescriptor.prototype = new a.Descriptor,\n\ta.DecoderConfigDescriptor.prototype.parse = function(t) {\n\t\tthis.oti = t.readUint8(),\n\t\tthis.streamType = t.readUint8(),\n\t\tthis.upStream = 0 != (this.streamType >> 1 & 1),\n\t\tthis.streamType = this.streamType >>> 2,\n\t\tthis.bufferSize = t.readUint24(),\n\t\tthis.maxBitrate = t.readUint32(),\n\t\tthis.avgBitrate = t.readUint32(),\n\t\tthis.size -= 13,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.DecoderSpecificInfo = function(t) {\n\t\ta.Descriptor.call(this, 5, t)\n\t},\n\ta.DecoderSpecificInfo.prototype = new a.Descriptor,\n\ta.SLConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 6, t)\n\t},\n\ta.SLConfigDescriptor.prototype = new a.Descriptor,\n\tthis\n};\n"undefined" != typeof exports && (exports.MPEG4DescriptorParser = MPEG4DescriptorParser);\nvar BoxParser = {\n\tERR_INVALID_DATA: -1,\n\tERR_NOT_ENOUGH_DATA: 0,\n\tOK: 1,\n\tBASIC_BOXES: [{\n\t\ttype: "mdat",\n\t\tname: "MediaDataBox"\n\t},\n\t{\n\t\ttype: "idat",\n\t\tname: "ItemDataBox"\n\t},\n\t{\n\t\ttype: "free",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "skip",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t},\n\t{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}],\n\tFULL_BOXES: [{\n\t\ttype: "hmhd",\n\t\tname: "HintMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "nmhd",\n\t\tname: "NullMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "iods",\n\t\tname: "ObjectDescriptorBox"\n\t},\n\t{\n\t\ttype: "xml ",\n\t\tname: "XMLBox"\n\t},\n\t{\n\t\ttype: "bxml",\n\t\tname: "BinaryXMLBox"\n\t},\n\t{\n\t\ttype: "ipro",\n\t\tname: "ItemProtectionBox"\n\t},\n\t{\n\t\ttype: "mere",\n\t\tname: "MetaboxRelationBox"\n\t}],\n\tCONTAINER_BOXES: [[{\n\t\ttype: "moov",\n\t\tname: "CompressedMovieBox"\n\t},\n\t["trak", "pssh"]], [{\n\t\ttype: "trak",\n\t\tname: "TrackBox"\n\t}], [{\n\t\ttype: "edts",\n\t\tname: "EditBox"\n\t}], [{\n\t\ttype: "mdia",\n\t\tname: "MediaBox"\n\t}], [{\n\t\ttype: "minf",\n\t\tname: "MediaInformationBox"\n\t}], [{\n\t\ttype: "dinf",\n\t\tname: "DataInformationBox"\n\t}], [{\n\t\ttype: "stbl",\n\t\tname: "SampleTableBox"\n\t},\n\t["sgpd", "sbgp"]], [{\n\t\ttype: "mvex",\n\t\tname: "MovieExtendsBox"\n\t},\n\t["trex"]], [{\n\t\ttype: "moof",\n\t\tname: "CompressedMovieFragmentBox"\n\t},\n\t["traf"]], [{\n\t\ttype: "traf",\n\t\tname: "TrackFragmentBox"\n\t},\n\t["trun", "sgpd", "sbgp"]], [{\n\t\ttype: "vttc",\n\t\tname: "VTTCueBox"\n\t}], [{\n\t\ttype: "tref",\n\t\tname: "TrackReferenceBox"\n\t}], [{\n\t\ttype: "iref",\n\t\tname: "ItemReferenceBox"\n\t}], [{\n\t\ttype: "mfra",\n\t\tname: "MovieFragmentRandomAccessBox"\n\t},\n\t["tfra"]], [{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t}], [{\n\t\ttype: "hnti",\n\t\tname: "trackhintinformation"\n\t}], [{\n\t\ttype: "hinf",\n\t\tname: "hintstatisticsbox"\n\t}], [{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}], [{\n\t\ttype: "strd",\n\t\tname: "SubTrackDefinitionBox"\n\t}], [{\n\t\ttype: "sinf",\n\t\tname: "ProtectionSchemeInfoBox"\n\t}], [{\n\t\ttype: "rinf",\n\t\tname: "RestrictedSchemeInfoBox"\n\t}], [{\n\t\ttype: "schi",\n\t\tname: "SchemeInformationBox"\n\t}], [{\n\t\ttype: "trgr",\n\t\tname: "TrackGroupBox"\n\t}], [{\n\t\ttype: "udta",\n\t\tname: "UserDataBox"\n\t},\n\t["kind"]], [{\n\t\ttype: "iprp",\n\t\tname: "ItemPropertiesBox"\n\t},\n\t["ipma"]], [{\n\t\ttype: "ipco",\n\t\tname: "ItemPropertyContainerBox"\n\t}], [{\n\t\ttype: "grpl",\n\t\tname: "GroupsListBox"\n\t}], [{\n\t\ttype: "j2kH",\n\t\tname: "J2KHeaderInfoBox"\n\t}], [{\n\t\ttype: "etyp",\n\t\tname: "ExtendedTypeBox"\n\t},\n\t["tyco"]]],\n\tboxCodes: [],\n\tfullBoxCodes: [],\n\tcontainerBoxCodes: [],\n\tsampleEntryCodes: {},\n\tsampleGroupEntryCodes: [],\n\ttrackGroupTypes: [],\n\tUUIDBoxes: {},\n\tUUIDs: [],\n\tinitialize: function() {\n\t\tBoxParser.FullBox.prototype = new BoxParser.Box,\n\t\tBoxParser.ContainerBox.prototype = new BoxParser.Box,\n\t\tBoxParser.SampleEntry.prototype = new BoxParser.Box,\n\t\tBoxParser.TrackGroupTypeBox.prototype = new BoxParser.FullBox,\n\t\tBoxParser.BASIC_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.FULL_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createFullBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.CONTAINER_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createContainerBoxCtor(t[0].type, t[0].name, null, t[1])\n\t\t})\n\t},\n\tBox: function(t, e, i, r) {\n\t\tthis.type = t,\n\t\tthis.box_name = i,\n\t\tthis.size = e,\n\t\tthis.uuid = r\n\t},\n\tFullBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.flags = 0,\n\t\tthis.version = 0\n\t},\n\tContainerBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.boxes = []\n\t},\n\tSampleEntry: function(t, e, i, r) {\n\t\tBoxParser.ContainerBox.call(this, t, e),\n\t\tthis.hdr_size = i,\n\t\tthis.start = r\n\t},\n\tSampleGroupEntry: function(t) {\n\t\tthis.grouping_type = t\n\t},\n\tTrackGroupTypeBox: function(t, e) {\n\t\tBoxParser.FullBox.call(this, t, e)\n\t},\n\tcreateBoxCtor: function(e, i, t) {\n\t\tBoxParser.boxCodes.push(e),\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.Box.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.Box,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateFullBoxCtor: function(e, i, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.FullBox.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\t\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\tr && r.call(this, t)\n\t\t}\n\t},\n\taddSubBoxArrays: function(t) {\n\t\tif (t) for (var e = (this.subBoxNames = t).length, i = 0; i < e; i++) this[t[i] + "s"] = []\n\t},\n\tcreateContainerBoxCtor: function(e, i, t, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.ContainerBox.call(this, e, t, i),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.ContainerBox,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateMediaSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.sampleEntryCodes[t] = [],\n\t\tBoxParser[t + "SampleEntry"] = function(t, e) {\n\t\t\tBoxParser.SampleEntry.call(this, t, e),\n\t\t\tBoxParser.addSubBoxArrays.call(this, i)\n\t\t},\n\t\tBoxParser[t + "SampleEntry"].prototype = new BoxParser.SampleEntry,\n\t\te && (BoxParser[t + "SampleEntry"].prototype.parse = e)\n\t},\n\tcreateSampleEntryCtor: function(e, i, t, r) {\n\t\tBoxParser.sampleEntryCodes[e].push(i),\n\t\tBoxParser[i + "SampleEntry"] = function(t) {\n\t\t\tBoxParser[e + "SampleEntry"].call(this, i, t),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[i + "SampleEntry"].prototype = new BoxParser[e + "SampleEntry"],\n\t\tt && (BoxParser[i + "SampleEntry"].prototype.parse = t)\n\t},\n\tcreateEncryptedSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.createSampleEntryCtor.call(this, t, e, i, ["sinf"])\n\t},\n\tcreateSampleGroupCtor: function(e, t) {\n\t\tBoxParser[e + "SampleGroupEntry"] = function(t) {\n\t\t\tBoxParser.SampleGroupEntry.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "SampleGroupEntry"].prototype = new BoxParser.SampleGroupEntry,\n\t\tt && (BoxParser[e + "SampleGroupEntry"].prototype.parse = t)\n\t},\n\tcreateTrackGroupCtor: function(e, t) {\n\t\tBoxParser[e + "TrackGroupTypeBox"] = function(t) {\n\t\t\tBoxParser.TrackGroupTypeBox.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "TrackGroupTypeBox"].prototype = new BoxParser.TrackGroupTypeBox,\n\t\tt && (BoxParser[e + "TrackGroupTypeBox"].prototype.parse = t)\n\t},\n\tcreateUUIDBox: function(e, i, r, s, a) {\n\t\tBoxParser.UUIDs.push(e),\n\t\tBoxParser.UUIDBoxes[e] = function(t) { (r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box).call(this, "uuid", t, i, e)\n\t\t},\n\t\tBoxParser.UUIDBoxes[e].prototype = new(r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box),\n\t\ta && (BoxParser.UUIDBoxes[e].prototype.parse = r ?\n\t\tfunction(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\ta && a.call(this, t)\n\t\t}: a)\n\t}\n};\nfunction printPS(t) {\n\tvar e = "<table class=\'inner-table\'>";\n\te += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",\n\te += "<tbody>";\n\tfor (var i = 0; i < t.length; i++) {\n\t\tvar r = t[i];\n\t\te += "<tr>",\n\t\te += "<td>" + r.length + "</td>",\n\t\te += "<td>",\n\t\te += r.nalu.reduce(function(t, e) {\n\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t},\n\t\t"0x"),\n\t\te += "</td></tr>"\n\t}\n\treturn e += "</tbody></table>"\n}\nfunction ColorPoint(t, e) {\n\tthis.x = t,\n\tthis.y = e\n}\nfunction Pixel(t, e) {\n\tthis.bad_pixel_row = t,\n\tthis.bad_pixel_column = e\n}\nBoxParser.initialize(),\nBoxParser.TKHD_FLAG_ENABLED = 1,\nBoxParser.TKHD_FLAG_IN_MOVIE = 2,\nBoxParser.TKHD_FLAG_IN_PREVIEW = 4,\nBoxParser.TFHD_FLAG_BASE_DATA_OFFSET = 1,\nBoxParser.TFHD_FLAG_SAMPLE_DESC = 2,\nBoxParser.TFHD_FLAG_SAMPLE_DUR = 8,\nBoxParser.TFHD_FLAG_SAMPLE_SIZE = 16,\nBoxParser.TFHD_FLAG_SAMPLE_FLAGS = 32,\nBoxParser.TFHD_FLAG_DUR_EMPTY = 65536,\nBoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072,\nBoxParser.TRUN_FLAGS_DATA_OFFSET = 1,\nBoxParser.TRUN_FLAGS_FIRST_FLAG = 4,\nBoxParser.TRUN_FLAGS_DURATION = 256,\nBoxParser.TRUN_FLAGS_SIZE = 512,\nBoxParser.TRUN_FLAGS_FLAGS = 1024,\nBoxParser.TRUN_FLAGS_CTS_OFFSET = 2048,\nBoxParser.Box.prototype.add = function(t) {\n\treturn this.addBox(new BoxParser[t + "Box"])\n},\nBoxParser.Box.prototype.addBox = function(t) {\n\treturn this.boxes.push(t),\n\tthis[t.type + "s"] ? this[t.type + "s"].push(t) : this[t.type] = t,\n\tt\n},\nBoxParser.Box.prototype.set = function(t, e) {\n\treturn this[t] = e,\n\tthis\n},\nBoxParser.Box.prototype.addEntry = function(t, e) {\n\te = e || "entries";\n\treturn this[e] || (this[e] = []),\n\tthis[e].push(t),\n\tthis\n},\n"undefined" != typeof exports && (exports.BoxParser = BoxParser),\nBoxParser.parseUUID = function(t) {\n\treturn BoxParser.parseHex16(t)\n},\nBoxParser.parseHex16 = function(t) {\n\tfor (var e = "",\n\ti = 0; i < 16; i++) {\n\t\tvar r = t.readUint8().toString(16);\n\t\te += 1 === r.length ? "0" + r: r\n\t}\n\treturn e\n},\nBoxParser.parseOneBox = function(t, e, i) {\n\tvar r, s, a = t.getPosition(),\n\tn = 0;\n\tif (t.getEndPosition() - a < 8) return Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tif (i && i < 8) return Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tvar o = t.readUint32(),\n\th = t.readString(4),\n\td = h;\n\tif (Log.debug("BoxParser", "Found box of type \'" + h + "\' and size " + o + " at position " + a), n = 8, "uuid" == h) {\n\t\tif (t.getEndPosition() - t.getPosition() < 16 || i - n < 16) return t.seek(a),\n\t\tLog.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box"),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\tn += 16,\n\t\td = s = BoxParser.parseUUID(t)\n\t}\n\tif (1 == o) {\n\t\tif (t.getEndPosition() - t.getPosition() < 8 || i && i - n < 8) return t.seek(a),\n\t\tLog.warn("BoxParser", \'Not enough data in stream to parse the extended size of the "\' + h + \'" box\'),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\to = t.readUint64(),\n\t\tn += 8\n\t} else if (0 === o) if (i) o = i;\n\telse if ("mdat" !== h) return Log.error("BoxParser", "Unlimited box size not supported for type: \'" + h + "\'"),\n\tr = new BoxParser.Box(h, o),\n\t{\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t};\n\treturn 0 !== o && o < n ? (Log.error("BoxParser", "Box of type " + h + " has an invalid size " + o + " (too small to be a box)"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && i && i < o ? (Log.error("BoxParser", "Box of type \'" + h + "\' has a size " + o + " greater than its container size " + i), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && a + o > t.getEndPosition() ? (t.seek(a), Log.info("BoxParser", "Not enough data in stream to parse the entire \'" + h + "\' box"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : e ? {\n\t\tcode: BoxParser.OK,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}: (BoxParser[h + "Box"] ? r = new BoxParser[h + "Box"](o) : "uuid" !== h ? (Log.warn("BoxParser", "Unknown box type: \'" + h + "\'"), (r = new BoxParser.Box(h, o)).has_unparsed_data = !0) : BoxParser.UUIDBoxes[s] ? r = new BoxParser.UUIDBoxes[s](o) : (Log.warn("BoxParser", "Unknown uuid type: \'" + s + "\'"), (r = new BoxParser.Box(h, o)).uuid = s, r.has_unparsed_data = !0), r.hdr_size = n, r.start = a, r.write === BoxParser.Box.prototype.write && "mdat" !== r.type && (Log.info("BoxParser", "\'" + d + "\' box writing not yet implemented, keeping unparsed data in memory for later write"), r.parseDataAndRewind(t)), r.parse(t), (a = t.getPosition() - (r.start + r.size)) < 0 ? (Log.warn("BoxParser", "Parsing of box \'" + d + "\' did not read the entire indicated box data size (missing " + -a + " bytes), seeking forward"), t.seek(r.start + r.size)) : 0 < a && (Log.error("BoxParser", "Parsing of box \'" + d + "\' read " + a + " more bytes than the indicated box data size, seeking backwards"), 0 !== r.size && t.seek(r.start + r.size)), {\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t})\n},\nBoxParser.Box.prototype.parse = function(t) {\n\t"mdat" != this.type ? this.data = t.readUint8Array(this.size - this.hdr_size) : 0 === this.size ? t.seek(t.getEndPosition()) : t.seek(this.start + this.size)\n},\nBoxParser.Box.prototype.parseDataAndRewind = function(t) {\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseDataAndRewind = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 4,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseFullHeader = function(t) {\n\tthis.version = t.readUint8(),\n\tthis.flags = t.readUint24(),\n\tthis.hdr_size += 4\n},\nBoxParser.FullBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.ContainerBox.prototype.parse = function(t) {\n\tfor (; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tvar e, i = e.box;\n\t\tthis.boxes.push(i),\n\t\tthis.subBoxNames && -1 != this.subBoxNames.indexOf(i.type) ? this[this.subBoxNames[this.subBoxNames.indexOf(i.type)] + "s"].push(i) : this[e = "uuid" !== i.type ? i.type: i.uuid] ? Log.warn("Box of type " + e + " already stored in field of this type") : this[e] = i\n\t}\n},\nBoxParser.Box.prototype.parseLanguage = function(t) {\n\tthis.language = t.readUint16();\n\tt = [];\n\tt[0] = this.language >> 10 & 31,\n\tt[1] = this.language >> 5 & 31,\n\tt[2] = 31 & this.language,\n\tthis.languageString = String.fromCharCode(t[0] + 96, t[1] + 96, t[2] + 96)\n},\nBoxParser.SAMPLE_ENTRY_TYPE_VISUAL = "Visual",\nBoxParser.SAMPLE_ENTRY_TYPE_AUDIO = "Audio",\nBoxParser.SAMPLE_ENTRY_TYPE_HINT = "Hint",\nBoxParser.SAMPLE_ENTRY_TYPE_METADATA = "Metadata",\nBoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE = "Subtitle",\nBoxParser.SAMPLE_ENTRY_TYPE_SYSTEM = "System",\nBoxParser.SAMPLE_ENTRY_TYPE_TEXT = "Text",\nBoxParser.SampleEntry.prototype.parseHeader = function(t) {\n\tt.readUint8Array(6),\n\tthis.data_reference_index = t.readUint16(),\n\tthis.hdr_size += 8\n},\nBoxParser.SampleEntry.prototype.parse = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.SampleEntry.prototype.parseDataAndRewind = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 8,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.SampleEntry.prototype.parseFooter = function(t) {\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n},\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_HINT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL,\nfunction(t) {\n\tvar e;\n\tthis.parseHeader(t),\n\tt.readUint16(),\n\tt.readUint16(),\n\tt.readUint32Array(3),\n\tthis.width = t.readUint16(),\n\tthis.height = t.readUint16(),\n\tthis.horizresolution = t.readUint32(),\n\tthis.vertresolution = t.readUint32(),\n\tt.readUint32(),\n\tthis.frame_count = t.readUint16(),\n\te = Math.min(31, t.readUint8()),\n\tthis.compressorname = t.readString(e),\n\te < 31 && t.readString(31 - e),\n\tthis.depth = t.readUint16(),\n\tt.readUint16(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO,\nfunction(t) {\n\tthis.parseHeader(t),\n\tt.readUint32Array(2),\n\tthis.channel_count = t.readUint16(),\n\tthis.samplesize = t.readUint16(),\n\tt.readUint16(),\n\tt.readUint16(),\n\tthis.samplerate = t.readUint32() / 65536,\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "av01"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dav1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hev1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvt1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "lhe1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvh1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvhe"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvi1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvs1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvcN"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp08"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp09"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avs3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "j2ki"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjp2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjpg"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "uncv"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mp4a"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ec-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "Opus"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "fLaC"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "encv"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "enca"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "encu"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM, "encs"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT, "enct"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "encm"),\nBoxParser.createBoxCtor("a1lx", "AV1LayeredImageIndexingProperty",\nfunction(t) {\n\tvar e = 16 * (1 + (1 & (1 & t.readUint8())));\n\tthis.layer_size = [];\n\tfor (var i = 0; i < 3; i++) this.layer_size[i] = 16 == e ? t.readUint16() : t.readUint32()\n}),\nBoxParser.createBoxCtor("a1op", "OperatingPointSelectorProperty",\nfunction(t) {\n\tthis.op_index = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("auxC", "AuxiliaryTypeProperty",\nfunction(t) {\n\tthis.aux_type = t.readCString();\n\tvar e = this.size - this.hdr_size - (this.aux_type.length + 1);\n\tthis.aux_subtype = t.readUint8Array(e)\n}),\nBoxParser.createBoxCtor("av1C", "AV1CodecConfigurationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tif (1 == (e >> 7 & 1)) if (this.version = 127 & e, 1 === this.version) if (e = t.readUint8(), this.seq_profile = e >> 5 & 7, this.seq_level_idx_0 = 31 & e, e = t.readUint8(), this.seq_tier_0 = e >> 7 & 1, this.high_bitdepth = e >> 6 & 1, this.twelve_bit = e >> 5 & 1, this.monochrome = e >> 4 & 1, this.chroma_subsampling_x = e >> 3 & 1, this.chroma_subsampling_y = e >> 2 & 1, this.chroma_sample_position = 3 & e, e = t.readUint8(), this.reserved_1 = e >> 5 & 7, 0 === this.reserved_1) {\n\t\tif (this.initial_presentation_delay_present = e >> 4 & 1, 1 === this.initial_presentation_delay_present) this.initial_presentation_delay_minus_one = 15 & e;\n\t\telse if (this.reserved_2 = 15 & e, 0 !== this.reserved_2) return void Log.error("av1C reserved_2 parsing problem");\n\t\te = this.size - this.hdr_size - 4;\n\t\tthis.configOBUs = t.readUint8Array(e)\n\t} else Log.error("av1C reserved_1 parsing problem");\n\telse Log.error("av1C version " + this.version + " not supported");\n\telse Log.error("av1C marker problem")\n}),\nBoxParser.createBoxCtor("avcC", "AVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (this.configurationVersion = t.readUint8(), this.AVCProfileIndication = t.readUint8(), this.profile_compatibility = t.readUint8(), this.AVCLevelIndication = t.readUint8(), this.lengthSizeMinusOne = 3 & t.readUint8(), this.nb_SPS_nalus = 31 & t.readUint8(), i = this.size - this.hdr_size - 6, this.SPS = [], this.SPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_SPS_nalus; e++) this.SPS[e] = {},\n\tthis.SPS[e].length = t.readUint16(),\n\tthis.SPS[e].nalu = t.readUint8Array(this.SPS[e].length),\n\ti -= 2 + this.SPS[e].length;\n\tfor (this.nb_PPS_nalus = t.readUint8(), i--, this.PPS = [], this.PPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_PPS_nalus; e++) this.PPS[e] = {},\n\tthis.PPS[e].length = t.readUint16(),\n\tthis.PPS[e].nalu = t.readUint8Array(this.PPS[e].length),\n\ti -= 2 + this.PPS[e].length;\n\t0 < i && (this.ext = t.readUint8Array(i))\n}),\nBoxParser.createBoxCtor("btrt", "BitRateBox",\nfunction(t) {\n\tthis.bufferSizeDB = t.readUint32(),\n\tthis.maxBitrate = t.readUint32(),\n\tthis.avgBitrate = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("ccst", "CodingConstraintsBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.all_ref_pics_intra = 128 == (128 & e),\n\tthis.intra_pred_used = 64 == (64 & e),\n\tthis.max_ref_per_pic = (63 & e) >> 2,\n\tt.readUint24()\n}),\nBoxParser.createBoxCtor("cdef", "ComponentDefinitionBox",\nfunction(t) {\n\tvar e;\n\tfor (this.channel_count = t.readUint16(), this.channel_indexes = [], this.channel_types = [], this.channel_associations = [], e = 0; e < this.channel_count; e++) this.channel_indexes.push(t.readUint16()),\n\tthis.channel_types.push(t.readUint16()),\n\tthis.channel_associations.push(t.readUint16())\n}),\nBoxParser.createBoxCtor("clap", "CleanApertureBox",\nfunction(t) {\n\tthis.cleanApertureWidthN = t.readUint32(),\n\tthis.cleanApertureWidthD = t.readUint32(),\n\tthis.cleanApertureHeightN = t.readUint32(),\n\tthis.cleanApertureHeightD = t.readUint32(),\n\tthis.horizOffN = t.readUint32(),\n\tthis.horizOffD = t.readUint32(),\n\tthis.vertOffN = t.readUint32(),\n\tthis.vertOffD = t.readUint32()\n}),\nBoxParser.createBoxCtor("clli", "ContentLightLevelBox",\nfunction(t) {\n\tthis.max_content_light_level = t.readUint16(),\n\tthis.max_pic_average_light_level = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("cmex", "CameraExtrinsicMatrixProperty",\nfunction(t) {\n\t1 & this.flags && (this.pos_x = t.readInt32()),\n\t2 & this.flags && (this.pos_y = t.readInt32()),\n\t4 & this.flags && (this.pos_z = t.readInt32()),\n\t8 & this.flags && (0 == this.version ? 16 & this.flags ? (this.quat_x = t.readInt32(), this.quat_y = t.readInt32(), this.quat_z = t.readInt32()) : (this.quat_x = t.readInt16(), this.quat_y = t.readInt16(), this.quat_z = t.readInt16()) : this.version),\n\t32 & this.flags && (this.id = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("cmin", "CameraIntrinsicMatrixProperty",\nfunction(t) {\n\tthis.focal_length_x = t.readInt32(),\n\tthis.principal_point_x = t.readInt32(),\n\tthis.principal_point_y = t.readInt32(),\n\t1 & this.flags && (this.focal_length_y = t.readInt32(), this.skew_factor = t.readInt32())\n}),\nBoxParser.createBoxCtor("cmpd", "ComponentDefinitionBox",\nfunction(t) {\n\tfor (this.component_count = t.readUint32(), this.component_types = [], this.component_type_urls = [], i = 0; i < this.component_count; i++) {\n\t\tvar e = t.readUint16();\n\t\tthis.component_types.push(e),\n\t\t32768 <= e && this.component_type_urls.push(t.readCString())\n\t}\n}),\nBoxParser.createFullBoxCtor("co64", "ChunkLargeOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (e = 0; e < i; e++) this.chunk_offsets.push(t.readUint64())\n}),\nBoxParser.createFullBoxCtor("CoLL", "ContentLightLevelBox",\nfunction(t) {\n\tthis.maxCLL = t.readUint16(),\n\tthis.maxFALL = t.readUint16()\n}),\nBoxParser.createBoxCtor("colr", "ColourInformationBox",\nfunction(t) {\n\tvar e;\n\tthis.colour_type = t.readString(4),\n\t"nclx" === this.colour_type ? (this.colour_primaries = t.readUint16(), this.transfer_characteristics = t.readUint16(), this.matrix_coefficients = t.readUint16(), e = t.readUint8(), this.full_range_flag = e >> 7) : "rICC" !== this.colour_type && "prof" !== this.colour_type || (this.ICC_profile = t.readUint8Array(this.size - 4))\n}),\nBoxParser.createFullBoxCtor("cprt", "CopyrightBox",\nfunction(t) {\n\tthis.parseLanguage(t),\n\tthis.notice = t.readCString()\n}),\nBoxParser.createFullBoxCtor("cslg", "CompositionToDecodeBox",\nfunction(t) {\n\t0 === this.version && (this.compositionToDTSShift = t.readInt32(), this.leastDecodeToDisplayDelta = t.readInt32(), this.greatestDecodeToDisplayDelta = t.readInt32(), this.compositionStartTime = t.readInt32(), this.compositionEndTime = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("ctts", "CompositionOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.sample_counts = [], this.sample_offsets = [], 0 === this.version) for (e = 0; e < i; e++) {\n\t\tthis.sample_counts.push(t.readUint32());\n\t\tvar r = t.readInt32();\n\t\tr < 0 && Log.warn("BoxParser", "ctts box uses negative values without using version 1"),\n\t\tthis.sample_offsets.push(r)\n\t} else if (1 == this.version) for (e = 0; e < i; e++) this.sample_counts.push(t.readUint32()),\n\tthis.sample_offsets.push(t.readInt32())\n}),\nBoxParser.createBoxCtor("dac3", "AC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint8(),\n\ti = t.readUint8(),\n\tt = t.readUint8();\n\tthis.fscod = e >> 6,\n\tthis.bsid = e >> 1 & 31,\n\tthis.bsmod = (1 & e) << 2 | i >> 6 & 3,\n\tthis.acmod = i >> 3 & 7,\n\tthis.lfeon = i >> 2 & 1,\n\tthis.bit_rate_code = 3 & i | t >> 5 & 7\n}),\nBoxParser.createBoxCtor("dec3", "EC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint16();\n\tthis.data_rate = e >> 3,\n\tthis.num_ind_sub = 7 & e,\n\tthis.ind_subs = [];\n\tfor (var i = 0; i < this.num_ind_sub + 1; i++) {\n\t\tvar r = {};\n\t\tthis.ind_subs.push(r);\n\t\tvar s = t.readUint8(),\n\t\ta = t.readUint8(),\n\t\tn = t.readUint8();\n\t\tr.fscod = s >> 6,\n\t\tr.bsid = s >> 1 & 31,\n\t\tr.bsmod = (1 & s) << 4 | a >> 4 & 15,\n\t\tr.acmod = a >> 1 & 7,\n\t\tr.lfeon = 1 & a,\n\t\tr.num_dep_sub = n >> 1 & 15,\n\t\t0 < r.num_dep_sub && (r.chan_loc = (1 & n) << 8 | t.readUint8())\n\t}\n}),\nBoxParser.createFullBoxCtor("dfLa", "FLACSpecificBox",\nfunction(t) {\n\tfor (var e = [], i = ["STREAMINFO", "PADDING", "APPLICATION", "SEEKTABLE", "VORBIS_COMMENT", "CUESHEET", "PICTURE", "RESERVED"];;) {\n\t\tvar r = t.readUint8(),\n\t\ts = Math.min(127 & r, i.length - 1);\n\t\tif (s ? t.readUint8Array(t.readUint24()) : (t.readUint8Array(13), this.samplerate = t.readUint32() >> 12, t.readUint8Array(20)), e.push(i[s]), 128 & r) break\n\t}\n\tthis.numMetadataBlocks = e.length + " (" + e.join(", ") + ")"\n}),\nBoxParser.createBoxCtor("dimm", "hintimmediateBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dmax", "hintlongestpacket",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("dmed", "hintmediaBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dOps", "OpusSpecificBox",\nfunction(t) {\n\tif (this.Version = t.readUint8(), this.OutputChannelCount = t.readUint8(), this.PreSkip = t.readUint16(), this.InputSampleRate = t.readUint32(), this.OutputGain = t.readInt16(), this.ChannelMappingFamily = t.readUint8(), 0 !== this.ChannelMappingFamily) {\n\t\tthis.StreamCount = t.readUint8(),\n\t\tthis.CoupledCount = t.readUint8(),\n\t\tthis.ChannelMapping = [];\n\t\tfor (var e = 0; e < this.OutputChannelCount; e++) this.ChannelMapping[e] = t.readUint8()\n\t}\n}),\nBoxParser.createFullBoxCtor("dref", "DataReferenceBox",\nfunction(t) {\n\tvar e;\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\te = e.box,\n\t\tthis.entries.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("drep", "hintrepeatedBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("elng", "ExtendedLanguageBox",\nfunction(t) {\n\tthis.extended_language = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("elst", "EditListBox",\nfunction(t) {\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\t1 === this.version ? (r.segment_duration = t.readUint64(), r.media_time = t.readInt64()) : (r.segment_duration = t.readUint32(), r.media_time = t.readInt32()),\n\t\tr.media_rate_integer = t.readInt16(),\n\t\tr.media_rate_fraction = t.readInt16()\n\t}\n}),\nBoxParser.createFullBoxCtor("emsg", "EventMessageBox",\nfunction(t) {\n\t1 == this.version ? (this.timescale = t.readUint32(), this.presentation_time = t.readUint64(), this.event_duration = t.readUint32(), this.id = t.readUint32(), this.scheme_id_uri = t.readCString(), this.value = t.readCString()) : (this.scheme_id_uri = t.readCString(), this.value = t.readCString(), this.timescale = t.readUint32(), this.presentation_time_delta = t.readUint32(), this.event_duration = t.readUint32(), this.id = t.readUint32());\n\tvar e = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));\n\t1 == this.version && (e -= 4),\n\tthis.message_data = t.readUint8Array(e)\n}),\nBoxParser.createEntityToGroupCtor = function(e, r) {\n\tBoxParser[e + "Box"] = function(t) {\n\t\tBoxParser.FullBox.call(this, e, t)\n\t},\n\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\tif (this.parseFullHeader(t), r) r.call(this, t);\n\t\telse for (this.group_id = t.readUint32(), this.num_entities_in_group = t.readUint32(), this.entity_ids = [], i = 0; i < this.num_entities_in_group; i++) {\n\t\t\tvar e = t.readUint32();\n\t\t\tthis.entity_ids.push(e)\n\t\t}\n\t}\n},\nBoxParser.createEntityToGroupCtor("aebr"),\nBoxParser.createEntityToGroupCtor("afbr"),\nBoxParser.createEntityToGroupCtor("albc"),\nBoxParser.createEntityToGroupCtor("altr"),\nBoxParser.createEntityToGroupCtor("brst"),\nBoxParser.createEntityToGroupCtor("dobr"),\nBoxParser.createEntityToGroupCtor("eqiv"),\nBoxParser.createEntityToGroupCtor("favc"),\nBoxParser.createEntityToGroupCtor("fobr"),\nBoxParser.createEntityToGroupCtor("iaug"),\nBoxParser.createEntityToGroupCtor("pano"),\nBoxParser.createEntityToGroupCtor("slid"),\nBoxParser.createEntityToGroupCtor("ster"),\nBoxParser.createEntityToGroupCtor("tsyn"),\nBoxParser.createEntityToGroupCtor("wbbr"),\nBoxParser.createEntityToGroupCtor("prgr"),\nBoxParser.createEntityToGroupCtor("pymd",\nfunction(t) {\n\tthis.group_id = t.readUint32(),\n\tthis.num_entities_in_group = t.readUint32(),\n\tthis.entity_ids = [];\n\tfor (var e = 0; e < this.num_entities_in_group; e++) {\n\t\tvar i = t.readUint32();\n\t\tthis.entity_ids.push(i)\n\t}\n\tfor (this.tile_size_x = t.readUint16(), this.tile_size_y = t.readUint16(), this.layer_binning = [], this.tiles_in_layer_column_minus1 = [], this.tiles_in_layer_row_minus1 = [], e = 0; e < this.num_entities_in_group; e++) this.layer_binning[e] = t.readUint16(),\n\tthis.tiles_in_layer_row_minus1[e] = t.readUint16(),\n\tthis.tiles_in_layer_column_minus1[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("esds", "ElementaryStreamDescriptorBox",\nfunction(t) {\n\tvar e = t.readUint8Array(this.size - this.hdr_size);\n\tvoid 0 !== MPEG4DescriptorParser && (t = new MPEG4DescriptorParser, this.esd = t.parseOneDescriptor(new DataStream(e.buffer, 0, DataStream.BIG_ENDIAN)))\n}),\nBoxParser.createBoxCtor("fiel", "FieldHandlingBox",\nfunction(t) {\n\tthis.fieldCount = t.readUint8(),\n\tthis.fieldOrdering = t.readUint8()\n}),\nBoxParser.createBoxCtor("frma", "OriginalFormatBox",\nfunction(t) {\n\tthis.data_format = t.readString(4)\n}),\nBoxParser.createBoxCtor("ftyp", "FileTypeBox",\nfunction(t) {\n\tvar e = this.size - this.hdr_size;\n\tthis.major_brand = t.readString(4),\n\tthis.minor_version = t.readUint32(),\n\te -= 8,\n\tthis.compatible_brands = [];\n\tfor (var i = 0; 4 <= e;) this.compatible_brands[i] = t.readString(4),\n\te -= 4,\n\ti++\n}),\nBoxParser.createFullBoxCtor("hdlr", "HandlerBox",\nfunction(t) {\n\t0 === this.version && (t.readUint32(), this.handler = t.readString(4), t.readUint32Array(3), this.name = t.readString(this.size - this.hdr_size - 20), "\0" === this.name[this.name.length - 1] && (this.name = this.name.slice(0, -1)))\n}),\nBoxParser.createBoxCtor("hvcC", "HEVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tthis.configurationVersion = t.readUint8(),\n\ti = t.readUint8(),\n\tthis.general_profile_space = i >> 6,\n\tthis.general_tier_flag = (32 & i) >> 5,\n\tthis.general_profile_idc = 31 & i,\n\tthis.general_profile_compatibility = t.readUint32(),\n\tthis.general_constraint_indicator = t.readUint8Array(6),\n\tthis.general_level_idc = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\tthis.chroma_format_idc = 3 & t.readUint8(),\n\tthis.bit_depth_luma_minus8 = 7 & t.readUint8(),\n\tthis.bit_depth_chroma_minus8 = 7 & t.readUint8(),\n\tthis.avgFrameRate = t.readUint16(),\n\ti = t.readUint8(),\n\tthis.constantFrameRate = i >> 6,\n\tthis.numTemporalLayers = (13 & i) >> 3,\n\tthis.temporalIdNested = (4 & i) >> 2,\n\tthis.lengthSizeMinusOne = 3 & i,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var r = t.readUint8(), s = 0; s < r; s++) {\n\t\tvar a = [];\n\t\tthis.nalu_arrays.push(a),\n\t\ti = t.readUint8(),\n\t\ta.completeness = (128 & i) >> 7,\n\t\ta.nalu_type = 63 & i;\n\t\tfor (var n = t.readUint16(), o = 0; o < n; o++) {\n\t\t\tvar h = {};\n\t\t\ta.push(h),\n\t\t\te = t.readUint16(),\n\t\t\th.data = t.readUint8Array(e)\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iinf", "ItemInfoBox",\nfunction(t) {\n\tvar e;\n\t0 === this.version ? this.entry_count = t.readUint16() : this.entry_count = t.readUint32(),\n\tthis.item_infos = [];\n\tfor (var i = 0; i < this.entry_count; i++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\t"infe" !== e.box.type && Log.error("BoxParser", "Expected \'infe\' box, got " + e.box.type),\n\t\tthis.item_infos[i] = e.box\n\t}\n}),\nBoxParser.createFullBoxCtor("iloc", "ItemLocationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.offset_size = e >> 4 & 15,\n\tthis.length_size = 15 & e,\n\te = t.readUint8(),\n\tthis.base_offset_size = e >> 4 & 15,\n\t1 === this.version || 2 === this.version ? this.index_size = 15 & e: this.index_size = 0,\n\tthis.items = [];\n\tvar i = 0;\n\tif (this.version < 2) i = t.readUint16();\n\telse {\n\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\ti = t.readUint32()\n\t}\n\tfor (var r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tif (this.items.push(s), this.version < 2) s.item_ID = t.readUint16();\n\t\telse {\n\t\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\t\ts.item_ID = t.readUint32()\n\t\t}\n\t\tswitch (1 === this.version || 2 === this.version ? s.construction_method = 15 & t.readUint16() : s.construction_method = 0, s.data_reference_index = t.readUint16(), this.base_offset_size) {\n\t\tcase 0:\n\t\t\ts.base_offset = 0;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ts.base_offset = t.readUint32();\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ts.base_offset = t.readUint64();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "Error reading base offset size"\n\t\t}\n\t\tvar a = t.readUint16();\n\t\ts.extents = [];\n\t\tfor (var n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\tif (s.extents.push(o), 1 === this.version || 2 === this.version) switch (this.index_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_index = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_index = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_index = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.offset_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_offset = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_offset = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_offset = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.length_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_length = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_length = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_length = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("imir", "ImageMirror",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.reserved = t >> 7,\n\tthis.axis = 1 & t\n}),\nBoxParser.createFullBoxCtor("infe", "ItemInfoEntry",\nfunction(t) {\n\treturn 0 !== this.version && 1 !== this.version || (this.item_ID = t.readUint16(), this.item_protection_index = t.readUint16(), this.item_name = t.readCString(), this.content_type = t.readCString(), this.content_encoding = t.readCString()),\n\t1 === this.version ? (this.extension_type = t.readString(4), Log.warn("BoxParser", "Cannot parse extension type"), void t.seek(this.start + this.size)) : void(2 <= this.version && (2 === this.version ? this.item_ID = t.readUint16() : 3 === this.version && (this.item_ID = t.readUint32()), this.item_protection_index = t.readUint16(), this.item_type = t.readString(4), this.item_name = t.readCString(), "mime" === this.item_type ? (this.content_type = t.readCString(), this.content_encoding = t.readCString()) : "uri " === this.item_type && (this.item_uri_type = t.readCString())))\n}),\nBoxParser.createFullBoxCtor("ipma", "ItemPropertyAssociationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (entry_count = t.readUint32(), this.associations = [], e = 0; e < entry_count; e++) {\n\t\tvar r = {};\n\t\tthis.associations.push(r),\n\t\tthis.version < 1 ? r.id = t.readUint16() : r.id = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tfor (r.props = [], i = 0; i < s; i++) {\n\t\t\tvar a = t.readUint8(),\n\t\t\tn = {};\n\t\t\tr.props.push(n),\n\t\t\tn.essential = (128 & a) >> 7 == 1,\n\t\t\t1 & this.flags ? n.property_index = (127 & a) << 8 | t.readUint8() : n.property_index = 127 & a\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iref", "ItemReferenceBox",\nfunction(t) {\n\tvar e;\n\tfor (this.references = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new(0 === this.version ? BoxParser.SingleItemTypeReferenceBox: BoxParser.SingleItemTypeReferenceBoxLarge)(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.warn("BoxParser", e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.references.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("irot", "ImageRotation",\nfunction(t) {\n\tthis.angle = 3 & t.readUint8()\n}),\nBoxParser.createFullBoxCtor("ispe", "ImageSpatialExtentsProperty",\nfunction(t) {\n\tthis.image_width = t.readUint32(),\n\tthis.image_height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("kind", "KindBox",\nfunction(t) {\n\tthis.schemeURI = t.readCString(),\n\tthis.value = t.readCString()\n}),\nBoxParser.createFullBoxCtor("leva", "LevelAssignmentBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.levels = [];\n\tfor (var i = 0; i < e; i++) {\n\t\tvar r = {}; (this.levels[i] = r).track_ID = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tswitch (r.padding_flag = s >> 7, r.assignment_type = 127 & s, r.assignment_type) {\n\t\tcase 0:\n\t\t\tr.grouping_type = t.readString(4);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tr.grouping_type = t.readString(4),\n\t\t\tr.grouping_type_parameter = t.readUint32();\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tr.sub_track_id = t.readUint32();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLog.warn("BoxParser", "Unknown leva assignement type")\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lhvC", "LHEVCConfigurationBox",\nfunction(t) {\n\tvar e;\n\tthis.configurationVersion = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\te = t.readUint8(),\n\tthis.numTemporalLayers = (13 & e) >> 3,\n\tthis.temporalIdNested = (4 & e) >> 2,\n\tthis.lengthSizeMinusOne = 3 & e,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = [];\n\t\tthis.nalu_arrays.push(s),\n\t\te = t.readUint8(),\n\t\ts.completeness = (128 & e) >> 7,\n\t\ts.nalu_type = 63 & e;\n\t\tfor (var a = t.readUint16(), n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\ts.push(o);\n\t\t\tvar h = t.readUint16();\n\t\t\to.data = t.readUint8Array(h)\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lsel", "LayerSelectorProperty",\nfunction(t) {\n\tthis.layer_id = t.readUint16()\n}),\nBoxParser.createBoxCtor("maxr", "hintmaxrate",\nfunction(t) {\n\tthis.period = t.readUint32(),\n\tthis.bytes = t.readUint32()\n}),\nColorPoint.prototype.toString = function() {\n\treturn "(" + this.x + "," + this.y + ")"\n},\nBoxParser.createBoxCtor("mdcv", "MasteringDisplayColourVolumeBox",\nfunction(t) {\n\tthis.display_primaries = [],\n\tthis.display_primaries[0] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[1] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[2] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.white_point = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.max_display_mastering_luminance = t.readUint32(),\n\tthis.min_display_mastering_luminance = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mdhd", "MediaHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.parseLanguage(t),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("mehd", "MovieExtendsHeaderBox",\nfunction(t) {\n\t1 & this.flags && (Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1"), this.version = 1),\n\t1 == this.version ? this.fragment_duration = t.readUint64() : this.fragment_duration = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("meta", "MetaBox",\nfunction(t) {\n\tthis.boxes = [],\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("mfhd", "MovieFragmentHeaderBox",\nfunction(t) {\n\tthis.sequence_number = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mfro", "MovieFragmentRandomAccessOffsetBox",\nfunction(t) {\n\tthis._size = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mskC", "MaskConfigurationProperty",\nfunction(t) {\n\tthis.bits_per_pixel = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("mvhd", "MovieHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.rate = t.readUint32(),\n\tthis.volume = t.readUint16() >> 8,\n\tt.readUint16(),\n\tt.readUint32Array(2),\n\tthis.matrix = t.readUint32Array(9),\n\tt.readUint32Array(6),\n\tthis.next_track_id = t.readUint32()\n}),\nBoxParser.createBoxCtor("npck", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint32()\n}),\nBoxParser.createBoxCtor("nump", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("padb", "PaddingBitsBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.padbits = [];\n\tfor (var i = 0; i < Math.floor((e + 1) / 2); i++) this.padbits = t.readUint8()\n}),\nBoxParser.createBoxCtor("pasp", "PixelAspectRatioBox",\nfunction(t) {\n\tthis.hSpacing = t.readUint32(),\n\tthis.vSpacing = t.readUint32()\n}),\nBoxParser.createBoxCtor("payl", "CuePayloadBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createBoxCtor("payt", "hintpayloadID",\nfunction(t) {\n\tthis.payloadID = t.readUint32();\n\tvar e = t.readUint8();\n\tthis.rtpmap_string = t.readString(e)\n}),\nBoxParser.createFullBoxCtor("pdin", "ProgressiveDownloadInfoBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 8;\n\tthis.rate = [],\n\tthis.initial_delay = [];\n\tfor (var i = 0; i < e; i++) this.rate[i] = t.readUint32(),\n\tthis.initial_delay[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pitm", "PrimaryItemBox",\nfunction(t) {\n\t0 === this.version ? this.item_id = t.readUint16() : this.item_id = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pixi", "PixelInformationProperty",\nfunction(t) {\n\tvar e;\n\tfor (this.num_channels = t.readUint8(), this.bits_per_channels = [], e = 0; e < this.num_channels; e++) this.bits_per_channels[e] = t.readUint8()\n}),\nBoxParser.createBoxCtor("pmax", "hintlargestpacket",\nfunction(t) {\n\tthis.bytes = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prdi", "ProgressiveDerivedImageItemInformationProperty",\nfunction(t) {\n\tif (this.step_count = t.readUint16(), this.item_count = [], 2 & this.flags) for (var e = 0; e < this.step_count; e++) this.item_count[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("prft", "ProducerReferenceTimeBox",\nfunction(t) {\n\tthis.ref_track_id = t.readUint32(),\n\tthis.ntp_timestamp = t.readUint64(),\n\t0 === this.version ? this.media_time = t.readUint32() : this.media_time = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("pssh", "ProtectionSystemSpecificHeaderBox",\nfunction(t) {\n\tif (this.system_id = BoxParser.parseHex16(t), 0 < this.version) {\n\t\tvar e = t.readUint32();\n\t\tthis.kid = [];\n\t\tfor (var i = 0; i < e; i++) this.kid[i] = BoxParser.parseHex16(t)\n\t}\n\tvar r = t.readUint32();\n\t0 < r && (this.data = t.readUint8Array(r))\n}),\nBoxParser.createFullBoxCtor("clef", "TrackCleanApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("enof", "TrackEncodedPixelsDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prof", "TrackProductionApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createContainerBoxCtor("tapt", "TrackApertureModeDimensionsBox", null, ["clef", "prof", "enof"]),\nBoxParser.createBoxCtor("rtp ", "rtpmoviehintinformation",\nfunction(t) {\n\tthis.descriptionformat = t.readString(4),\n\tthis.sdptext = t.readString(this.size - this.hdr_size - 4)\n}),\nBoxParser.createFullBoxCtor("saio", "SampleAuxiliaryInformationOffsetsBox",\nfunction(t) {\n\t1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32());\n\tvar e = t.readUint32();\n\tthis.offset = [];\n\tfor (var i = 0; i < e; i++) 0 === this.version ? this.offset[i] = t.readUint32() : this.offset[i] = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("saiz", "SampleAuxiliaryInformationSizesBox",\nfunction(t) {\n\tif (1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32()), this.default_sample_info_size = t.readUint8(), this.sample_count = t.readUint32(), this.sample_info_size = [], 0 === this.default_sample_info_size) for (var e = 0; e < this.sample_count; e++) this.sample_info_size[e] = t.readUint8()\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "mett",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "metx",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "sbtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stpp",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.auxiliary_mime_types = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stxt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "tx3g",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.displayFlags = t.readUint32(),\n\tthis.horizontal_justification = t.readInt8(),\n\tthis.vertical_justification = t.readInt8(),\n\tthis.bg_color_rgba = t.readUint8Array(4),\n\tthis.box_record = t.readInt16Array(4),\n\tthis.style_record = t.readUint8Array(12),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "wvtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleGroupCtor("alst",\nfunction(t) {\n\tvar e, i = t.readUint16();\n\tfor (this.first_output_sample = t.readUint16(), this.sample_offset = [], e = 0; e < i; e++) this.sample_offset[e] = t.readUint32();\n\tvar r = this.description_length - 4 - 4 * i;\n\tfor (this.num_output_samples = [], this.num_total_samples = [], e = 0; e < r / 4; e++) this.num_output_samples[e] = t.readUint16(),\n\tthis.num_total_samples[e] = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avll",\nfunction(t) {\n\tthis.layerNumber = t.readUint8(),\n\tthis.accurateStatisticsFlag = t.readUint8(),\n\tthis.avgBitRate = t.readUint16(),\n\tthis.avgFrameRate = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avss",\nfunction(t) {\n\tthis.subSequenceIdentifier = t.readUint16(),\n\tthis.layerNumber = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.durationFlag = e >> 7,\n\tthis.avgRateFlag = e >> 6 & 1,\n\tthis.durationFlag && (this.duration = t.readUint32()),\n\tthis.avgRateFlag && (this.accurateStatisticsFlag = t.readUint8(), this.avgBitRate = t.readUint16(), this.avgFrameRate = t.readUint16()),\n\tthis.dependency = [];\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tthis.dependency.push(s),\n\t\ts.subSeqDirectionFlag = t.readUint8(),\n\t\ts.layerNumber = t.readUint8(),\n\t\ts.subSequenceIdentifier = t.readUint16()\n\t}\n}),\nBoxParser.createSampleGroupCtor("dtrt",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("mvif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("prol",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.createSampleGroupCtor("rap ",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.num_leading_samples_known = t >> 7,\n\tthis.num_leading_samples = 127 & t\n}),\nBoxParser.createSampleGroupCtor("rash",\nfunction(t) {\n\tif (this.operation_point_count = t.readUint16(), this.description_length !== 2 + (1 === this.operation_point_count ? 2 : 6 * this.operation_point_count) + 9) Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length"),\n\tthis.data = t.readUint8Array(this.description_length - 2);\n\telse {\n\t\tif (1 === this.operation_point_count) this.target_rate_share = t.readUint16();\n\t\telse {\n\t\t\tthis.target_rate_share = [],\n\t\t\tthis.available_bitrate = [];\n\t\t\tfor (var e = 0; e < this.operation_point_count; e++) this.available_bitrate[e] = t.readUint32(),\n\t\t\tthis.target_rate_share[e] = t.readUint16()\n\t\t}\n\t\tthis.maximum_bitrate = t.readUint32(),\n\t\tthis.minimum_bitrate = t.readUint32(),\n\t\tthis.discard_priority = t.readUint8()\n\t}\n}),\nBoxParser.createSampleGroupCtor("roll",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.SampleGroupEntry.prototype.parse = function(t) {\n\tLog.warn("BoxParser", "Unknown Sample Group type: " + this.grouping_type),\n\tthis.data = t.readUint8Array(this.description_length)\n},\nBoxParser.createSampleGroupCtor("scif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("scnm",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("seig",\nfunction(t) {\n\tthis.reserved = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.crypt_byte_block = e >> 4,\n\tthis.skip_byte_block = 15 & e,\n\tthis.isProtected = t.readUint8(),\n\tthis.Per_Sample_IV_Size = t.readUint8(),\n\tthis.KID = BoxParser.parseHex16(t),\n\tthis.constant_IV_size = 0,\n\tthis.constant_IV = 0,\n\t1 === this.isProtected && 0 === this.Per_Sample_IV_Size && (this.constant_IV_size = t.readUint8(), this.constant_IV = t.readUint8Array(this.constant_IV_size))\n}),\nBoxParser.createSampleGroupCtor("stsa",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("sync",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.NAL_unit_type = 63 & t\n}),\nBoxParser.createSampleGroupCtor("tele",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.level_independently_decodable = t >> 7\n}),\nBoxParser.createSampleGroupCtor("tsas",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("tscl",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("vipr",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createFullBoxCtor("sbgp", "SampleToGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\t1 === this.version ? this.grouping_type_parameter = t.readUint32() : this.grouping_type_parameter = 0,\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\tr.sample_count = t.readInt32(),\n\t\tr.group_description_index = t.readInt32()\n\t}\n}),\nPixel.prototype.toString = function() {\n\treturn "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]"\n},\nBoxParser.createFullBoxCtor("sbpm", "SensorBadPixelsMapBox",\nfunction(t) {\n\tvar e;\n\tfor (this.component_count = t.readUint16(), this.component_index = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16());\n\tvar i = t.readUint8();\n\tfor (this.correction_applied = 128 == (128 & i), this.num_bad_rows = t.readUint32(), this.num_bad_cols = t.readUint32(), this.num_bad_pixels = t.readUint32(), this.bad_rows = [], this.bad_columns = [], this.bad_pixels = [], e = 0; e < this.num_bad_rows; e++) this.bad_rows.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_cols; e++) this.bad_columns.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_pixels; e++) {\n\t\tvar r = t.readUint32(),\n\t\ts = t.readUint32();\n\t\tthis.bad_pixels.push(new Pixel(r, s))\n\t}\n}),\nBoxParser.createFullBoxCtor("schm", "SchemeTypeBox",\nfunction(t) {\n\tthis.scheme_type = t.readString(4),\n\tthis.scheme_version = t.readUint32(),\n\t1 & this.flags && (this.scheme_uri = t.readString(this.size - this.hdr_size - 8))\n}),\nBoxParser.createBoxCtor("sdp ", "rtptracksdphintinformation",\nfunction(t) {\n\tthis.sdptext = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("sdtp", "SampleDependencyTypeBox",\nfunction(t) {\n\tvar e, i = this.size - this.hdr_size;\n\tthis.is_leading = [],\n\tthis.sample_depends_on = [],\n\tthis.sample_is_depended_on = [],\n\tthis.sample_has_redundancy = [];\n\tfor (var r = 0; r < i; r++) e = t.readUint8(),\n\tthis.is_leading[r] = e >> 6,\n\tthis.sample_depends_on[r] = e >> 4 & 3,\n\tthis.sample_is_depended_on[r] = e >> 2 & 3,\n\tthis.sample_has_redundancy[r] = 3 & e\n}),\nBoxParser.createFullBoxCtor("senc", "SampleEncryptionBox"),\nBoxParser.createFullBoxCtor("sgpd", "SampleGroupDescriptionBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\tLog.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type),\n\t1 === this.version ? this.default_length = t.readUint32() : this.default_length = 0,\n\t2 <= this.version && (this.default_group_description_index = t.readUint32()),\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = new(BoxParser[this.grouping_type + "SampleGroupEntry"] ? BoxParser[this.grouping_type + "SampleGroupEntry"] : BoxParser.SampleGroupEntry)(this.grouping_type);\n\t\tthis.entries.push(r),\n\t\t1 === this.version && 0 === this.default_length ? r.description_length = t.readUint32() : r.description_length = this.default_length,\n\t\tr.write === BoxParser.SampleGroupEntry.prototype.write && (Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write"), r.data = t.readUint8Array(r.description_length), t.position -= r.description_length),\n\t\tr.parse(t)\n\t}\n}),\nBoxParser.createFullBoxCtor("sidx", "CompressedSegmentIndexBox",\nfunction(t) {\n\tthis.reference_ID = t.readUint32(),\n\tthis.timescale = t.readUint32(),\n\t0 === this.version ? (this.earliest_presentation_time = t.readUint32(), this.first_offset = t.readUint32()) : (this.earliest_presentation_time = t.readUint64(), this.first_offset = t.readUint64()),\n\tt.readUint16(),\n\tthis.references = [];\n\tfor (var e = t.readUint16(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.references.push(r);\n\t\tvar s = t.readUint32();\n\t\tr.reference_type = s >> 31 & 1,\n\t\tr.referenced_size = 2147483647 & s,\n\t\tr.subsegment_duration = t.readUint32(),\n\t\ts = t.readUint32(),\n\t\tr.starts_with_SAP = s >> 31 & 1,\n\t\tr.SAP_type = s >> 28 & 7,\n\t\tr.SAP_delta_time = 268435455 & s\n\t}\n}),\nBoxParser.SingleItemTypeReferenceBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBox.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBox.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint16();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint16()\n},\nBoxParser.SingleItemTypeReferenceBoxLarge = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint32()\n},\nBoxParser.createFullBoxCtor("SmDm", "SMPTE2086MasteringDisplayMetadataBox",\nfunction(t) {\n\tthis.primaryRChromaticity_x = t.readUint16(),\n\tthis.primaryRChromaticity_y = t.readUint16(),\n\tthis.primaryGChromaticity_x = t.readUint16(),\n\tthis.primaryGChromaticity_y = t.readUint16(),\n\tthis.primaryBChromaticity_x = t.readUint16(),\n\tthis.primaryBChromaticity_y = t.readUint16(),\n\tthis.whitePointChromaticity_x = t.readUint16(),\n\tthis.whitePointChromaticity_y = t.readUint16(),\n\tthis.luminanceMax = t.readUint32(),\n\tthis.luminanceMin = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("smhd", "SoundMediaHeaderBox",\nfunction(t) {\n\tthis.balance = t.readUint16(),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("ssix", "CompressedSubsegmentIndexBox",\nfunction(t) {\n\tthis.subsegments = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.subsegments.push(r),\n\t\tr.ranges = [];\n\t\tfor (var s = t.readUint32(), a = 0; a < s; a++) {\n\t\t\tvar n = {};\n\t\t\tr.ranges.push(n),\n\t\t\tn.level = t.readUint8(),\n\t\t\tn.range_size = t.readUint24()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("stco", "ChunkOffsetBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (var i = 0; i < e; i++) this.chunk_offsets.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stdp", "DegradationPriorityBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 2;\n\tthis.priority = [];\n\tfor (var i = 0; i < e; i++) this.priority[i] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("sthd", "SubtitleMediaHeaderBox"),\nBoxParser.createFullBoxCtor("stri", "SubTrackInformationBox",\nfunction(t) {\n\tthis.switch_group = t.readUint16(),\n\tthis.alternate_group = t.readUint16(),\n\tthis.sub_track_id = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 8) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsc", "SampleToChunkBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.first_chunk = [], this.samples_per_chunk = [], this.sample_description_index = [], 0 === this.version) for (e = 0; e < i; e++) this.first_chunk.push(t.readUint32()),\n\tthis.samples_per_chunk.push(t.readUint32()),\n\tthis.sample_description_index.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsd", "SampleDescriptionBox",\nfunction(t) {\n\tvar e, i, r, s;\n\tfor (this.entries = [], r = t.readUint32(), e = 1; e <= r; e++) {\n\t\tif ((i = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tBoxParser[i.type + "SampleEntry"] ? ((s = new BoxParser[i.type + "SampleEntry"](i.size)).hdr_size = i.hdr_size, s.start = i.start) : (Log.warn("BoxParser", "Unknown sample entry type: " + i.type), s = new BoxParser.SampleEntry(i.type, i.size, i.hdr_size, i.start)),\n\t\ts.write === BoxParser.SampleEntry.prototype.write && (Log.info("BoxParser", "SampleEntry " + s.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), s.parseDataAndRewind(t)),\n\t\ts.parse(t),\n\t\tthis.entries.push(s)\n\t}\n}),\nBoxParser.createFullBoxCtor("stsg", "SubTrackSampleGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.group_description_index = [];\n\tfor (var i = 0; i < e; i++) this.group_description_index[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsh", "ShadowSyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.shadowed_sample_numbers = [], this.sync_sample_numbers = [], 0 === this.version) for (e = 0; e < i; e++) this.shadowed_sample_numbers.push(t.readUint32()),\n\tthis.sync_sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stss", "SyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (0 === this.version) for (this.sample_numbers = [], e = 0; e < i; e++) this.sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsz", "SampleSizeBox",\nfunction(t) {\n\tvar e;\n\tif (this.sample_sizes = [], 0 === this.version) for (this.sample_size = t.readUint32(), this.sample_count = t.readUint32(), e = 0; e < this.sample_count; e++) 0 === this.sample_size ? this.sample_sizes.push(t.readUint32()) : this.sample_sizes[e] = this.sample_size\n}),\nBoxParser.createFullBoxCtor("stts", "TimeToSampleBox",\nfunction(t) {\n\tvar e, i, r = t.readUint32();\n\tif (this.sample_counts = [], this.sample_deltas = [], 0 === this.version) for (e = 0; e < r; e++) this.sample_counts.push(t.readUint32()),\n\t(i = t.readInt32()) < 0 && (Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!"), i = 1),\n\tthis.sample_deltas.push(i)\n}),\nBoxParser.createFullBoxCtor("stvi", "StereoVideoBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.single_view_allowed = 3 & e,\n\tthis.stereo_scheme = t.readUint32();\n\tvar i, e = t.readUint32();\n\tfor (this.stereo_indication_type = t.readString(e), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((i = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\ti = i.box,\n\t\tthis.boxes.push(i),\n\t\tthis[i.type] = i\n\t}\n}),\nBoxParser.createBoxCtor("styp", "SegmentTypeBox",\nfunction(t) {\n\tBoxParser.ftypBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("stz2", "CompactSampleSizeBox",\nfunction(t) {\n\tvar e, i;\n\tif (this.sample_sizes = [], 0 === this.version) if (this.reserved = t.readUint24(), this.field_size = t.readUint8(), i = t.readUint32(), 4 === this.field_size) for (e = 0; e < i; e += 2) {\n\t\tvar r = t.readUint8();\n\t\tthis.sample_sizes[e] = r >> 4 & 15,\n\t\tthis.sample_sizes[e + 1] = 15 & r\n\t} else if (8 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint8();\n\telse if (16 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint16();\n\telse Log.error("BoxParser", "Error in length field in stz2 box")\n}),\nBoxParser.createFullBoxCtor("subs", "SubSampleInformationBox",\nfunction(t) {\n\tvar e, i, r, s = t.readUint32();\n\tfor (this.entries = [], e = 0; e < s; e++) {\n\t\tvar a = {};\n\t\tif ((this.entries[e] = a).sample_delta = t.readUint32(), a.subsamples = [], 0 < (r = t.readUint16())) for (i = 0; i < r; i++) {\n\t\t\tvar n = {};\n\t\t\ta.subsamples.push(n),\n\t\t\t1 == this.version ? n.size = t.readUint32() : n.size = t.readUint16(),\n\t\t\tn.priority = t.readUint8(),\n\t\t\tn.discardable = t.readUint8(),\n\t\t\tn.codec_specific_parameters = t.readUint32()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("tenc", "TrackEncryptionBox",\nfunction(t) {\n\tvar e;\n\tt.readUint8(),\n\t0 === this.version ? t.readUint8() : (e = t.readUint8(), this.default_crypt_byte_block = e >> 4 & 15, this.default_skip_byte_block = 15 & e),\n\tthis.default_isProtected = t.readUint8(),\n\tthis.default_Per_Sample_IV_Size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t),\n\t1 === this.default_isProtected && 0 === this.default_Per_Sample_IV_Size && (this.default_constant_IV_size = t.readUint8(), this.default_constant_IV = t.readUint8Array(this.default_constant_IV_size))\n}),\nBoxParser.createFullBoxCtor("tfdt", "TrackFragmentBaseMediaDecodeTimeBox",\nfunction(t) {\n\t1 == this.version ? this.baseMediaDecodeTime = t.readUint64() : this.baseMediaDecodeTime = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("tfhd", "TrackFragmentHeaderBox",\nfunction(t) {\n\tvar e = 0;\n\tthis.track_id = t.readUint32(),\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET ? (this.base_data_offset = t.readUint64(), e += 8) : this.base_data_offset = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? (this.default_sample_description_index = t.readUint32(), e += 4) : this.default_sample_description_index = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? (this.default_sample_duration = t.readUint32(), e += 4) : this.default_sample_duration = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? (this.default_sample_size = t.readUint32(), e += 4) : this.default_sample_size = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? (this.default_sample_flags = t.readUint32(), e += 4) : this.default_sample_flags = 0\n}),\nBoxParser.createFullBoxCtor("tfra", "TrackFragmentRandomAccessBox",\nfunction(t) {\n\tthis.track_ID = t.readUint32(),\n\tt.readUint24();\n\tvar e = t.readUint8();\n\tthis.length_size_of_traf_num = e >> 4 & 3,\n\tthis.length_size_of_trun_num = e >> 2 & 3,\n\tthis.length_size_of_sample_num = 3 & e,\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) 1 === this.version ? (this.time = t.readUint64(), this.moof_offset = t.readUint64()) : (this.time = t.readUint32(), this.moof_offset = t.readUint32()),\n\tthis.traf_number = t["readUint" + 8 * (this.length_size_of_traf_num + 1)](),\n\tthis.trun_number = t["readUint" + 8 * (this.length_size_of_trun_num + 1)](),\n\tthis.sample_number = t["readUint" + 8 * (this.length_size_of_sample_num + 1)]()\n}),\nBoxParser.createFullBoxCtor("tkhd", "TrackHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint32()),\n\tt.readUint32Array(2),\n\tthis.layer = t.readInt16(),\n\tthis.alternate_group = t.readInt16(),\n\tthis.volume = t.readInt16() >> 8,\n\tt.readUint16(),\n\tthis.matrix = t.readInt32Array(9),\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmax", "hintmaxrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmin", "hintminrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("totl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpay", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpyl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.TrackGroupTypeBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.track_group_id = t.readUint32()\n},\nBoxParser.createTrackGroupCtor("msrc"),\nBoxParser.TrackReferenceTypeBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.TrackReferenceTypeBox.prototype = new BoxParser.Box,\nBoxParser.TrackReferenceTypeBox.prototype.parse = function(t) {\n\tthis.track_ids = t.readUint32Array((this.size - this.hdr_size) / 4)\n},\nBoxParser.trefBox.prototype.parse = function(t) {\n\tfor (var e; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new BoxParser.TrackReferenceTypeBox(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.info("BoxParser", "TrackReference " + e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.boxes.push(e)\n\t}\n},\nBoxParser.createFullBoxCtor("trep", "TrackExtensionPropertiesBox",\nfunction(t) {\n\tfor (this.track_ID = t.readUint32(), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif (ret = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start)), ret.code !== BoxParser.OK) return;\n\t\tbox = ret.box,\n\t\tthis.boxes.push(box)\n\t}\n}),\nBoxParser.createFullBoxCtor("trex", "TrackExtendsBox",\nfunction(t) {\n\tthis.track_id = t.readUint32(),\n\tthis.default_sample_description_index = t.readUint32(),\n\tthis.default_sample_duration = t.readUint32(),\n\tthis.default_sample_size = t.readUint32(),\n\tthis.default_sample_flags = t.readUint32()\n}),\nBoxParser.createBoxCtor("trpy", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("trun", "TrackRunBox",\nfunction(t) {\n\tvar e = 0;\n\tif (this.sample_count = t.readUint32(), e += 4, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET ? (this.data_offset = t.readInt32(), e += 4) : this.data_offset = 0, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG ? (this.first_sample_flags = t.readUint32(), e += 4) : this.first_sample_flags = 0, this.sample_duration = [], this.sample_size = [], this.sample_flags = [], this.sample_composition_time_offset = [], this.size - this.hdr_size > e) for (var i = 0; i < this.sample_count; i++) this.flags & BoxParser.TRUN_FLAGS_DURATION && (this.sample_duration[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.sample_size[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.sample_flags[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? this.sample_composition_time_offset[i] = t.readUint32() : this.sample_composition_time_offset[i] = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("tsel", "TrackSelectionBox",\nfunction(t) {\n\tthis.switch_group = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 4) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("txtC", "TextConfigBox",\nfunction(t) {\n\tthis.config = t.readCString()\n}),\nBoxParser.createBoxCtor("tyco", "TypeCombinationBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 4;\n\tthis.compatible_brands = [];\n\tfor (var i = 0; i < e; i++) this.compatible_brands[i] = t.readString(4)\n}),\nBoxParser.createFullBoxCtor("udes", "UserDescriptionProperty",\nfunction(t) {\n\tthis.lang = t.readCString(),\n\tthis.name = t.readCString(),\n\tthis.description = t.readCString(),\n\tthis.tags = t.readCString()\n}),\nBoxParser.createFullBoxCtor("uncC", "UncompressedFrameConfigBox",\nfunction(t) {\n\tvar e;\n\tif (this.profile = t.readString(4), 1 != this.version && 0 == this.version) {\n\t\tfor (this.component_count = t.readUint32(), this.component_index = [], this.component_bit_depth_minus_one = [], this.component_format = [], this.component_align_size = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16()),\n\t\tthis.component_bit_depth_minus_one.push(t.readUint8()),\n\t\tthis.component_format.push(t.readUint8()),\n\t\tthis.component_align_size.push(t.readUint8());\n\t\tthis.sampling_type = t.readUint8(),\n\t\tthis.interleave_type = t.readUint8(),\n\t\tthis.block_size = t.readUint8();\n\t\tvar i = t.readUint8();\n\t\tthis.component_little_endian = i >> 7 & 1,\n\t\tthis.block_pad_lsb = i >> 6 & 1,\n\t\tthis.block_little_endian = i >> 5 & 1,\n\t\tthis.block_reversed = i >> 4 & 1,\n\t\tthis.pad_unknown = i >> 3 & 1,\n\t\tthis.pixel_size = t.readUint32(),\n\t\tthis.row_align_size = t.readUint32(),\n\t\tthis.tile_align_size = t.readUint32(),\n\t\tthis.num_tile_cols_minus_one = t.readUint32(),\n\t\tthis.num_tile_rows_minus_one = t.readUint32()\n\t}\n}),\nBoxParser.createFullBoxCtor("url ", "DataEntryUrlBox",\nfunction(t) {\n\t1 !== this.flags && (this.location = t.readCString())\n}),\nBoxParser.createFullBoxCtor("urn ", "DataEntryUrnBox",\nfunction(t) {\n\tthis.name = t.readCString(),\n\t0 < this.size - this.hdr_size - this.name.length - 1 && (this.location = t.readCString())\n}),\nBoxParser.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66", "LiveServerManifestBox", !0, !1,\nfunction(t) {\n\tthis.LiveServerManifest = t.readString(this.size - this.hdr_size).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\'/g, "&#039;")\n}),\nBoxParser.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3", "PiffProtectionSystemSpecificHeaderBox", !0, !1,\nfunction(t) {\n\tthis.system_id = BoxParser.parseHex16(t);\n\tvar e = t.readUint32();\n\t0 < e && (this.data = t.readUint8Array(e))\n}),\nBoxParser.createUUIDBox("a2394f525a9b4f14a2446c427c648df4", "PiffSampleEncryptionBox", !0, !1),\nBoxParser.createUUIDBox("8974dbce7be74c5184f97148f9882554", "PiffTrackEncryptionBox", !0, !1,\nfunction(t) {\n\tthis.default_AlgorithmID = t.readUint24(),\n\tthis.default_IV_size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t)\n}),\nBoxParser.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f", "TfrfBox", !0, !1,\nfunction(t) {\n\tthis.fragment_count = t.readUint8(),\n\tthis.entries = [];\n\tfor (var e = 0; e < this.fragment_count; e++) {\n\t\tvar i = {},\n\t\tr = 0,\n\t\ts = 0,\n\t\ts = 1 === this.version ? (r = t.readUint64(), t.readUint64()) : (r = t.readUint32(), t.readUint32());\n\t\ti.absolute_time = r,\n\t\ti.absolute_duration = s,\n\t\tthis.entries.push(i)\n\t}\n}),\nBoxParser.createUUIDBox("6d1d9b0542d544e680e2141daff757b2", "TfxdBox", !0, !1,\nfunction(t) {\n\t1 === this.version ? (this.absolute_time = t.readUint64(), this.duration = t.readUint64()) : (this.absolute_time = t.readUint32(), this.duration = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("vmhd", "VideoMediaHeaderBox",\nfunction(t) {\n\tthis.graphicsmode = t.readUint16(),\n\tthis.opcolor = t.readUint16Array(3)\n}),\nBoxParser.createFullBoxCtor("vpcC", "VPCodecConfigurationRecord",\nfunction(t) {\n\tvar e;\n\t1 === this.version ? (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4, this.chromaSubsampling = e >> 1 & 7, this.videoFullRangeFlag = 1 & e, this.colourPrimaries = t.readUint8(), this.transferCharacteristics = t.readUint8(), this.matrixCoefficients = t.readUint8()) : (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4 & 15, this.colorSpace = 15 & e, e = t.readUint8(), this.chromaSubsampling = e >> 4 & 15, this.transferFunction = e >> 1 & 7, this.videoFullRangeFlag = 1 & e),\n\tthis.codecIntializationDataSize = t.readUint16(),\n\tthis.codecIntializationData = t.readUint8Array(this.codecIntializationDataSize)\n}),\nBoxParser.createBoxCtor("vttC", "WebVTTConfigurationBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("vvcC", "VvcConfigurationBox",\nfunction(t) {\n\tvar e, i = {\n\t\theld_bits: void 0,\n\t\tnum_held_bits: 0,\n\t\tstream_read_1_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint8(),\n\t\t\tthis.num_held_bits = 8\n\t\t},\n\t\tstream_read_2_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint16(),\n\t\t\tthis.num_held_bits = 16\n\t\t},\n\t\textract_bits: function(t) {\n\t\t\tvar e = this.held_bits >> this.num_held_bits - t & (1 << t) - 1;\n\t\t\treturn this.num_held_bits -= t,\n\t\t\te\n\t\t}\n\t};\n\tif (i.stream_read_1_bytes(t), i.extract_bits(5), this.lengthSizeMinusOne = i.extract_bits(2), this.ptl_present_flag = i.extract_bits(1), this.ptl_present_flag) {\n\t\tif (i.stream_read_2_bytes(t), this.ols_idx = i.extract_bits(9), this.num_sublayers = i.extract_bits(3), this.constant_frame_rate = i.extract_bits(2), this.chroma_format_idc = i.extract_bits(2), i.stream_read_1_bytes(t), this.bit_depth_minus8 = i.extract_bits(3), i.extract_bits(5), i.stream_read_2_bytes(t), i.extract_bits(2), this.num_bytes_constraint_info = i.extract_bits(6), this.general_profile_idc = i.extract_bits(7), this.general_tier_flag = i.extract_bits(1), this.general_level_idc = t.readUint8(), i.stream_read_1_bytes(t), this.ptl_frame_only_constraint_flag = i.extract_bits(1), this.ptl_multilayer_enabled_flag = i.extract_bits(1), this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info), this.num_bytes_constraint_info) {\n\t\t\tfor (o = 0; o < this.num_bytes_constraint_info - 1; o++) {\n\t\t\t\tvar r = i.extract_bits(6);\n\t\t\t\ti.stream_read_1_bytes(t);\n\t\t\t\tvar s = i.extract_bits(2);\n\t\t\t\tthis.general_constraint_info[o] = r << 2 | s\n\t\t\t}\n\t\t\tthis.general_constraint_info[this.num_bytes_constraint_info - 1] = i.extract_bits(6)\n\t\t} else i.extract_bits(6);\n\t\tif (1 < this.num_sublayers) {\n\t\t\tfor (i.stream_read_1_bytes(t), this.ptl_sublayer_present_mask = 0, e = this.num_sublayers - 2; 0 <= e; --e) {\n\t\t\t\tvar a = i.extract_bits(1);\n\t\t\t\tthis.ptl_sublayer_present_mask |= a << e\n\t\t\t}\n\t\t\tfor (e = this.num_sublayers; e <= 8 && 1 < this.num_sublayers; ++e) i.extract_bits(1);\n\t\t\tfor (this.sublayer_level_idc = [], e = this.num_sublayers - 2; 0 <= e; --e) this.ptl_sublayer_present_mask & 1 << e && (this.sublayer_level_idc[e] = t.readUint8())\n\t\t}\n\t\tif (this.ptl_num_sub_profiles = t.readUint8(), this.general_sub_profile_idc = [], this.ptl_num_sub_profiles) for (o = 0; o < this.ptl_num_sub_profiles; o++) this.general_sub_profile_idc.push(t.readUint32());\n\t\tthis.max_picture_width = t.readUint16(),\n\t\tthis.max_picture_height = t.readUint16(),\n\t\tthis.avg_frame_rate = t.readUint16()\n\t}\n\tthis.nalu_arrays = [];\n\tfor (var n = t.readUint8(), o = 0; o < n; o++) {\n\t\tvar h = [];\n\t\tthis.nalu_arrays.push(h),\n\t\ti.stream_read_1_bytes(t),\n\t\th.completeness = i.extract_bits(1),\n\t\ti.extract_bits(2),\n\t\th.nalu_type = i.extract_bits(5);\n\t\tvar d = 1;\n\t\tfor (13 != h.nalu_type && 12 != h.nalu_type && (d = t.readUint16()), e = 0; e < d; e++) {\n\t\t\tvar l = t.readUint16();\n\t\t\th.push({\n\t\t\t\tdata: t.readUint8Array(l),\n\t\t\t\tlength: l\n\t\t\t})\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("vvnC", "VvcNALUConfigBox",\nfunction(t) {\n\tvar e = strm.readUint8();\n\tthis.lengthSizeMinusOne = 3 & e\n}),\nBoxParser.SampleEntry.prototype.isVideo = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isAudio = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isSubtitle = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isMetadata = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isHint = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.getCodec = function() {\n\treturn this.type.replace(".", "")\n},\nBoxParser.SampleEntry.prototype.getWidth = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getHeight = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getChannelCount = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleRate = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleSize = function() {\n\treturn ""\n},\nBoxParser.VisualSampleEntry.prototype.isVideo = function() {\n\treturn ! 0\n},\nBoxParser.VisualSampleEntry.prototype.getWidth = function() {\n\treturn this.width\n},\nBoxParser.VisualSampleEntry.prototype.getHeight = function() {\n\treturn this.height\n},\nBoxParser.AudioSampleEntry.prototype.isAudio = function() {\n\treturn ! 0\n},\nBoxParser.AudioSampleEntry.prototype.getChannelCount = function() {\n\treturn this.channel_count\n},\nBoxParser.AudioSampleEntry.prototype.getSampleRate = function() {\n\treturn this.samplerate\n},\nBoxParser.AudioSampleEntry.prototype.getSampleSize = function() {\n\treturn this.samplesize\n},\nBoxParser.SubtitleSampleEntry.prototype.isSubtitle = function() {\n\treturn ! 0\n},\nBoxParser.MetadataSampleEntry.prototype.isMetadata = function() {\n\treturn ! 0\n},\nBoxParser.decimalToHex = function(t, e) {\n\tvar i = Number(t).toString(16);\n\tfor (e = null == e ? e = 2 : e; i.length < e;) i = "0" + i;\n\treturn i\n},\nBoxParser.avc1SampleEntry.prototype.getCodec = BoxParser.avc2SampleEntry.prototype.getCodec = BoxParser.avc3SampleEntry.prototype.getCodec = BoxParser.avc4SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.avcC ? t + "." + BoxParser.decimalToHex(this.avcC.AVCProfileIndication) + BoxParser.decimalToHex(this.avcC.profile_compatibility) + BoxParser.decimalToHex(this.avcC.AVCLevelIndication) : t\n},\nBoxParser.hev1SampleEntry.prototype.getCodec = BoxParser.hvc1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.hvcC) {\n\t\tswitch (t += ".", this.hvcC.general_profile_space) {\n\t\tcase 0:\n\t\t\tt += "";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tt += "A";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tt += "B";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tt += "C"\n\t\t}\n\t\tt += this.hvcC.general_profile_idc,\n\t\tt += ".";\n\t\tfor (var e = this.hvcC.general_profile_compatibility,\n\t\ti = 0,\n\t\tr = 0; r < 32 && (i |= 1 & e, 31 != r); r++) i <<= 1,\n\t\te >>= 1;\n\t\tt += BoxParser.decimalToHex(i, 0),\n\t\tt += ".",\n\t\t0 === this.hvcC.general_tier_flag ? t += "L": t += "H",\n\t\tt += this.hvcC.general_level_idc;\n\t\tvar s = !1,\n\t\ta = "";\n\t\tfor (r = 5; 0 <= r; r--)(this.hvcC.general_constraint_indicator[r] || s) && (a = "." + BoxParser.decimalToHex(this.hvcC.general_constraint_indicator[r], 0) + a, s = !0);\n\t\tt += a\n\t}\n\treturn t\n},\nBoxParser.vvc1SampleEntry.prototype.getCodec = BoxParser.vvi1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.vvcC) {\n\t\tt += "." + this.vvcC.general_profile_idc,\n\t\tthis.vvcC.general_tier_flag ? t += ".H": t += ".L",\n\t\tt += this.vvcC.general_level_idc;\n\t\tvar e = "";\n\t\tif (this.vvcC.general_constraint_info) {\n\t\t\tvar i, r = [],\n\t\t\ts = 0;\n\t\t\tfor (s |= this.vvcC.ptl_frame_only_constraint << 7, s |= this.vvcC.ptl_multilayer_enabled << 6, h = 0; h < this.vvcC.general_constraint_info.length; ++h) s |= this.vvcC.general_constraint_info[h] >> 2 & 63,\n\t\t\tr.push(s),\n\t\t\ts && (i = h),\n\t\t\ts = this.vvcC.general_constraint_info[h] >> 2 & 3;\n\t\t\tif (void 0 === i) e = ".CA";\n\t\t\telse {\n\t\t\t\te = ".C";\n\t\t\t\tfor (var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",\n\t\t\t\tn = 0,\n\t\t\t\to = 0,\n\t\t\t\th = 0; h <= i; ++h) for (n = n << 8 | r[h], o += 8; 5 <= o;) e += a[n >> o - 5 & 31],\n\t\t\t\tn &= (1 << (o -= 5)) - 1;\n\t\t\t\to && (e += a[31 & (n <<= 5 - o)])\n\t\t\t}\n\t\t}\n\t\tt += e\n\t}\n\treturn t\n},\nBoxParser.mp4aSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.esds && this.esds.esd) {\n\t\tvar e = this.esds.esd.getOTI(),\n\t\ti = this.esds.esd.getAudioConfig();\n\t\treturn t + "." + BoxParser.decimalToHex(e) + (i ? "." + i: "")\n\t}\n\treturn t\n},\nBoxParser.stxtSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.mime_format ? t + "." + this.mime_format: t\n},\nBoxParser.vp08SampleEntry.prototype.getCodec = BoxParser.vp09SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\te = this.vpcC.level;\n\t0 == e && (e = "00");\n\tvar i = this.vpcC.bitDepth;\n\treturn 8 == i && (i = "08"),\n\tt + ".0" + this.vpcC.profile + "." + e + "." + i\n},\nBoxParser.av01SampleEntry.prototype.getCodec = function() {\n\tvar t, e = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\ti = this.av1C.seq_level_idx_0;\n\treturn i < 10 && (i = "0" + i),\n\t2 === this.av1C.seq_profile && 1 === this.av1C.high_bitdepth ? t = 1 === this.av1C.twelve_bit ? "12": "10": this.av1C.seq_profile <= 2 && (t = 1 === this.av1C.high_bitdepth ? "10": "08"),\n\te + "." + this.av1C.seq_profile + "." + i + (this.av1C.seq_tier_0 ? "H": "M") + "." + t\n},\nBoxParser.Box.prototype.writeHeader = function(t, e) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tLog.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + t.getPosition() + (e || "")),\n\tthis.size > MAX_SIZE ? t.writeUint32(1) : (this.sizePosition = t.getPosition(), t.writeUint32(this.size)),\n\tt.writeString(this.type, null, 4),\n\t"uuid" === this.type && t.writeUint8Array(this.uuid),\n\tthis.size > MAX_SIZE && t.writeUint64(this.size)\n},\nBoxParser.FullBox.prototype.writeHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.writeHeader.call(this, t, " v=" + this.version + " f=" + this.flags),\n\tt.writeUint8(this.version),\n\tt.writeUint24(this.flags)\n},\nBoxParser.Box.prototype.write = function(t) {\n\t"mdat" === this.type ? this.data && (this.size = this.data.length, this.writeHeader(t), t.writeUint8Array(this.data)) : (this.size = this.data ? this.data.length: 0, this.writeHeader(t), this.data && t.writeUint8Array(this.data))\n},\nBoxParser.ContainerBox.prototype.write = function(t) {\n\tthis.size = 0,\n\tthis.writeHeader(t);\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && (this.boxes[e].write(t), this.size += this.boxes[e].size);\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.TrackReferenceTypeBox.prototype.write = function(t) {\n\tthis.size = 4 * this.track_ids.length,\n\tthis.writeHeader(t),\n\tt.writeUint32Array(this.track_ids)\n},\nBoxParser.avcCBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.size = 7, e = 0; e < this.SPS.length; e++) this.size += 2 + this.SPS[e].length;\n\tfor (e = 0; e < this.PPS.length; e++) this.size += 2 + this.PPS[e].length;\n\tfor (this.ext && (this.size += this.ext.length), this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8(this.AVCProfileIndication), t.writeUint8(this.profile_compatibility), t.writeUint8(this.AVCLevelIndication), t.writeUint8(this.lengthSizeMinusOne + 252), t.writeUint8(this.SPS.length + 224), e = 0; e < this.SPS.length; e++) t.writeUint16(this.SPS[e].length),\n\tt.writeUint8Array(this.SPS[e].nalu);\n\tfor (t.writeUint8(this.PPS.length), e = 0; e < this.PPS.length; e++) t.writeUint16(this.PPS[e].length),\n\tt.writeUint8Array(this.PPS[e].nalu);\n\tthis.ext && t.writeUint8Array(this.ext)\n},\nBoxParser.co64Box.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.chunk_offsets.length, this.writeHeader(t), t.writeUint32(this.chunk_offsets.length), e = 0; e < this.chunk_offsets.length; e++) t.writeUint64(this.chunk_offsets[e])\n},\nBoxParser.cslgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeInt32(this.compositionToDTSShift),\n\tt.writeInt32(this.leastDecodeToDisplayDelta),\n\tt.writeInt32(this.greatestDecodeToDisplayDelta),\n\tt.writeInt32(this.compositionStartTime),\n\tt.writeInt32(this.compositionEndTime)\n},\nBoxParser.cttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\t1 === this.version ? t.writeInt32(this.sample_offsets[e]) : t.writeUint32(this.sample_offsets[e])\n},\nBoxParser.drefBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.elngBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.extended_language.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.extended_language)\n},\nBoxParser.elstBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 12 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeUint32(i.segment_duration),\n\t\tt.writeInt32(i.media_time),\n\t\tt.writeInt16(i.media_rate_integer),\n\t\tt.writeInt16(i.media_rate_fraction)\n\t}\n},\nBoxParser.emsgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.scheme_id_uri),\n\tt.writeCString(this.value),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.presentation_time_delta),\n\tt.writeUint32(this.event_duration),\n\tt.writeUint32(this.id),\n\tt.writeUint8Array(this.message_data)\n},\nBoxParser.ftypBox.prototype.write = function(t) {\n\tthis.size = 8 + 4 * this.compatible_brands.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.major_brand, null, 4),\n\tt.writeUint32(this.minor_version);\n\tfor (var e = 0; e < this.compatible_brands.length; e++) t.writeString(this.compatible_brands[e], null, 4)\n},\nBoxParser.hdlrBox.prototype.write = function(t) {\n\tthis.size = 20 + this.name.length + 1,\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(0),\n\tt.writeString(this.handler, null, 4),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeCString(this.name)\n},\nBoxParser.hvcCBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.size = 23, e = 0; e < this.nalu_arrays.length; e++) for (this.size += 3, i = 0; i < this.nalu_arrays[e].length; i++) this.size += 2 + this.nalu_arrays[e][i].data.length;\n\tfor (this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc), t.writeUint32(this.general_profile_compatibility), t.writeUint8Array(this.general_constraint_indicator), t.writeUint8(this.general_level_idc), t.writeUint16(this.min_spatial_segmentation_idc + (15 << 24)), t.writeUint8(this.parallelismType + 252), t.writeUint8(this.chroma_format_idc + 252), t.writeUint8(this.bit_depth_luma_minus8 + 248), t.writeUint8(this.bit_depth_chroma_minus8 + 248), t.writeUint16(this.avgFrameRate), t.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne), t.writeUint8(this.nalu_arrays.length), e = 0; e < this.nalu_arrays.length; e++) for (t.writeUint8((this.nalu_arrays[e].completeness << 7) + this.nalu_arrays[e].nalu_type), t.writeUint16(this.nalu_arrays[e].length), i = 0; i < this.nalu_arrays[e].length; i++) t.writeUint16(this.nalu_arrays[e][i].data.length),\n\tt.writeUint8Array(this.nalu_arrays[e][i].data)\n},\nBoxParser.kindBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.schemeURI.length + 1 + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.schemeURI),\n\tt.writeCString(this.value)\n},\nBoxParser.mdhdBox.prototype.write = function(t) {\n\tthis.size = 20,\n\tthis.flags = 0,\n\tthis.version = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint16(this.language),\n\tt.writeUint16(0)\n},\nBoxParser.mehdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.fragment_duration)\n},\nBoxParser.mfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sequence_number)\n},\nBoxParser.mvhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 96,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(this.rate),\n\tt.writeUint16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32Array(this.matrix),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(this.next_track_id)\n},\nBoxParser.SampleEntry.prototype.writeHeader = function(t) {\n\tthis.size = 8,\n\tBoxParser.Box.prototype.writeHeader.call(this, t),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint16(this.data_reference_index)\n},\nBoxParser.SampleEntry.prototype.writeFooter = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t),\n\tthis.size += this.boxes[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.SampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tt.writeUint8Array(this.data),\n\tthis.size += this.data.length,\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.VisualSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 70,\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.width),\n\tt.writeUint16(this.height),\n\tt.writeUint32(this.horizresolution),\n\tt.writeUint32(this.vertresolution),\n\tt.writeUint32(0),\n\tt.writeUint16(this.frame_count),\n\tt.writeUint8(Math.min(31, this.compressorname.length)),\n\tt.writeString(this.compressorname, null, 31),\n\tt.writeUint16(this.depth),\n\tt.writeInt16(-1),\n\tthis.writeFooter(t)\n},\nBoxParser.AudioSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 20,\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.channel_count),\n\tt.writeUint16(this.samplesize),\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(this.samplerate << 16),\n\tthis.writeFooter(t)\n},\nBoxParser.stppSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1,\n\tt.writeCString(this.namespace),\n\tt.writeCString(this.schema_location),\n\tt.writeCString(this.auxiliary_mime_types),\n\tthis.writeFooter(t)\n},\nBoxParser.SampleGroupEntry.prototype.write = function(t) {\n\tt.writeUint8Array(this.data)\n},\nBoxParser.sbgpBox.prototype.write = function(t) {\n\tthis.version = 1,\n\tthis.flags = 0,\n\tthis.size = 12 + 8 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.grouping_type, null, 4),\n\tt.writeUint32(this.grouping_type_parameter),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeInt32(i.sample_count),\n\t\tt.writeInt32(i.group_description_index)\n\t}\n},\nBoxParser.sgpdBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.flags = 0, this.size = 12, e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && (0 === this.default_length && (this.size += 4), this.size += i.data.length);\n\tfor (this.writeHeader(t), t.writeString(this.grouping_type, null, 4), 1 === this.version && t.writeUint32(this.default_length), 2 <= this.version && t.writeUint32(this.default_sample_description_index), t.writeUint32(this.entries.length), e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && 0 === this.default_length && t.writeUint32(i.description_length),\n\ti.write(t)\n},\nBoxParser.sidxBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20 + 12 * this.references.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.reference_ID),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.earliest_presentation_time),\n\tt.writeUint32(this.first_offset),\n\tt.writeUint16(0),\n\tt.writeUint16(this.references.length);\n\tfor (var e = 0; e < this.references.length; e++) {\n\t\tvar i = this.references[e];\n\t\tt.writeUint32(i.reference_type << 31 | i.referenced_size),\n\t\tt.writeUint32(i.subsegment_duration),\n\t\tt.writeUint32(i.starts_with_SAP << 31 | i.SAP_type << 28 | i.SAP_delta_time)\n\t}\n},\nBoxParser.smhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.balance),\n\tt.writeUint16(0)\n},\nBoxParser.stcoBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.chunk_offsets.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.chunk_offsets.length),\n\tt.writeUint32Array(this.chunk_offsets)\n},\nBoxParser.stscBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 12 * this.first_chunk.length, this.writeHeader(t), t.writeUint32(this.first_chunk.length), e = 0; e < this.first_chunk.length; e++) t.writeUint32(this.first_chunk[e]),\n\tt.writeUint32(this.samples_per_chunk[e]),\n\tt.writeUint32(this.sample_description_index[e])\n},\nBoxParser.stsdBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 0, this.writeHeader(t), t.writeUint32(this.entries.length), this.size += 4, e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.stshBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.shadowed_sample_numbers.length, this.writeHeader(t), t.writeUint32(this.shadowed_sample_numbers.length), e = 0; e < this.shadowed_sample_numbers.length; e++) t.writeUint32(this.shadowed_sample_numbers[e]),\n\tt.writeUint32(this.sync_sample_numbers[e])\n},\nBoxParser.stssBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.sample_numbers.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_numbers.length),\n\tt.writeUint32Array(this.sample_numbers)\n},\nBoxParser.stszBox.prototype.write = function(t) {\n\tvar e, i = !0;\n\tif (this.version = 0, (this.flags = 0) < this.sample_sizes.length) for (e = 0; e + 1 < this.sample_sizes.length;) {\n\t\tif (this.sample_sizes[e + 1] !== this.sample_sizes[0]) {\n\t\t\ti = !1;\n\t\t\tbreak\n\t\t}\n\t\te++\n\t} else i = !1;\n\tthis.size = 8,\n\ti || (this.size += 4 * this.sample_sizes.length),\n\tthis.writeHeader(t),\n\ti ? t.writeUint32(this.sample_sizes[0]) : t.writeUint32(0),\n\tt.writeUint32(this.sample_sizes.length),\n\ti || t.writeUint32Array(this.sample_sizes)\n},\nBoxParser.sttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\tt.writeUint32(this.sample_deltas[e])\n},\nBoxParser.tfdtBox.prototype.write = function(t) {\n\tvar e = Math.pow(2, 32) - 1;\n\tthis.version = this.baseMediaDecodeTime > e ? 1 : 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\t1 === this.version && (this.size += 4),\n\tthis.writeHeader(t),\n\t1 === this.version ? t.writeUint64(this.baseMediaDecodeTime) : t.writeUint32(this.baseMediaDecodeTime)\n},\nBoxParser.tfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && (this.size += 8),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && (this.size += 4),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && t.writeUint64(this.base_data_offset),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && t.writeUint32(this.default_sample_description_index),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && t.writeUint32(this.default_sample_duration),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && t.writeUint32(this.default_sample_size),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && t.writeUint32(this.default_sample_flags)\n},\nBoxParser.tkhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 80,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(0),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeInt16(this.layer),\n\tt.writeInt16(this.alternate_group),\n\tt.writeInt16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeInt32Array(this.matrix),\n\tt.writeUint32(this.width),\n\tt.writeUint32(this.height)\n},\nBoxParser.trexBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(this.default_sample_description_index),\n\tt.writeUint32(this.default_sample_duration),\n\tt.writeUint32(this.default_sample_size),\n\tt.writeUint32(this.default_sample_flags)\n},\nBoxParser.trunBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_DURATION && (this.size += 4 * this.sample_duration.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.size += 4 * this.sample_size.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.size += 4 * this.sample_flags.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (this.size += 4 * this.sample_composition_time_offset.length),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_count),\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.data_offset_position = t.getPosition(), t.writeInt32(this.data_offset)),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && t.writeUint32(this.first_sample_flags);\n\tfor (var e = 0; e < this.sample_count; e++) this.flags & BoxParser.TRUN_FLAGS_DURATION && t.writeUint32(this.sample_duration[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && t.writeUint32(this.sample_size[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && t.writeUint32(this.sample_flags[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? t.writeUint32(this.sample_composition_time_offset[e]) : t.writeInt32(this.sample_composition_time_offset[e]))\n},\nBoxParser["url Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.location ? (this.flags = 0, this.size = this.location.length + 1) : (this.flags = 1, this.size = 0),\n\tthis.writeHeader(t),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser["urn Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0),\n\tthis.writeHeader(t),\n\tt.writeCString(this.name),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser.vmhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 8,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.graphicsmode),\n\tt.writeUint16Array(this.opcolor)\n},\nBoxParser.cttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].pts = t[i].dts + this.sample_offsets[r],\n\ti++\n},\nBoxParser.sttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].dts = 0 === i ? 0 : t[i - 1].dts + this.sample_deltas[r],\n\ti++\n},\nBoxParser.stcoBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.chunk_offsets.length; e++) t[e].offset = this.chunk_offsets[e]\n},\nBoxParser.stscBox.prototype.unpack = function(t) {\n\tfor (var e, i, r = 0,\n\ts = 0,\n\ta = 0; a < this.first_chunk.length; a++) for (e = 0; e < (a + 1 < this.first_chunk.length ? this.first_chunk[a + 1] : 1 / 0); e++) for (s++, i = 0; i < this.samples_per_chunk[a]; i++) {\n\t\tif (!t[r]) return;\n\t\tt[r].description_index = this.sample_description_index[a],\n\t\tt[r].chunk_index = s,\n\t\tr++\n\t}\n},\nBoxParser.stszBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.sample_sizes.length; e++) t[e].size = this.sample_sizes[e]\n},\nBoxParser.DIFF_BOXES_PROP_NAMES = ["boxes", "entries", "references", "subsamples", "items", "item_infos", "extents", "associations", "subsegments", "ranges", "seekLists", "seekPoints", "esd", "levels"],\nBoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES = ["compatible_brands", "matrix", "opcolor", "sample_counts", "sample_deltas", "first_chunk", "samples_per_chunk", "sample_sizes", "chunk_offsets", "sample_offsets", "sample_description_index", "sample_duration"],\nBoxParser.boxEqualFields = function(t, e) {\n\tif (t && !e) return ! 1;\n\tfor (var i in t) if (! (-1 < BoxParser.DIFF_BOXES_PROP_NAMES.indexOf(i) || t[i] instanceof BoxParser.Box || e[i] instanceof BoxParser.Box || void 0 === t[i] || void 0 === e[i] || "function" == typeof t[i] || "function" == typeof e[i] || t.subBoxNames && -1 < t.subBoxNames.indexOf(i.slice(0, 4)) || e.subBoxNames && -1 < e.subBoxNames.indexOf(i.slice(0, 4)) || "data" === i || "start" === i || "size" === i || "creation_time" === i || "modification_time" === i || -1 < BoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i) || t[i] === e[i])) return ! 1;\n\treturn ! 0\n},\nBoxParser.boxEqual = function(t, e) {\n\tif (!BoxParser.boxEqualFields(t, e)) return ! 1;\n\tfor (var i = 0; i < BoxParser.DIFF_BOXES_PROP_NAMES.length; i++) {\n\t\tvar r = BoxParser.DIFF_BOXES_PROP_NAMES[i];\n\t\tif (t[r] && e[r] && !BoxParser.boxEqual(t[r], e[r])) return ! 1\n\t}\n\treturn ! 0\n};\nvar VTTin4Parser = function() {};\nVTTin4Parser.prototype.parseSample = function(t) {\n\tfor (var e, i = new MP4BoxStream(t.buffer), r = []; ! i.isEos();)(e = BoxParser.parseOneBox(i, !1)).code === BoxParser.OK && "vttc" === e.box.type && r.push(e.box);\n\treturn r\n},\nVTTin4Parser.prototype.getText = function(t, e, i) {\n\tfunction s(t, e, i) {\n\t\treturn i = i || "0",\n\t\t(t += "").length >= e ? t: new Array(e - t.length + 1).join(i) + t\n\t}\n\tfunction r(t) {\n\t\tvar e = Math.floor(t / 3600),\n\t\ti = Math.floor((t - 3600 * e) / 60),\n\t\tr = Math.floor(t - 3600 * e - 60 * i),\n\t\tt = Math.floor(1e3 * (t - 3600 * e - 60 * i - r));\n\t\treturn s(e, 2) + ":" + s(i, 2) + ":" + s(r, 2) + "." + s(t, 3)\n\t}\n\tfor (var a = this.parseSample(i), n = "", o = 0; o < a.length; o++) {\n\t\tvar h = a[o];\n\t\tn += r(t) + " --\\x3e " + r(e) + "\\r\\n",\n\t\tn += h.payl.text\n\t}\n\treturn n\n};\nvar XMLSubtitlein4Parser = function() {};\nXMLSubtitlein4Parser.prototype.parseSample = function(t) {\n\tvar e, i = {\n\t\tresources: []\n\t},\n\tr = new MP4BoxStream(t.data.buffer);\n\tif (t.subsamples && 0 !== t.subsamples.length) {\n\t\tif (i.documentString = r.readString(t.subsamples[0].size), 1 < t.subsamples.length) for (e = 1; e < t.subsamples.length; e++) i.resources[e] = r.readUint8Array(t.subsamples[e].size)\n\t} else i.documentString = r.readString(t.data.length);\n\treturn "undefined" != typeof DOMParser && (i.document = (new DOMParser).parseFromString(i.documentString, "application/xml")),\n\ti\n};\nvar Textin4Parser = function() {};\nTextin4Parser.prototype.parseSample = function(t) {\n\treturn new MP4BoxStream(t.data.buffer).readString(t.data.length)\n},\nTextin4Parser.prototype.parseConfig = function(t) {\n\tt = new MP4BoxStream(t.buffer);\n\treturn t.readUint32(),\n\tt.readCString()\n},\n"undefined" != typeof exports && (exports.VTTin4Parser = VTTin4Parser, exports.XMLSubtitlein4Parser = XMLSubtitlein4Parser, exports.Textin4Parser = Textin4Parser);\nvar ISOFile = function(t) {\n\tthis.stream = t || new MultiBufferStream,\n\tthis.boxes = [],\n\tthis.mdats = [],\n\tthis.moofs = [],\n\tthis.isProgressive = !1,\n\tthis.moovStartFound = !1,\n\tthis.onMoovStart = null,\n\tthis.moovStartSent = !1,\n\tthis.onReady = null,\n\tthis.readySent = !1,\n\tthis.onSegment = null,\n\tthis.onSamples = null,\n\tthis.onError = null,\n\tthis.sampleListBuilt = !1,\n\tthis.fragmentedTracks = [],\n\tthis.extractedTracks = [],\n\tthis.isFragmentationInitialized = !1,\n\tthis.sampleProcessingStarted = !1,\n\tthis.nextMoofNumber = 0,\n\tthis.itemListBuilt = !1,\n\tthis.items = [],\n\tthis.entity_groups = [],\n\tthis.onSidx = null,\n\tthis.sidxSent = !1\n};\nISOFile.prototype.setSegmentOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.fragmentedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.segmentStream = null, r.nb_samples = 1e3, r.rapAlignement = !0, i && (i.nbSamples && (r.nb_samples = i.nbSamples), i.rapAlignement && (r.rapAlignement = i.rapAlignement)))\n},\nISOFile.prototype.unsetSegmentOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.fragmentedTracks.length; i++) this.fragmentedTracks[i].id == t && (e = i); - 1 < e && this.fragmentedTracks.splice(e, 1)\n},\nISOFile.prototype.setExtractionOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.extractedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.nb_samples = 1e3, r.samples = [], i && i.nbSamples && (r.nb_samples = i.nbSamples))\n},\nISOFile.prototype.unsetExtractionOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.extractedTracks.length; i++) this.extractedTracks[i].id == t && (e = i); - 1 < e && this.extractedTracks.splice(e, 1)\n},\nISOFile.prototype.parse = function() {\n\tvar t;\n\tif (!this.restoreParsePosition || this.restoreParsePosition()) for (;;) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) {\n\t\tif (!this.processIncompleteMdat()) return\n\t} else if (this.saveParsePosition && this.saveParsePosition(), (t = BoxParser.parseOneBox(this.stream, !1)).code === BoxParser.ERR_NOT_ENOUGH_DATA) {\n\t\tif (!this.processIncompleteBox) return;\n\t\tif (!this.processIncompleteBox(t)) return\n\t} else {\n\t\tvar e, i = "uuid" !== (e = t.box).type ? e.type: e.uuid;\n\t\tswitch (this.boxes.push(e), i) {\n\t\tcase "mdat":\n\t\t\tthis.mdats.push(e);\n\t\t\tbreak;\n\t\tcase "moof":\n\t\t\tthis.moofs.push(e);\n\t\t\tbreak;\n\t\tcase "moov":\n\t\t\tthis.moovStartFound = !0,\n\t\t\t0 === this.mdats.length && (this.isProgressive = !0);\n\t\tdefault:\n\t\t\tvoid 0 !== this[i] && Log.warn("ISOFile", "Duplicate Box of type: " + i + ", overriding previous occurrence"),\n\t\t\tthis[i] = e\n\t\t}\n\t\tthis.updateUsedBytes && this.updateUsedBytes(e, t)\n\t}\n},\nISOFile.prototype.checkBuffer = function(t) {\n\tif (null == t) throw "Buffer must be defined and non empty";\n\tif (void 0 === t.fileStart) throw "Buffer must have a fileStart property";\n\treturn 0 === t.byteLength ? (Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + t.fileStart + ")"), this.stream.logBufferLevel(), !1) : (Log.info("ISOFile", "Processing buffer (fileStart: " + t.fileStart + ")"), t.usedBytes = 0, this.stream.insertBuffer(t), this.stream.logBufferLevel(), !!this.stream.initialized() || (Log.warn("ISOFile", "Not ready to start parsing"), !1))\n},\nISOFile.prototype.appendBuffer = function(t, e) {\n\tvar i;\n\tif (this.checkBuffer(t)) return this.parse(),\n\tthis.moovStartFound && !this.moovStartSent && (this.moovStartSent = !0, this.onMoovStart && this.onMoovStart()),\n\tthis.moov ? (this.sampleListBuilt || (this.buildSampleLists(), this.sampleListBuilt = !0), this.updateSampleLists(), this.onReady && !this.readySent && (this.readySent = !0, this.onReady(this.getInfo())), this.processSamples(e), this.nextSeekPosition ? (i = this.nextSeekPosition, this.nextSeekPosition = void 0) : i = this.nextParsePosition, this.stream.getEndFilePositionAfter && (i = this.stream.getEndFilePositionAfter(i))) : i = this.nextParsePosition || 0,\n\tthis.sidx && this.onSidx && !this.sidxSent && (this.onSidx(this.sidx), this.sidxSent = !0),\n\tthis.meta && (this.flattenItemInfo && !this.itemListBuilt && (this.flattenItemInfo(), this.itemListBuilt = !0), this.processItems && this.processItems(this.onItem)),\n\tthis.stream.cleanBuffers && (Log.info("ISOFile", "Done processing buffer (fileStart: " + t.fileStart + ") - next buffer to fetch should have a fileStart position of " + i), this.stream.logBufferLevel(), this.stream.cleanBuffers(), this.stream.logBufferLevel(!0), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize())),\n\ti\n},\nISOFile.prototype.getInfo = function() {\n\tvar t, e, i, r, s, a, n = {},\n\to = new Date("1904-01-01T00:00:00Z").getTime();\n\tif (this.moov) for (n.hasMoov = !0, n.duration = this.moov.mvhd.duration, n.timescale = this.moov.mvhd.timescale, n.isFragmented = null != this.moov.mvex, n.isFragmented && this.moov.mvex.mehd && (n.fragment_duration = this.moov.mvex.mehd.fragment_duration), n.isProgressive = this.isProgressive, n.hasIOD = null != this.moov.iods, n.brands = [], n.brands.push(this.ftyp.major_brand), n.brands = n.brands.concat(this.ftyp.compatible_brands), n.created = new Date(o + 1e3 * this.moov.mvhd.creation_time), n.modified = new Date(o + 1e3 * this.moov.mvhd.modification_time), n.tracks = [], n.audioTracks = [], n.videoTracks = [], n.subtitleTracks = [], n.metadataTracks = [], n.hintTracks = [], n.otherTracks = [], t = 0; t < this.moov.traks.length; t++) {\n\t\tif (a = (i = this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0], r = {},\n\t\tn.tracks.push(r), r.id = i.tkhd.track_id, r.name = i.mdia.hdlr.name, r.references = [], i.tref) for (e = 0; e < i.tref.boxes.length; e++) s = {},\n\t\tr.references.push(s),\n\t\ts.type = i.tref.boxes[e].type,\n\t\ts.track_ids = i.tref.boxes[e].track_ids;\n\t\ti.edts && (r.edits = i.edts.elst.entries),\n\t\tr.created = new Date(o + 1e3 * i.tkhd.creation_time),\n\t\tr.modified = new Date(o + 1e3 * i.tkhd.modification_time),\n\t\tr.movie_duration = i.tkhd.duration,\n\t\tr.movie_timescale = n.timescale,\n\t\tr.layer = i.tkhd.layer,\n\t\tr.alternate_group = i.tkhd.alternate_group,\n\t\tr.volume = i.tkhd.volume,\n\t\tr.matrix = i.tkhd.matrix,\n\t\tr.track_width = i.tkhd.width / 65536,\n\t\tr.track_height = i.tkhd.height / 65536,\n\t\tr.timescale = i.mdia.mdhd.timescale,\n\t\tr.cts_shift = i.mdia.minf.stbl.cslg,\n\t\tr.duration = i.mdia.mdhd.duration,\n\t\tr.samples_duration = i.samples_duration,\n\t\tr.codec = a.getCodec(),\n\t\tr.kind = i.udta && i.udta.kinds.length ? i.udta.kinds[0] : {\n\t\t\tschemeURI: "",\n\t\t\tvalue: ""\n\t\t},\n\t\tr.language = i.mdia.elng ? i.mdia.elng.extended_language: i.mdia.mdhd.languageString,\n\t\tr.nb_samples = i.samples.length,\n\t\tr.size = i.samples_size,\n\t\tr.bitrate = 8 * r.size * r.timescale / r.samples_duration,\n\t\ta.isAudio() ? (r.type = "audio", n.audioTracks.push(r), r.audio = {},\n\t\tr.audio.sample_rate = a.getSampleRate(), r.audio.channel_count = a.getChannelCount(), r.audio.sample_size = a.getSampleSize()) : a.isVideo() ? (r.type = "video", n.videoTracks.push(r), r.video = {},\n\t\tr.video.width = a.getWidth(), r.video.height = a.getHeight()) : a.isSubtitle() ? (r.type = "subtitles", n.subtitleTracks.push(r)) : a.isHint() ? (r.type = "metadata", n.hintTracks.push(r)) : a.isMetadata() ? (r.type = "metadata", n.metadataTracks.push(r)) : (r.type = "metadata", n.otherTracks.push(r))\n\t} else n.hasMoov = !1;\n\tif (n.mime = "", n.hasMoov && n.tracks) {\n\t\tfor (n.videoTracks && 0 < n.videoTracks.length ? n.mime += \'video/mp4; codecs="\': n.audioTracks && 0 < n.audioTracks.length ? n.mime += \'audio/mp4; codecs="\': n.mime += \'application/mp4; codecs="\', t = 0; t < n.tracks.length; t++) 0 !== t && (n.mime += ","),\n\t\tn.mime += n.tracks[t].codec;\n\t\tn.mime += \'"; profiles="\',\n\t\tn.mime += this.ftyp.compatible_brands.join(),\n\t\tn.mime += \'"\'\n\t}\n\treturn n\n},\nISOFile.prototype.setNextSeekPositionFromSample = function(t) {\n\tt && (this.nextSeekPosition ? this.nextSeekPosition = Math.min(t.offset + t.alreadyRead, this.nextSeekPosition) : this.nextSeekPosition = t.offset + t.alreadyRead)\n},\nISOFile.prototype.processSamples = function(t) {\n\tvar e;\n\tif (this.sampleProcessingStarted) {\n\t\tif (this.isFragmentationInitialized && null !== this.onSegment) for (e = 0; e < this.fragmentedTracks.length; e++) for (var i = this.fragmentedTracks[e], r = i.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\tLog.debug("ISOFile", "Creating media fragment on track #" + i.id + " for sample " + r.nextSample);\n\t\t\tvar s = this.createFragment(i.id, r.nextSample, i.segmentStream);\n\t\t\tif (!s) break;\n\t\t\tif (i.segmentStream = s, r.nextSample++, (r.nextSample % i.nb_samples == 0 || t || r.nextSample >= r.samples.length) && (Log.info("ISOFile", "Sending fragmented data on track #" + i.id + " for samples [" + Math.max(0, r.nextSample - i.nb_samples) + "," + (r.nextSample - 1) + "]"), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize()), this.onSegment && this.onSegment(i.id, i.user, i.segmentStream.buffer, r.nextSample, t || r.nextSample >= r.samples.length), i.segmentStream = null, i !== this.fragmentedTracks[e])) break\n\t\t}\n\t\tif (null !== this.onSamples) for (e = 0; e < this.extractedTracks.length; e++) {\n\t\t\tvar a = this.extractedTracks[e];\n\t\t\tfor (r = a.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\t\tLog.debug("ISOFile", "Exporting on track #" + a.id + " sample #" + r.nextSample);\n\t\t\t\tvar n = this.getSample(r, r.nextSample);\n\t\t\t\tif (!n) {\n\t\t\t\t\tthis.setNextSeekPositionFromSample(r.samples[r.nextSample]);\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (r.nextSample++, a.samples.push(n), (r.nextSample % a.nb_samples == 0 || r.nextSample >= r.samples.length) && (Log.debug("ISOFile", "Sending samples on track #" + a.id + " for sample " + r.nextSample), this.onSamples && this.onSamples(a.id, a.user, a.samples), a.samples = [], a !== this.extractedTracks[e])) break\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getBox = function(t) {\n\tt = this.getBoxes(t, !0);\n\treturn t.length ? t[0] : null\n},\nISOFile.prototype.getBoxes = function(t, e) {\n\tvar i = [];\n\treturn ISOFile._sweep.call(this, t, i, e),\n\ti\n},\nISOFile._sweep = function(t, e, i) {\n\tfor (var r in this.type && this.type == t && e.push(this), this.boxes) {\n\t\tif (e.length && i) return;\n\t\tISOFile._sweep.call(this.boxes[r], t, e, i)\n\t}\n},\nISOFile.prototype.getTrackSamplesInfo = function(t) {\n\tt = this.getTrackById(t);\n\tif (t) return t.samples\n},\nISOFile.prototype.getTrackSample = function(t, e) {\n\tt = this.getTrackById(t);\n\treturn this.getSample(t, e)\n},\nISOFile.prototype.releaseUsedSamples = function(t, e) {\n\tvar i = 0,\n\tr = this.getTrackById(t);\n\tr.lastValidSample || (r.lastValidSample = 0);\n\tfor (var s = r.lastValidSample; s < e; s++) i += this.releaseSample(r, s);\n\tLog.info("ISOFile", "Track #" + t + " released samples up to " + e + " (released size: " + i + ", remaining: " + this.samplesDataSize + ")"),\n\tr.lastValidSample = e\n},\nISOFile.prototype.start = function() {\n\tthis.sampleProcessingStarted = !0,\n\tthis.processSamples(!1)\n},\nISOFile.prototype.stop = function() {\n\tthis.sampleProcessingStarted = !1\n},\nISOFile.prototype.flush = function() {\n\tLog.info("ISOFile", "Flushing remaining samples"),\n\tthis.updateSampleLists(),\n\tthis.processSamples(!0),\n\tthis.stream.cleanBuffers(),\n\tthis.stream.logBufferLevel(!0)\n},\nISOFile.prototype.seekTrack = function(t, e, i) {\n\tvar r, s, a, n, o = 0,\n\th = 0;\n\tif (0 === i.samples.length) return Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0"),\n\t{\n\t\toffset: 0,\n\t\ttime: 0\n\t};\n\tfor (r = 0; r < i.samples.length; r++) {\n\t\tif (s = i.samples[r], 0 === r) h = 0,\n\t\tn = s.timescale;\n\t\telse if (s.cts > t * s.timescale) {\n\t\t\th = r - 1;\n\t\t\tbreak\n\t\t}\n\t\te && s.is_sync && (o = r)\n\t}\n\tfor (e && (h = o), t = i.samples[h].cts, i.nextSample = h; i.samples[h].alreadyRead === i.samples[h].size && i.samples[h + 1];) h++;\n\treturn a = i.samples[h].offset + i.samples[h].alreadyRead,\n\tLog.info("ISOFile", "Seeking to " + (e ? "RAP": "") + " sample #" + i.nextSample + " on track " + i.tkhd.track_id + ", time " + Log.getDurationString(t, n) + " and offset: " + a),\n\t{\n\t\toffset: a,\n\t\ttime: t / n\n\t}\n},\nISOFile.prototype.getTrackDuration = function(t) {\n\treturn t.samples ? ((t = t.samples[t.samples.length - 1]).cts + t.duration) / t.timescale: 1 / 0\n},\nISOFile.prototype.seek = function(t, e) {\n\tvar i, r, s = this.moov,\n\ta = {\n\t\toffset: 1 / 0,\n\t\ttime: 1 / 0\n\t};\n\tif (this.moov) {\n\t\tfor (r = 0; r < s.traks.length; r++) i = s.traks[r],\n\t\tt > this.getTrackDuration(i) || ((i = this.seekTrack(t, e, i)).offset < a.offset && (a.offset = i.offset), i.time < a.time && (a.time = i.time));\n\t\treturn Log.info("ISOFile", "Seeking at time " + Log.getDurationString(a.time, 1) + " needs a buffer with a fileStart position of " + a.offset),\n\t\ta.offset === 1 / 0 ? a = {\n\t\t\toffset: this.nextParsePosition,\n\t\t\ttime: 0\n\t\t}: a.offset = this.stream.getEndFilePositionAfter(a.offset),\n\t\tLog.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + a.offset),\n\t\ta\n\t}\n\tthrow "Cannot seek: moov not received!"\n},\nISOFile.prototype.equal = function(t) {\n\tfor (var e = 0; e < this.boxes.length && e < t.boxes.length;) {\n\t\tvar i = this.boxes[e],\n\t\tr = t.boxes[e];\n\t\tif (!BoxParser.boxEqual(i, r)) return ! 1;\n\t\te++\n\t}\n\treturn ! 0\n},\n"undefined" != typeof exports && (exports.ISOFile = ISOFile),\nISOFile.prototype.lastBoxStartPosition = 0,\nISOFile.prototype.parsingMdat = null,\nISOFile.prototype.nextParsePosition = 0,\nISOFile.prototype.discardMdatData = !1,\nISOFile.prototype.processIncompleteBox = function(t) {\n\tvar e;\n\treturn "mdat" === t.type ? (e = new BoxParser[t.type + "Box"](t.size), this.parsingMdat = e, this.boxes.push(e), this.mdats.push(e), e.start = t.start, e.hdr_size = t.hdr_size, this.stream.addUsedBytes(e.hdr_size), this.lastBoxStartPosition = e.start + e.size, this.stream.seek(e.start + e.size, !1, this.discardMdatData) ? !(this.parsingMdat = null) : (this.moovStartFound ? this.nextParsePosition = this.stream.findEndContiguousBuf() : this.nextParsePosition = e.start + e.size, !1)) : ("moov" === t.type && (this.moovStartFound = !0, 0 === this.mdats.length && (this.isProgressive = !0)), !!this.stream.mergeNextBuffer && this.stream.mergeNextBuffer() ? (this.nextParsePosition = this.stream.getEndPosition(), !0) : (!t.type || this.moovStartFound ? this.nextParsePosition = this.stream.getEndPosition() : this.nextParsePosition = this.stream.getPosition() + t.size, !1))\n},\nISOFile.prototype.hasIncompleteMdat = function() {\n\treturn null !== this.parsingMdat\n},\nISOFile.prototype.processIncompleteMdat = function() {\n\tvar t = this.parsingMdat;\n\treturn this.stream.seek(t.start + t.size, !1, this.discardMdatData) ? (Log.debug("ISOFile", "Found \'mdat\' end in buffered data"), !(this.parsingMdat = null)) : (this.nextParsePosition = this.stream.findEndContiguousBuf(), !1)\n},\nISOFile.prototype.restoreParsePosition = function() {\n\treturn this.stream.seek(this.lastBoxStartPosition, !0, this.discardMdatData)\n},\nISOFile.prototype.saveParsePosition = function() {\n\tthis.lastBoxStartPosition = this.stream.getPosition()\n},\nISOFile.prototype.updateUsedBytes = function(t, e) {\n\tthis.stream.addUsedBytes && ("mdat" === t.type ? (this.stream.addUsedBytes(t.hdr_size), this.discardMdatData && this.stream.addUsedBytes(t.size - t.hdr_size)) : this.stream.addUsedBytes(t.size))\n},\nISOFile.prototype.add = BoxParser.Box.prototype.add,\nISOFile.prototype.addBox = BoxParser.Box.prototype.addBox,\nISOFile.prototype.init = function(t) {\n\tvar e = t || {},\n\tt = (this.add("ftyp").set("major_brand", e.brands && e.brands[0] || "iso4").set("minor_version", 0).set("compatible_brands", e.brands || ["iso4"]), this.add("moov"));\n\treturn t.add("mvhd").set("timescale", e.timescale || 600).set("rate", e.rate || 65536).set("creation_time", 0).set("modification_time", 0).set("duration", e.duration || 0).set("volume", e.width ? 0 : 256).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("next_track_id", 1),\n\tt.add("mvex"),\n\tthis\n},\nISOFile.prototype.addTrack = function(t) {\n\tthis.moov || this.init(t);\n\tvar e = t || {};\n\te.width = e.width || 320,\n\te.height = e.height || 320,\n\te.id = e.id || this.moov.mvhd.next_track_id,\n\te.type = e.type || "avc1";\n\tvar i = this.moov.add("trak");\n\tthis.moov.mvhd.next_track_id = e.id + 1,\n\ti.add("tkhd").set("flags", BoxParser.TKHD_FLAG_ENABLED | BoxParser.TKHD_FLAG_IN_MOVIE | BoxParser.TKHD_FLAG_IN_PREVIEW).set("creation_time", 0).set("modification_time", 0).set("track_id", e.id).set("duration", e.duration || 0).set("layer", e.layer || 0).set("alternate_group", 0).set("volume", 1).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("width", e.width << 16).set("height", e.height << 16);\n\tt = i.add("mdia");\n\tt.add("mdhd").set("creation_time", 0).set("modification_time", 0).set("timescale", e.timescale || 1).set("duration", e.media_duration || 0).set("language", e.language || "und"),\n\tt.add("hdlr").set("handler", e.hdlr || "vide").set("name", e.name || "Track created with MP4Box.js"),\n\tt.add("elng").set("extended_language", e.language || "fr-FR");\n\tvar r = t.add("minf");\n\tif (void 0 !== BoxParser[e.type + "SampleEntry"]) {\n\t\tvar s = new BoxParser[e.type + "SampleEntry"];\n\t\ts.data_reference_index = 1;\n\t\tvar a, n, o = "";\n\t\tfor (a in BoxParser.sampleEntryCodes) for (var h = BoxParser.sampleEntryCodes[a], d = 0; d < h.length; d++) if (-1 < h.indexOf(e.type)) {\n\t\t\to = a;\n\t\t\tbreak\n\t\t}\n\t\tswitch (o) {\n\t\tcase "Visual":\n\t\t\tr.add("vmhd").set("graphicsmode", 0).set("opcolor", [0, 0, 0]),\n\t\t\ts.set("width", e.width).set("height", e.height).set("horizresolution", 72 << 16).set("vertresolution", 72 << 16).set("frame_count", 1).set("compressorname", e.type + " Compressor").set("depth", 24),\n\t\t\te.avcDecoderConfigRecord ? ((n = new BoxParser.avcCBox).parse(new MP4BoxStream(e.avcDecoderConfigRecord)), s.addBox(n)) : e.hevcDecoderConfigRecord && ((n = new BoxParser.hvcCBox).parse(new MP4BoxStream(e.hevcDecoderConfigRecord)), s.addBox(n));\n\t\t\tbreak;\n\t\tcase "Audio":\n\t\t\tr.add("smhd").set("balance", e.balance || 0),\n\t\t\ts.set("channel_count", e.channel_count || 2).set("samplesize", e.samplesize || 16).set("samplerate", e.samplerate || 65536);\n\t\t\tbreak;\n\t\tcase "Hint":\n\t\t\tr.add("hmhd");\n\t\t\tbreak;\n\t\tcase "Subtitle":\n\t\t\tr.add("sthd"),\n\t\t\t"stpp" === e.type && s.set("namespace", e.namespace || "nonamespace").set("schema_location", e.schema_location || "").set("auxiliary_mime_types", e.auxiliary_mime_types || "");\n\t\t\tbreak;\n\t\tcase "Metadata":\n\t\tcase "System":\n\t\tdefault:\n\t\t\tr.add("nmhd")\n\t\t}\n\t\te.description && s.addBox(e.description),\n\t\te.description_boxes && e.description_boxes.forEach(function(t) {\n\t\t\ts.addBox(t)\n\t\t}),\n\t\tr.add("dinf").add("dref").addEntry((new BoxParser["url Box"]).set("flags", 1));\n\t\tt = r.add("stbl");\n\t\treturn t.add("stsd").addEntry(s),\n\t\tt.add("stts").set("sample_counts", []).set("sample_deltas", []),\n\t\tt.add("stsc").set("first_chunk", []).set("samples_per_chunk", []).set("sample_description_index", []),\n\t\tt.add("stco").set("chunk_offsets", []),\n\t\tt.add("stsz").set("sample_sizes", []),\n\t\tthis.moov.mvex.add("trex").set("track_id", e.id).set("default_sample_description_index", e.default_sample_description_index || 1).set("default_sample_duration", e.default_sample_duration || 0).set("default_sample_size", e.default_sample_size || 0).set("default_sample_flags", e.default_sample_flags || 0),\n\t\tthis.buildTrakSampleLists(i),\n\t\te.id\n\t}\n},\nBoxParser.Box.prototype.computeSize = function(t) {\n\tt = t || new DataStream;\n\tt.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t)\n},\nISOFile.prototype.addSample = function(t, e, i) {\n\tvar r = i || {},\n\ti = {},\n\tt = this.getTrackById(t);\n\tif (null !== t) {\n\t\ti.number = t.samples.length,\n\t\ti.track_id = t.tkhd.track_id,\n\t\ti.timescale = t.mdia.mdhd.timescale,\n\t\ti.description_index = r.sample_description_index ? r.sample_description_index - 1 : 0,\n\t\ti.description = t.mdia.minf.stbl.stsd.entries[i.description_index],\n\t\ti.data = e,\n\t\ti.size = e.byteLength,\n\t\ti.alreadyRead = i.size,\n\t\ti.duration = r.duration || 1,\n\t\ti.cts = r.cts || 0,\n\t\ti.dts = r.dts || 0,\n\t\ti.is_sync = r.is_sync || !1,\n\t\ti.is_leading = r.is_leading || 0,\n\t\ti.depends_on = r.depends_on || 0,\n\t\ti.is_depended_on = r.is_depended_on || 0,\n\t\ti.has_redundancy = r.has_redundancy || 0,\n\t\ti.degradation_priority = r.degradation_priority || 0,\n\t\ti.offset = 0,\n\t\ti.subsamples = r.subsamples,\n\t\tt.samples.push(i),\n\t\tt.samples_size += i.size,\n\t\tt.samples_duration += i.duration,\n\t\tvoid 0 === t.first_dts && (t.first_dts = r.dts),\n\t\tthis.processSamples();\n\t\tr = this.createSingleSampleMoof(i);\n\t\treturn this.addBox(r),\n\t\tr.computeSize(),\n\t\tr.trafs[0].truns[0].data_offset = r.size + 8,\n\t\tthis.add("mdat").data = new Uint8Array(e),\n\t\ti\n\t}\n},\nISOFile.prototype.createSingleSampleMoof = function(t) {\n\tvar e = 0,\n\te = t.is_sync ? 1 << 25 : 65536,\n\ti = new BoxParser.moofBox;\n\ti.add("mfhd").set("sequence_number", this.nextMoofNumber),\n\tthis.nextMoofNumber++;\n\tvar r = i.add("traf"),\n\ts = this.getTrackById(t.track_id);\n\treturn r.add("tfhd").set("track_id", t.track_id).set("flags", BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\tr.add("tfdt").set("baseMediaDecodeTime", t.dts - (s.first_dts || 0)),\n\tr.add("trun").set("flags", BoxParser.TRUN_FLAGS_DATA_OFFSET | BoxParser.TRUN_FLAGS_DURATION | BoxParser.TRUN_FLAGS_SIZE | BoxParser.TRUN_FLAGS_FLAGS | BoxParser.TRUN_FLAGS_CTS_OFFSET).set("data_offset", 0).set("first_sample_flags", 0).set("sample_count", 1).set("sample_duration", [t.duration]).set("sample_size", [t.size]).set("sample_flags", [e]).set("sample_composition_time_offset", [t.cts - t.dts]),\n\ti\n},\nISOFile.prototype.lastMoofIndex = 0,\nISOFile.prototype.samplesDataSize = 0,\nISOFile.prototype.resetTables = function() {\n\tvar t, e;\n\tfor (this.initial_duration = this.moov.mvhd.duration, t = this.moov.mvhd.duration = 0; t < this.moov.traks.length; t++) { (e = this.moov.traks[t]).tkhd.duration = 0,\n\t\te.mdia.mdhd.duration = 0,\n\t\t(e.mdia.minf.stbl.stco || e.mdia.minf.stbl.co64).chunk_offsets = [],\n\t\t(i = e.mdia.minf.stbl.stsc).first_chunk = [],\n\t\ti.samples_per_chunk = [],\n\t\ti.sample_description_index = [],\n\t\t(e.mdia.minf.stbl.stsz || e.mdia.minf.stbl.stz2).sample_sizes = [],\n\t\t(i = e.mdia.minf.stbl.stts).sample_counts = [],\n\t\ti.sample_deltas = [],\n\t\t(i = e.mdia.minf.stbl.ctts) && (i.sample_counts = [], i.sample_offsets = []),\n\t\ti = e.mdia.minf.stbl.stss;\n\t\tvar i = e.mdia.minf.stbl.boxes.indexOf(i); - 1 != i && (e.mdia.minf.stbl.boxes[i] = null)\n\t}\n},\nISOFile.initSampleGroups = function(t, e, i, r, s) {\n\tvar a, n, o, h;\n\tfunction d(t, e, i) {\n\t\tthis.grouping_type = t,\n\t\tthis.grouping_type_parameter = e,\n\t\tthis.sbgp = i,\n\t\tthis.last_sample_in_run = -1,\n\t\tthis.entry_index = -1\n\t}\n\tfor (e && (e.sample_groups_info = []), t.sample_groups_info || (t.sample_groups_info = []), n = 0; n < i.length; n++) {\n\t\tfor (h = i[n].grouping_type + "/" + i[n].grouping_type_parameter, o = new d(i[n].grouping_type, i[n].grouping_type_parameter, i[n]), e && (e.sample_groups_info[h] = o), t.sample_groups_info[h] || (t.sample_groups_info[h] = o), a = 0; a < r.length; a++) r[a].grouping_type === i[n].grouping_type && (o.description = r[a], o.description.used = !0);\n\t\tif (s) for (a = 0; a < s.length; a++) s[a].grouping_type === i[n].grouping_type && (o.fragment_description = s[a], o.fragment_description.used = !0, o.is_fragment = !0)\n\t}\n\tif (e) {\n\t\tif (s) for (n = 0; n < s.length; n++) ! s[n].used && 2 <= s[n].version && (h = s[n].grouping_type + "/0", (o = new d(s[n].grouping_type, 0)).is_fragment = !0, e.sample_groups_info[h] || (e.sample_groups_info[h] = o))\n\t} else for (n = 0; n < r.length; n++) ! r[n].used && 2 <= r[n].version && (h = r[n].grouping_type + "/0", o = new d(r[n].grouping_type, 0), t.sample_groups_info[h] || (t.sample_groups_info[h] = o))\n},\nISOFile.setSampleGroupProperties = function(t, e, i, r) {\n\tvar s, a, n;\n\tfor (s in e.sample_groups = [], r) e.sample_groups[s] = {},\n\te.sample_groups[s].grouping_type = r[s].grouping_type,\n\te.sample_groups[s].grouping_type_parameter = r[s].grouping_type_parameter,\n\ti >= r[s].last_sample_in_run && (r[s].last_sample_in_run < 0 && (r[s].last_sample_in_run = 0), r[s].entry_index++, r[s].entry_index <= r[s].sbgp.entries.length - 1 && (r[s].last_sample_in_run += r[s].sbgp.entries[r[s].entry_index].sample_count)),\n\tr[s].entry_index <= r[s].sbgp.entries.length - 1 ? e.sample_groups[s].group_description_index = r[s].sbgp.entries[r[s].entry_index].group_description_index: e.sample_groups[s].group_description_index = -1,\n\t0 !== e.sample_groups[s].group_description_index && (n = r[s].fragment_description || r[s].description, 0 < e.sample_groups[s].group_description_index ? (a = 65535 < e.sample_groups[s].group_description_index ? (e.sample_groups[s].group_description_index >> 16) - 1 : e.sample_groups[s].group_description_index - 1, n && 0 <= a && (e.sample_groups[s].description = n.entries[a])) : n && 2 <= n.version && 0 < n.default_group_description_index && (e.sample_groups[s].description = n.entries[n.default_group_description_index - 1]))\n},\nISOFile.process_sdtp = function(t, e, i) {\n\te && (t ? (e.is_leading = t.is_leading[i], e.depends_on = t.sample_depends_on[i], e.is_depended_on = t.sample_is_depended_on[i], e.has_redundancy = t.sample_has_redundancy[i]) : (e.is_leading = 0, e.depends_on = 0, e.is_depended_on = 0, e.has_redundancy = 0))\n},\nISOFile.prototype.buildSampleLists = function() {\n\tfor (var t, e = 0; e < this.moov.traks.length; e++) t = this.moov.traks[e],\n\tthis.buildTrakSampleLists(t)\n},\nISOFile.prototype.buildTrakSampleLists = function(t) {\n\tvar e, i, r, s, a, n, o, h, d, l, p, f, u, _, c, m, x, g, y, B, S, P, U, b;\n\tif (t.samples = [], t.samples_duration = 0, t.samples_size = 0, i = t.mdia.minf.stbl.stco || t.mdia.minf.stbl.co64, r = t.mdia.minf.stbl.stsc, s = t.mdia.minf.stbl.stsz || t.mdia.minf.stbl.stz2, a = t.mdia.minf.stbl.stts, n = t.mdia.minf.stbl.ctts, o = t.mdia.minf.stbl.stss, h = t.mdia.minf.stbl.stsd, d = t.mdia.minf.stbl.subs, f = t.mdia.minf.stbl.stdp, l = t.mdia.minf.stbl.sbgps, p = t.mdia.minf.stbl.sgpds, S = B = y = g = -1, b = U = P = 0, ISOFile.initSampleGroups(t, null, l, p), void 0 !== s) {\n\t\tfor (e = 0; e < s.sample_sizes.length; e++) {\n\t\t\tvar v = {};\n\t\t\tv.number = e,\n\t\t\tv.track_id = t.tkhd.track_id,\n\t\t\tv.timescale = t.mdia.mdhd.timescale,\n\t\t\tv.alreadyRead = 0,\n\t\t\t(t.samples[e] = v).size = s.sample_sizes[e],\n\t\t\tt.samples_size += v.size,\n\t\t\t0 === e ? (_ = 1, u = 0, v.chunk_index = _, v.chunk_run_index = u, x = r.samples_per_chunk[u], m = 0, c = u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0) : e < x ? (v.chunk_index = _, v.chunk_run_index = u) : (_++, m = 0, (v.chunk_index = _) <= c || (c = ++u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0), v.chunk_run_index = u, x += r.samples_per_chunk[u]),\n\t\t\tv.description_index = r.sample_description_index[v.chunk_run_index] - 1,\n\t\t\tv.description = h.entries[v.description_index],\n\t\t\tv.offset = i.chunk_offsets[v.chunk_index - 1] + m,\n\t\t\tm += v.size,\n\t\t\tg < e && (y++, g < 0 && (g = 0), g += a.sample_counts[y]),\n\t\t\t0 < e ? (t.samples[e - 1].duration = a.sample_deltas[y], t.samples_duration += t.samples[e - 1].duration, v.dts = t.samples[e - 1].dts + t.samples[e - 1].duration) : v.dts = 0,\n\t\t\tn ? (B <= e && (S++, B < 0 && (B = 0), B += n.sample_counts[S]), v.cts = t.samples[e].dts + n.sample_offsets[S]) : v.cts = v.dts,\n\t\t\to ? (e == o.sample_numbers[P] - 1 ? (v.is_sync = !0, P++) : (v.is_sync = !1, v.degradation_priority = 0), d && d.entries[U].sample_delta + b == e + 1 && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta, U++)) : v.is_sync = !0,\n\t\t\tISOFile.process_sdtp(t.mdia.minf.stbl.sdtp, v, v.number),\n\t\t\tv.degradation_priority = f ? f.priority[e] : 0,\n\t\t\td && d.entries[U].sample_delta + b == e && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta),\n\t\t\t(0 < l.length || 0 < p.length) && ISOFile.setSampleGroupProperties(t, v, e, t.sample_groups_info)\n\t\t}\n\t\t0 < e && (t.samples[e - 1].duration = Math.max(t.mdia.mdhd.duration - t.samples[e - 1].dts, 0), t.samples_duration += t.samples[e - 1].duration)\n\t}\n},\nISOFile.prototype.updateSampleLists = function() {\n\tvar t, e, i, r, s, a, n, o, h, d, l, p;\n\tif (void 0 !== this.moov) for (; this.lastMoofIndex < this.moofs.length;) if (n = this.moofs[this.lastMoofIndex], this.lastMoofIndex++, "moof" == n.type) for (o = n, t = 0; t < o.trafs.length; t++) {\n\t\tfor (h = o.trafs[t], d = this.getTrackById(h.tfhd.track_id), l = this.getTrexById(h.tfhd.track_id), e = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? h.tfhd.default_sample_description_index: l ? l.default_sample_description_index: 1, i = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? h.tfhd.default_sample_duration: l ? l.default_sample_duration: 0, r = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? h.tfhd.default_sample_size: l ? l.default_sample_size: 0, s = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? h.tfhd.default_sample_flags: l ? l.default_sample_flags: 0, (h.sample_number = 0) < h.sbgps.length && ISOFile.initSampleGroups(d, h, h.sbgps, d.mdia.minf.stbl.sgpds, h.sgpds), y = 0; y < h.truns.length; y++) for (var f = h.truns[y], u = 0; u < f.sample_count; u++) { (p = {}).moof_number = this.lastMoofIndex,\n\t\t\tp.number_in_traf = h.sample_number,\n\t\t\th.sample_number++,\n\t\t\tp.number = d.samples.length,\n\t\t\th.first_sample_index = d.samples.length,\n\t\t\td.samples.push(p),\n\t\t\tp.track_id = d.tkhd.track_id,\n\t\t\tp.timescale = d.mdia.mdhd.timescale,\n\t\t\tp.description_index = e - 1,\n\t\t\tp.description = d.mdia.minf.stbl.stsd.entries[p.description_index],\n\t\t\tp.size = r,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_SIZE && (p.size = f.sample_size[u]),\n\t\t\td.samples_size += p.size,\n\t\t\tp.duration = i,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_DURATION && (p.duration = f.sample_duration[u]),\n\t\t\td.samples_duration += p.duration,\n\t\t\td.first_traf_merged || 0 < u ? p.dts = d.samples[d.samples.length - 2].dts + d.samples[d.samples.length - 2].duration: (h.tfdt ? p.dts = h.tfdt.baseMediaDecodeTime: p.dts = 0, d.first_traf_merged = !0),\n\t\t\tp.cts = p.dts,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (p.cts = p.dts + f.sample_composition_time_offset[u]),\n\t\t\tx = s,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_FLAGS ? x = f.sample_flags[u] : 0 === u && f.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (x = f.first_sample_flags),\n\t\t\tp.is_sync = !(x >> 16 & 1),\n\t\t\tp.is_leading = x >> 26 & 3,\n\t\t\tp.depends_on = x >> 24 & 3,\n\t\t\tp.is_depended_on = x >> 22 & 3,\n\t\t\tp.has_redundancy = x >> 20 & 3,\n\t\t\tp.degradation_priority = 65535 & x;\n\t\t\tvar _ = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET),\n\t\t\tc = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\t\t\tm = !!(f.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET),\n\t\t\tx = 0,\n\t\t\tx = _ ? h.tfhd.base_data_offset: c || 0 === y ? o.start: a;\n\t\t\tp.offset = 0 === y && 0 === u ? m ? x + f.data_offset: x: a,\n\t\t\ta = p.offset + p.size,\n\t\t\t(0 < h.sbgps.length || 0 < h.sgpds.length || 0 < d.mdia.minf.stbl.sbgps.length || 0 < d.mdia.minf.stbl.sgpds.length) && ISOFile.setSampleGroupProperties(d, p, p.number_in_traf, h.sample_groups_info)\n\t\t}\n\t\tif (h.subs) {\n\t\t\td.has_fragment_subsamples = !0;\n\t\t\tfor (var g = h.first_sample_index,\n\t\t\ty = 0; y < h.subs.entries.length; y++) g += h.subs.entries[y].sample_delta,\n\t\t\t(p = d.samples[g - 1]).subsamples = h.subs.entries[y].subsamples\n\t\t}\n\t}\n},\nISOFile.prototype.getSample = function(t, e) {\n\tvar i, r = t.samples[e];\n\tif (!this.moov) return null;\n\tif (r.data) {\n\t\tif (r.alreadyRead == r.size) return r\n\t} else r.data = new Uint8Array(r.size),\n\tr.alreadyRead = 0,\n\tthis.samplesDataSize += r.size,\n\tLog.debug("ISOFile", "Allocating sample #" + e + " on track #" + t.tkhd.track_id + " of size " + r.size + " (total: " + this.samplesDataSize + ")");\n\tfor (;;) {\n\t\tvar s = this.stream.findPosition(!0, r.offset + r.alreadyRead, !1);\n\t\tif (! (-1 < s)) return null;\n\t\ts = (i = this.stream.buffers[s]).byteLength - (r.offset + r.alreadyRead - i.fileStart);\n\t\tif (r.size - r.alreadyRead <= s) return Log.debug("ISOFile", "Getting sample #" + e + " data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + (r.size - r.alreadyRead) + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, r.size - r.alreadyRead),\n\t\ti.usedBytes += r.size - r.alreadyRead,\n\t\tthis.stream.logBufferLevel(),\n\t\tr.alreadyRead = r.size,\n\t\tr;\n\t\tif (0 == s) return null;\n\t\tLog.debug("ISOFile", "Getting sample #" + e + " partial data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + s + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, s),\n\t\tr.alreadyRead += s,\n\t\ti.usedBytes += s,\n\t\tthis.stream.logBufferLevel()\n\t}\n},\nISOFile.prototype.releaseSample = function(t, e) {\n\te = t.samples[e];\n\treturn e.data ? (this.samplesDataSize -= e.size, e.data = null, e.alreadyRead = 0, e.size) : 0\n},\nISOFile.prototype.getAllocatedSampleDataSize = function() {\n\treturn this.samplesDataSize\n},\nISOFile.prototype.getCodecs = function() {\n\tfor (var t = "",\n\te = 0; e < this.moov.traks.length; e++) 0 < e && (t += ","),\n\tt += this.moov.traks[e].mdia.minf.stbl.stsd.entries[0].getCodec();\n\treturn t\n},\nISOFile.prototype.getTrexById = function(t) {\n\tvar e;\n\tif (!this.moov || !this.moov.mvex) return null;\n\tfor (e = 0; e < this.moov.mvex.trexs.length; e++) {\n\t\tvar i = this.moov.mvex.trexs[e];\n\t\tif (i.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.getTrackById = function(t) {\n\tif (void 0 === this.moov) return null;\n\tfor (var e = 0; e < this.moov.traks.length; e++) {\n\t\tvar i = this.moov.traks[e];\n\t\tif (i.tkhd.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.itemsDataSize = 0,\nISOFile.prototype.flattenItemInfo = function() {\n\tvar t = this.items,\n\te = this.entity_groups,\n\ti = this.meta;\n\tif (null != i && void 0 !== i.hdlr && void 0 !== i.iinf) {\n\t\tfor (d = 0; d < i.iinf.item_infos.length; d++)(s = {}).id = i.iinf.item_infos[d].item_ID,\n\t\t(t[s.id] = s).ref_to = [],\n\t\ts.name = i.iinf.item_infos[d].item_name,\n\t\t0 < i.iinf.item_infos[d].protection_index && (s.protection = i.ipro.protections[i.iinf.item_infos[d].protection_index - 1]),\n\t\ti.iinf.item_infos[d].item_type ? s.type = i.iinf.item_infos[d].item_type: s.type = "mime",\n\t\ts.content_type = i.iinf.item_infos[d].content_type,\n\t\ts.content_encoding = i.iinf.item_infos[d].content_encoding,\n\t\ts.item_uri_type = i.iinf.item_infos[d].item_uri_type;\n\t\tif (i.grpl) for (d = 0; d < i.grpl.boxes.length; d++) entity_group = {},\n\t\tentity_group.id = i.grpl.boxes[d].group_id,\n\t\tentity_group.entity_ids = i.grpl.boxes[d].entity_ids,\n\t\tentity_group.type = i.grpl.boxes[d].type,\n\t\te[entity_group.id] = entity_group;\n\t\tif (i.iloc) for (d = 0; d < i.iloc.items.length; d++) {\n\t\t\tvar r = i.iloc.items[d],\n\t\t\ts = t[r.item_ID];\n\t\t\tswitch (0 !== r.data_reference_index && (Log.warn("Item storage with reference to other files: not supported"), s.source = i.dinf.boxes[r.data_reference_index - 1]), r.construction_method) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tLog.warn("Item storage with construction_method : not supported")\n\t\t\t}\n\t\t\tfor (s.extents = [], n = s.size = 0; n < r.extents.length; n++) s.extents[n] = {},\n\t\t\ts.extents[n].offset = r.extents[n].extent_offset + r.base_offset,\n\t\t\t1 == r.construction_method && (s.extents[n].offset += i.idat.start + i.idat.hdr_size),\n\t\t\ts.extents[n].length = r.extents[n].extent_length,\n\t\t\ts.extents[n].alreadyRead = 0,\n\t\t\ts.size += s.extents[n].length\n\t\t}\n\t\tif (i.pitm && (t[i.pitm.item_id].primary = !0), i.iref) for (d = 0; d < i.iref.references.length; d++) for (var a = i.iref.references[d], n = 0; n < a.references.length; n++) t[a.from_item_ID].ref_to.push({\n\t\t\ttype: a.type,\n\t\t\tid: a.references[n]\n\t\t});\n\t\tif (i.iprp) for (var o = 0; o < i.iprp.ipmas.length; o++) for (var h = i.iprp.ipmas[o], d = 0; d < h.associations.length; d++) {\n\t\t\tvar l = h.associations[d];\n\t\t\tif (s = (s = t[l.id]) || e[l.id]) for (void 0 === s.properties && (s.properties = {},\n\t\t\ts.properties.boxes = []), n = 0; n < l.props.length; n++) {\n\t\t\t\tvar p = l.props[n];\n\t\t\t\t0 < p.property_index && p.property_index - 1 < i.iprp.ipco.boxes.length && (p = i.iprp.ipco.boxes[p.property_index - 1], s.properties[p.type] = p, s.properties.boxes.push(p))\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getItem = function(t) {\n\tvar e, i;\n\tif (!this.meta) return null;\n\tif (! (i = this.items[t]).data && i.size) i.data = new Uint8Array(i.size),\n\ti.alreadyRead = 0,\n\tthis.itemsDataSize += i.size,\n\tLog.debug("ISOFile", "Allocating item #" + t + " of size " + i.size + " (total: " + this.itemsDataSize + ")");\n\telse if (i.alreadyRead === i.size) return i;\n\tfor (var r = 0; r < i.extents.length; r++) {\n\t\tvar s = i.extents[r];\n\t\tif (s.alreadyRead !== s.length) {\n\t\t\tvar a = this.stream.findPosition(!0, s.offset + s.alreadyRead, !1);\n\t\t\tif (! (-1 < a)) return null;\n\t\t\ta = (e = this.stream.buffers[a]).byteLength - (s.offset + s.alreadyRead - e.fileStart);\n\t\t\tif (! (s.length - s.alreadyRead <= a)) return Log.debug("ISOFile", "Getting item #" + t + " extent #" + r + " partial data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + a + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, a),\n\t\t\ts.alreadyRead += a,\n\t\t\ti.alreadyRead += a,\n\t\t\te.usedBytes += a,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\tnull;\n\t\t\tLog.debug("ISOFile", "Getting item #" + t + " extent #" + r + " data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + (s.length - s.alreadyRead) + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, s.length - s.alreadyRead),\n\t\t\te.usedBytes += s.length - s.alreadyRead,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\ti.alreadyRead += s.length - s.alreadyRead,\n\t\t\ts.alreadyRead = s.length\n\t\t}\n\t}\n\treturn i.alreadyRead === i.size ? i: null\n},\nISOFile.prototype.releaseItem = function(t) {\n\tvar e = this.items[t];\n\tif (e.data) {\n\t\tthis.itemsDataSize -= e.size,\n\t\te.data = null;\n\t\tfor (var i = e.alreadyRead = 0; i < e.extents.length; i++) e.extents[i].alreadyRead = 0;\n\t\treturn e.size\n\t}\n\treturn 0\n},\nISOFile.prototype.processItems = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tthis.getItem(i.id),\n\t\tt && !i.sent && (t(i), i.sent = !0, i.data = null)\n\t}\n},\nISOFile.prototype.hasItem = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tif (i.name === t) return i.id\n\t}\n\treturn - 1\n},\nISOFile.prototype.getMetaHandler = function() {\n\treturn this.meta ? this.meta.hdlr.handler: null\n},\nISOFile.prototype.getPrimaryItem = function() {\n\treturn this.meta && this.meta.pitm ? this.getItem(this.meta.pitm.item_id) : null\n},\nISOFile.prototype.itemToFragmentedTrackFile = function(t) {\n\tvar e = t || {},\n\ti = null;\n\tif (null == (i = e.itemId ? this.getItem(e.itemId) : this.getPrimaryItem())) return null;\n\tt = new ISOFile;\n\tt.discardMdatData = !1;\n\te = {\n\t\ttype: i.type,\n\t\tdescription_boxes: i.properties.boxes\n\t};\n\ti.properties.ispe && (e.width = i.properties.ispe.image_width, e.height = i.properties.ispe.image_height);\n\te = t.addTrack(e);\n\treturn e ? (t.addSample(e, i.data), t) : null\n},\nISOFile.prototype.write = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t)\n},\nISOFile.prototype.createFragment = function(t, e, i) {\n\tvar r = this.getTrackById(t),\n\tt = this.getSample(r, e);\n\tif (null == t) return this.setNextSeekPositionFromSample(r.samples[e]),\n\tnull;\n\te = i || new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN;\n\ti = this.createSingleSampleMoof(t);\n\ti.write(e),\n\ti.trafs[0].truns[0].data_offset = i.size + 8,\n\tLog.debug("MP4Box", "Adjusting data_offset with new value " + i.trafs[0].truns[0].data_offset),\n\te.adjustUint32(i.trafs[0].truns[0].data_offset_position, i.trafs[0].truns[0].data_offset);\n\ti = new BoxParser.mdatBox;\n\treturn i.data = t.data,\n\ti.write(e),\n\te\n},\nISOFile.writeInitializationSegment = function(t, e, i, r) {\n\tvar s;\n\tLog.debug("ISOFile", "Generating initialization segment");\n\tvar a = new DataStream;\n\ta.endianness = DataStream.BIG_ENDIAN,\n\tt.write(a);\n\tvar n = e.add("mvex");\n\tfor (i && n.add("mehd").set("fragment_duration", i), s = 0; s < e.traks.length; s++) n.add("trex").set("track_id", e.traks[s].tkhd.track_id).set("default_sample_description_index", 1).set("default_sample_duration", r).set("default_sample_size", 0).set("default_sample_flags", 65536);\n\treturn e.write(a),\n\ta.buffer\n},\nISOFile.prototype.save = function(t) {\n\tvar e = new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(e),\n\te.save(t)\n},\nISOFile.prototype.getBuffer = function() {\n\tvar t = new DataStream;\n\treturn t.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t),\n\tt.buffer\n},\nISOFile.prototype.initializeSegmentation = function() {\n\tvar t, e, i, r;\n\tfor (null === this.onSegment && Log.warn("MP4Box", "No segmentation callback set!"), this.isFragmentationInitialized || (this.isFragmentationInitialized = !0, this.nextMoofNumber = 0, this.resetTables()), e = [], t = 0; t < this.fragmentedTracks.length; t++) {\n\t\tvar s = new BoxParser.moovBox;\n\t\ts.mvhd = this.moov.mvhd,\n\t\ts.boxes.push(s.mvhd),\n\t\ti = this.getTrackById(this.fragmentedTracks[t].id),\n\t\ts.boxes.push(i),\n\t\ts.traks.push(i),\n\t\t(r = {}).id = i.tkhd.track_id,\n\t\tr.user = this.fragmentedTracks[t].user,\n\t\tr.buffer = ISOFile.writeInitializationSegment(this.ftyp, s, this.moov.mvex && this.moov.mvex.mehd ? this.moov.mvex.mehd.fragment_duration: void 0, 0 < this.moov.traks[t].samples.length ? this.moov.traks[t].samples[0].duration: 0),\n\t\te.push(r)\n\t}\n\treturn e\n},\nBoxParser.Box.prototype.printHeader = function(t) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tt.log(t.indent + "size:" + this.size),\n\tt.log(t.indent + "type:" + this.type)\n},\nBoxParser.FullBox.prototype.printHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "version:" + this.version),\n\tt.log(t.indent + "flags:" + this.flags)\n},\nBoxParser.Box.prototype.print = function(t) {\n\tthis.printHeader(t)\n},\nBoxParser.ContainerBox.prototype.print = function(t) {\n\tthis.printHeader(t);\n\tfor (var e, i = 0; i < this.boxes.length; i++) this.boxes[i] && (e = t.indent, t.indent += " ", this.boxes[i].print(t), t.indent = e)\n},\nISOFile.prototype.print = function(t) {\n\tt.indent = "";\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && this.boxes[e].print(t)\n},\nBoxParser.mvhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "timescale: " + this.timescale),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "rate: " + this.rate),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "next_track_id: " + this.next_track_id)\n},\nBoxParser.tkhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "track_id: " + this.track_id),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "layer: " + this.layer),\n\tt.log(t.indent + "alternate_group: " + this.alternate_group),\n\tt.log(t.indent + "width: " + this.width),\n\tt.log(t.indent + "height: " + this.height)\n};\nvar MP4Box = {\n\tcreateFile: function(t, e) {\n\t\tt = void 0 === t || t,\n\t\te = new ISOFile(e);\n\t\treturn e.discardMdatData = !t,\n\t\te\n\t}\n};\n"undefined" != typeof exports && (exports.createFile = MP4Box.createFile);\n',workerLogic="\n// 显式将变量绑定到self上,确保全局可访问\nself.abortFlag = false;\nself.mp4boxfile = null;\nself.videoDecoder = null;\nself.samplesInRange = [];\nself.videoTrack = null;\nself.arrayBuffer = null;\n\nonmessage = function(e) {\n if (e.data.type === 'decode') {\n self.abortFlag = false;\n decodeFile(e.data.file, e.data.start, e.data.end, e.data.hardwareAcceleration);\n } else if (e.data.type === 'abort') {\n self.abortFlag = true;\n // 主动销毁所有大对象和引用\n if (self.videoDecoder) {\n try {\n self.videoDecoder.flush();\n self.videoDecoder.reset();\n self.videoDecoder.close();\n } catch (err) {}\n self.videoDecoder = null;\n }\n if (self.mp4boxfile) {\n try { self.mp4boxfile.flush(); } catch (err) {}\n self.mp4boxfile = null;\n }\n self.samplesInRange = [];\n self.videoTrack = null;\n self.arrayBuffer = null;\n // 关闭worker\n self.close();\n }\n};\n\nfunction decodeFile(file, startFrame, endFrame, hardwareAcceleration) {\n self.arrayBuffer = file.data;\n self.mp4boxfile = MP4Box.createFile();\n self.videoTrack = null;\n let nbSampleTotal = 0;\n self.samplesInRange = [];\n self.videoDecoder = null;\n let frameIndex = 0;\n let totalFrames = 0;\n self.mp4boxfile.onReady = function(info) {\n self.videoTrack = info.videoTracks[0];\n nbSampleTotal = self.videoTrack.nb_samples;\n self.mp4boxfile.setExtractionOptions(self.videoTrack.id, null, {\n nbSamples: nbSampleTotal,\n rapAlignement: true\n });\n self.mp4boxfile.start();\n };\n self.mp4boxfile.onSamples = async function(trackId, ref, samples) {\n if (self.abortFlag) return; // 确保使用self访问\n // 自动对齐到区间内第一个关键帧\n let startIdx = Math.min(0, startFrame); // 修复Math.min, 因为仅有第一帧是关键帧\n let endIdx = Math.min(samples.length - 1, endFrame);\n while (startIdx <= endIdx && !samples[startIdx].is_sync) {\n startIdx++;\n }\n if (startIdx > endIdx) {\n // 区间内没有关键帧,直接done\n postMessage({ type: 'done' });\n return;\n }\n self.samplesInRange = samples.slice(0, endIdx + 1);\n totalFrames = self.samplesInRange.length;\n if (!self.videoDecoder) {\n self.videoDecoder = new VideoDecoder({\n output: handleFrame,\n error: err => {\n postMessage({ type: 'error', error: err.message })\n }\n });\n const entry = self.mp4boxfile.moov.traks[0].mdia.minf.stbl.stsd.entries[0];\n const box = entry.avcC ?? entry.hvcC ?? entry.vpcC;\n let description = undefined;\n if (box) {\n const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);\n box.write(stream);\n description = new Uint8Array(stream.buffer.slice(8));\n }\n\t\tconst isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);\n \tconst userAgent = (navigator.userAgent || \"\").toLowerCase();\n\t const isAndroid = /android/.test(userAgent) || /openharmony|arkweb/.test(userAgent);\n\t\tconst defaultConfig = {\n\t\t\tcodec: self.videoTrack.codec,\n\t\t\tcodedWidth: self.videoTrack.track_width,\n\t\t\tcodedHeight: self.videoTrack.track_height,\n\t\t\tdescription,\n\t\t}\n\t\t// Android 系统下,默认配置为 prefer-software 以避免硬件解码问题\n\t\tlet config = isAndroid ? { ...defaultConfig, hardwareAcceleration: 'prefer-software' } : hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t\t...defaultConfig,\n\t\t\thardwareAcceleration: hardwareAcceleration,\n\t\t}\n\t\t// let config = hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t// \t...defaultConfig,\n\t\t// \thardwareAcceleration: hardwareAcceleration,\n\t\t// }\n\t\tconst configSupport = (await VideoDecoder.isConfigSupported(config));\n\t\tconst isConfigSupported = configSupport.supported;\n\t\tpostMessage({ type: 'configSupport', configSupport: { config, configSupport}});\n\t\tlet isDefaultConfigSupported = false;\n\t\tif(!isConfigSupported) {\n\t\t\tconst defaultConfigSupport = await VideoDecoder.isConfigSupported(defaultConfig);\n\t\t\tpostMessage({ type: 'configSupport', configSupport: { defaultConfig, configSupport: defaultConfigSupport}});\n\t\t\tisDefaultConfigSupported = defaultConfigSupport.supported;\n\t\t}\n\t\tif(isConfigSupported) {\n\t\t\tself.videoDecoder.configure(config);\n\t\t} else if(isDefaultConfigSupported) {\n\t\t\tself.videoDecoder.configure(defaultConfig);\n\t\t} else {\n\t\t\tpostMessage({ type: 'error', error: '不支持的视频解码配置' });\n\t\t}\n }\n for (let i = 0; i < self.samplesInRange.length; i++) {\n if (self.abortFlag) break; // 确保使用self访问\n \n const sample = self.samplesInRange[i];\n const chunk = new EncodedVideoChunk({\n type: sample.is_sync ? 'key' : 'delta',\n timestamp: sample.cts,\n duration: sample.duration,\n data: sample.data\n });\n self.videoDecoder.decode(chunk);\n }\n self.videoDecoder.flush().then(() => {\n postMessage({ type: 'done' });\n });\n };\n function handleFrame(videoFrame) {\n if (self.abortFlag) { // 确保使用self访问\n videoFrame.close();\n return;\n }\n postMessage({ type: 'frame', frame: videoFrame, index: frameIndex++, total: totalFrames }, [videoFrame]);\n }\n self.arrayBuffer.fileStart = 0;\n self.mp4boxfile.appendBuffer(self.arrayBuffer);\n self.mp4boxfile.flush();\n}\n",fullWorkerScript=`\ntry {\n ${mp4boxSource}\n self.MP4Box = MP4Box;\n ${workerLogic}\n} catch (error) {\n console.error('Worker初始化失败:', error);\n throw error;\n}\n`,blob=new Blob([fullWorkerScript],{type:"application/javascript"}),workerURL=URL.createObjectURL(blob);function base64ToUint8Array(t){if(!t||""===t.trim())return new Uint8Array(0);const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function twoByteToInt16(t,e){const n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){const e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];const n=e.length/2,i=new ArrayBuffer(4*n),r=new Float32Array(i);for(let t=0;t<n;t++){const n=2*t,i=twoByteToInt16(e[n],e[n+1]);r[t]=i/32767}return Array.from(r)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=new Float32Array(e);return Array.from(n)}class ParallelDecoder{constructor(t){this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.currentDecodedFrameIndex=null,this.abortAfterFrame=null,this.cacheVideoCount=5,this.maxVideoCount=2,this.hardwareAcceleration="default",this.MAX_LOAD_VIDEO_TIMEOUT_MS=2e3,this._offlineLastFrame=0,this._offlineIdle=[],this._offlineIdleIndex=0,this.firstDecodeFrame=!0,this.tasks=new Map,this.queue=[],this.maxParallel=1,this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.resourceManager=t.resourceManager,this.onFrame=()=>{},this.onDone=()=>{},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}getRandomTaskId(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)}decode(t,e){if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=(t,n,i)=>{this.currentDecodedFrameIndex=t.startFrameIndex+i,this._handlePendingAbort(t,i),e(t,n,i)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)}clearOldQueue(t){this.queue=this.queue.filter(e=>e.sf>=t)}updateQueue(t){if(this.abortAfterFrame=null,0===this.queue.length)return void this.queue.push(...t);const e=this.queue[0].sf,n=t[0].sf;if(n>=this.queue[this.queue.length-1].ef)this.queue.push(...t);else if(n<e){if(null!==this.currentDecodedFrameIndex&&n>this.currentDecodedFrameIndex+1){this.abortAfterFrame=n-1;const e=this.queue.filter(t=>t.ef<n);return void(this.queue=e.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(n===e)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{const e=this.queue.findIndex(t=>t.sf>=n);-1!==e&&(this.queue.length=e),this.abortAfterFrame=n-1,this.queue.push(...t)}}_isIOS(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)}getQueue(){return this.queue.map(t=>_extends({},t,{x_offset:[]}))}timeoutPromise(t,e="请求超时"){return new Promise((e,n)=>{setTimeout(()=>{n()},t)})}async loadVideoWithTimeout(t){try{return await Promise.race([this.resourceManager.loadVideo(t),this.timeoutPromise(this.MAX_LOAD_VIDEO_TIMEOUT_MS,`视频 ${t} 加载超时(${this.MAX_LOAD_VIDEO_TIMEOUT_MS}ms)`)])}catch(t){return null}}async _tryStartNext(){var t;let e;if(e=(null==(t=this.queue)?void 0:t.some(t=>null!==this.currentDecodedFrameIndex&&t.sf<this.currentDecodedFrameIndex))?this._isIOS()?this.maxVideoCount:this.maxVideoCount+1:this._isIOS()?1:this.maxVideoCount,!(this.dataCacheQueue.getBodyVideoNameListLength()>=e)&&this.currentParallel<this.maxParallel&&this.queue.length>0){var n,i;const t=this.queue.shift();if(this.saveAndDownload.appendMultipleToArray("videoData",[_extends({},t,{x_offset:parseUint8ToFloat32(t.x_offset)||[]})]),this._cleanupOldWorkers(null!=(n=null!=(i=t.body_id)?i:t.id)?n:0),this.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,t),!t.n)return this.currentParallel--,this._tryStartNext(),void this.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:`body数据无Name: ${JSON.stringify(t)}`});const e=await this.loadVideoWithTimeout(t.n);if(!e)return this.currentParallel--,void this._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,t),window.performanceTracker.markStart(performanceConstant.decode_video,t),window.performanceTracker.markStart(performanceConstant.first_decode_video,t),this._startWorker({name:t.n,id:t.id,frameState:t.s,start:t.asf,end:t.aef,hfd:t.hfd,data:e,startFrameIndex:t.sf,endFrameIndex:t.ef,body_id:t.body_id,x_offset:parseUint8ToFloat32(t.x_offset)||[]})}}_startWorker(t){var e,n;const i=this.currentTaskId;let r;try{r=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}const s=`${null!=(e=null!=(n=t.body_id)?n:t.id)?e:0}_${t.name}`,a=t.data,o=new ArrayBuffer(a.byteLength);new Uint8Array(o).set(new Uint8Array(a)),r.addEventListener("error",t=>{i===this.currentTaskId&&this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});const l=e=>{if(i===this.currentTaskId)if("frame"===e.data.type)if(this.firstDecodeFrame&&(this.firstDecodeFrame=!1,window.performanceTracker.markEnd(performanceConstant.first_decode_video,t)),e.data.index<t.start||e.data.index>t.end)e.data.frame.close();else{var n;this.cacheVideo(),this.onFrame(t,e.data.frame,e.data.index);const i=null!=(n=this.bodyFrameCountMap.get(t.name))?n:0;this.bodyFrameCountMap.set(t.name,i+1),this.abortAfterFrame&&e.data.index+t.startFrameIndex>=this.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",this.abortAfterFrame,t),this.abortOne(s),this.abortAfterFrame=null,this._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var a;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(a=this.bodyFrameCountMap.get(t.name))?a:0)<t.end-t.start-1&&this.bodyFrameCountMap.delete(t.name);const e=this.tasks.get(s);e&&(e.status="done",e.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),r.removeEventListener("message",l),r.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1),this._tryStartNext()}else if("error"===e.data.type){var o;const n=null!=(o=e.data.error)?o:"",i=n.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;this.reportMessage({code:i,message:n||"视频解码错误",e:{fileName:t.name,error:n}});const a=this.tasks.get(s);a&&(a.status="error",a.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),r.removeEventListener("message",l),r.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1)}};r.addEventListener("message",l),this.tasks.set(s,{worker:r,status:"decoding",onMessage:l,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),r.postMessage({type:"decode",file:{data:o},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:i},[o])}cacheVideo(){const t=this.queue.slice(0,this.cacheVideoCount);for(const e of t)this.resourceManager.preloadVideo(e.n)}abort(){this.tasks.forEach(({worker:t,status:e,onMessage:n})=>{"decoding"===e&&(t.postMessage({type:"abort"}),n&&t.removeEventListener("message",n),t.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null}abortOne(t){const e=this.tasks.get(t);e&&"decoding"===e.status&&(null==e||e.worker.postMessage({type:"abort"}),null!=e&&e.onMessage&&e.worker.removeEventListener("message",e.onMessage),null==e||e.worker.terminate(),this.tasks.delete(t),this.currentParallel--,0===this.currentParallel&&0===this.queue.length&&(this._locked=!1))}destroy(){this.abort(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.abortAfterFrame=null,this.currentDecodedFrameIndex=null,this.firstDecodeFrame=!0}_handlePendingAbort(t,e){this.pendingAbort&&null!==this.abortAfterEf&&t.startFrameIndex+e>=this.abortAfterEf&&(this.abort(),this.queue=this.pendingNewQueue,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null)}_cleanupOldWorkers(t){for(const[e,n]of this.tasks){const[i]=e.split("_"),r=parseInt(i,10);!isNaN(r)&&r<t&&(n.worker.postMessage({type:"abort"}),n.onMessage&&n.worker.removeEventListener("message",n.onMessage),n.worker.terminate(),this.tasks.delete(e))}}syncDecode(t){const e=this.queue.filter(e=>e.ef>t);0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())}_reload(){this._offlineLastFrame=0,this.queue=[]}_offLineMode(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()}_offlineRun(){const t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0}_putOfflineBodyData(t){const e={id:-1,n:t.n,s:"idle",hfd:!1,body_id:-1,asf:t.asf,aef:t.aef,sf:this._offlineLastFrame,ef:this._offlineLastFrame+(t.aef-t.asf),x_offset:new Uint8Array};this.queue.push(e),this._offlineLastFrame=e.ef}}class FrameAnimationController{constructor({defaultSpeed:t=1,frameRate:e=24,frameCallback:n}={}){this.startTime=null,this.currentFrame=1,this.speed=t,this.frameCallback=n||null,this.frameRate=e,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}get playing(){return this.isPlaying}play(){this.isPlaying||(this.isPlaying=!0,window.avatarSDKLogger.log("开始时间",this.startTime),null===this.startTime&&(window.avatarSDKLogger.log("当前时间",performance.now()),this.startTime=performance.now(),this.startTimeFromDate=Date.now()),this.animationId=requestAnimationFrame(this._animate.bind(this)))}pause(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)}reset(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null}setSpeed(t){this.speed=t}gotoFrame(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()}nextFrame(){this.currentFrame++,this._updateFrame()}prevFrame(){this.gotoFrame(this.currentFrame-1)}destroy(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1}_animate(t){let e=performance.now();if(Math.abs(t-e)<100&&(e=t),this.currentFrame<50&&window.avatarSDKLogger.log("animate时间",t,"开始时间",this.startTime,"performance",performance.now()),this.isPlaying){if(null!==this.startTime){const t=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;t!==this.currentFrame&&(this.currentFrame=t,this._updateFrame());const n=Date.now()-this.startTimeFromDate,i=Math.floor(Math.floor(n/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=i}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}}_updateFrame(){let t=null;this.frameCallback&&(this.currentFrameFromDate!==this.currentFrame&&null!==this.currentFrameFromDate&&(t={key:"frame_number_error",Date帧号:this.currentFrameFromDate,performance帧号:this.currentFrame,开始时间:this.startTime,开始时间日期:this.startTimeFromDate,当前时间:Date.now(),"performance.now()":performance.now()}),this.frameCallback(this.currentFrame,t))}getCurrentFrame(){if(null!==this.startTime){const t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame}updateStartTime(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)}}const captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t=navigator){const e=getAudioSession(t);if(!e)return!1;const n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e=navigator){const n=getAudioSession(e);if(!n)return()=>{};let i=playbackSessionRestoredListeners.get(n);return i||(i=new Set,playbackSessionRestoredListeners.set(n,i)),i.add(t),()=>{var e,r;null==(e=i)||e.delete(t),0===(null==(r=i)?void 0:r.size)&&playbackSessionRestoredListeners.delete(n)}}function getAudioSession(t){return t.audioSession}function setAudioSessionType(t,e){try{return t.type=e,t.type===e}catch(t){return!1}}const pcm_audio_script="// pcm-audio-processor.js - 运行在音频线程的Worklet处理器\nclass PCMAudioProcessor extends AudioWorkletProcessor {\n // 音量配置(与主线程保持一致)\n static get parameterDescriptors() {\n return [\n {\n name: 'volume',\n defaultValue: 1.0,\n minValue: 0.0,\n maxValue: 1.0,\n automationRate: 'a-rate' // 支持音频速率自动化\n }\n ];\n }\n\n constructor() {\n super();\n this.config = {\n sampleRate: 24000, // 固定24kHz采样率\n bytesPerSample: 2, // S16LE=2字节/采样点\n };\n this.pcmCache = new Uint8Array(0); // Worklet内的PCM缓存\n this.isActive = false; // 播放音频状态(控制是否生成声音)\n this.isDestroyed = false;\n this.fadeState = {\n // 淡入淡出状态(避免片段切换爆音)\n phase: 'idle', // idle/fadeIn/fadeOut/steady\n currentGain: 0,\n fadeTime: 0.01, // 淡入淡出时间(秒,建议最小0.01s避免爆音)\n fadeSamples: Math.floor(0.01 * 24000), // 淡入淡出样本数(24000Hz下为240样本)\n };\n this.currentSegment = null; // 当前处理的音频段(float32数组)\n this.segmentOffset = 0; // 当前音频段的播放偏移量\n \n // 监听主线程消息(接收PCM数据、状态控制等)\n this.port.onmessage = (e) => this.handleMainThreadMessage(e.data);\n \n // 初始化淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n\n /**\n * 处理主线程发来的消息(PCM数据/状态控制等)\n * @param {Object} data - 消息数据\n * @param {string} data.type - 消息类型:'pcm'/'start'/'pause'/'stop'/'config'/'destroy'/'volume'\n * @param {Uint8Array} [data.pcmData] - PCM数据(仅type='pcm'时存在)\n * @param {Object} [data.config] - 配置更新(仅type='config'时存在)\n * @param {number} [data.volume] - 音量值(仅type='volume'时存在)\n */\n handleMainThreadMessage(data) {\n switch (data.type) {\n // 接收主线程下发的PCM流数据\n case 'pcm':\n if (data.pcmData instanceof Uint8Array && data.pcmData.length > 0) {\n // 确保PCM数据字节数为2的整数倍(S16LE要求)\n const validLength = data.pcmData.length - (data.pcmData.length % this.config.bytesPerSample);\n if (validLength <= 0) break;\n \n // 合并到Worklet缓存\n const newCache = new Uint8Array(this.pcmCache.length + validLength);\n newCache.set(this.pcmCache, 0);\n newCache.set(data.pcmData.subarray(0, validLength), this.pcmCache.length);\n this.pcmCache = newCache;\n \n // 向主线程发送缓存状态\n this.port.postMessage({\n type: 'cacheStatus',\n size: this.pcmCache.length,\n sampleCount: this.pcmCache.length / this.config.bytesPerSample\n });\n }\n break;\n\n // 启动播放(继续音频生成)\n case 'start':\n this.isActive = true;\n break;\n\n // 暂停播放(停止音频生成,保留缓存)\n case 'pause':\n this.isActive = false;\n this.resetSegmentState();\n break;\n\n // 停止播放(清空缓存+重置状态)\n case 'stop':\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n break;\n\n // 更新配置(如采样率/淡入淡出时间)\n case 'config':\n if (data.config.sampleRate) {\n this.config.sampleRate = data.config.sampleRate;\n // 重新计算淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n if (data.config.fadeTime) {\n this.fadeState.fadeTime = data.config.fadeTime;\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n break;\n\n // 单独更新音量(可选,也可通过参数自动化控制)\n case 'volume':\n this.volume = Number(data.volume);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncVolume',\n volume: this.volume\n });\n break;\n\n // 单独更新播放速率(可选,也可通过参数自动化控制)\n case 'speed':\n this.speed = Number(data.speed);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncSpeed',\n speed: this.speed\n });\n break;\n\n // 销毁处理器\n case 'destroy':\n this.isDestroyed = true;\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n this.port.postMessage({ type: 'destroyConfirmed' });\n break;\n \n default:\n console.warn('[PCMAudioProcessor] 未知消息类型:', data.type);\n }\n }\n\n /**\n * 重置当前音频段状态(暂停/停止时调用)\n */\n resetSegmentState() {\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n this.fadeState.currentGain = 0;\n }\n\n /**\n * S16LE Uint8Array 转 Float32Array(-1~1范围)\n * @param {Uint8Array} pcmData - PCM数据\n * @returns {Float32Array} 转换后的音频样本\n */\n pcmToFloat32(pcmData) {\n const sampleCount = pcmData.length / this.config.bytesPerSample;\n const floatData = new Float32Array(sampleCount);\n const dataView = new DataView(pcmData.buffer);\n\n for (let i = 0; i < sampleCount; i++) {\n // S16LE格式:小端序解析,范围-32768~32767 归一化到-1~1\n floatData[i] = dataView.getInt16(i * this.config.bytesPerSample, true) / 32768;\n }\n return floatData;\n }\n\n /**\n * 计算当前样本的增益(淡入淡出)\n * @param {number} segmentLength - 当前音频段的总样本数\n * @returns {number} 增益值(0~1)\n */\n calculateGain(segmentLength) {\n const { phase, fadeSamples } = this.fadeState;\n const { segmentOffset } = this;\n\n // 边界保护:防止无效值导致的NaN\n if (typeof segmentOffset !== 'number' || typeof segmentLength !== 'number' || segmentLength <= 0) {\n return 0;\n }\n\n switch (phase) {\n // 淡入阶段:从0线性增加到1\n case 'fadeIn':\n if (segmentOffset >= fadeSamples) {\n this.fadeState.phase = 'steady';\n return 1;\n }\n return segmentOffset / fadeSamples;\n\n // 稳定阶段:增益保持1\n case 'steady':\n // 检测是否进入淡出阶段(接近段尾)\n if (segmentOffset >= segmentLength - fadeSamples) {\n this.fadeState.phase = 'fadeOut';\n }\n return 1;\n\n // 淡出阶段:从1线性降低到0.0001(避免分音)\n case 'fadeOut':\n const fadeStart = Math.max(segmentLength - fadeSamples, 0);\n const fadeProgress = (segmentOffset - fadeStart) / fadeSamples;\n return Math.max(1 - fadeProgress, 0.0001);\n\n // 空闲阶段:增益0\n case 'idle':\n default:\n return 0;\n }\n }\n\n /**\n * AudioWorklet核心方法:实时生成音频样本(音频线程调用)\n * @param {Float32Array[][]} inputs - 输入样本\n * @param {Float32Array[][]} outputs - 输出样本(单声道)\n * @param {Object} parameters - 音频参数\n * @returns {boolean} 是否继续运行\n */\n process(inputs, outputs, parameters) {\n // 销毁状态:终止处理\n if (this.isDestroyed) {\n if (outputs.length > 0 && outputs[0].length > 0) {\n outputs[0][0].fill(0);\n }\n return false;\n }\n\n // 未激活或无输出:返回静音\n if (!this.isActive || outputs.length === 0 || outputs[0].length === 0) {\n outputs[0][0].fill(0);\n return true;\n }\n\n const outputBuffer = outputs[0][0];\n const bufferLength = outputBuffer.length;\n // 获取音量参数(支持自动化)\n const volume = parameters.volume.length > 1 \n ? parameters.volume // 自动化模式:每个样本点可能有不同值\n : parameters.volume[0]; // 控制模式:整个缓冲区使用相同值\n\n // 生成输出样本\n for (let i = 0; i < bufferLength; i++) {\n // 如当前无音频段且缓存有数据,创建新段\n if (!this.currentSegment && this.pcmCache.length > 0) {\n // 使用缓存中的所有数据创建新段\n this.currentSegment = this.pcmToFloat32(this.pcmCache);\n // 清空缓存(已处理)\n this.pcmCache = new Uint8Array(0);\n this.segmentOffset = 0;\n // 根据前一段状态决定是否淡入\n this.fadeState.phase = this.fadeState.phase === 'fadeOut' ? 'steady' : 'fadeIn';\n }\n\n // 生成当前样本\n let sample = 0;\n if (this.currentSegment) {\n const segmentLength = this.currentSegment.length;\n // 确保偏移量有效\n if (this.segmentOffset < segmentLength) {\n const gain = this.calculateGain(segmentLength);\n // 应用淡入淡出增益和音量控制\n sample = this.currentSegment[this.segmentOffset] * gain * volume;\n this.segmentOffset++;\n } else {\n // 当前段处理完毕,重置\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n }\n }\n\n outputBuffer[i] = sample;\n }\n\n return true;\n }\n}\n\n// 注册Worklet处理器\nregisterProcessor('pcm-audio-processor', PCMAudioProcessor);\n",pcm_capture_script="// pcm-capture-processor.js - 运行在音频线程的捕获处理器\nclass PCMCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.inputSampleRate = 24000; // PCM 播放器采样率\n this.outputSampleRate = 16000; // Opus 编码要求采样率\n this.bufferSize = 2400; // 100ms @ 24kHz\n this.buffer = new Float32Array(this.bufferSize);\n this.bufferIndex = 0;\n\n // 监听主线程的 reset 消息,清空内部缓冲区(打断/会话切换时使用)\n this.port.onmessage = (e) => {\n if (e.data && e.data.type === 'reset') {\n this.bufferIndex = 0;\n this.buffer.fill(0);\n }\n };\n }\n\n process(inputs) {\n const input = inputs[0];\n if (!input || !input[0] || input[0].length === 0) return true;\n\n const chunk = input[0];\n for (let i = 0; i < chunk.length; i++) {\n this.buffer[this.bufferIndex++] = chunk[i];\n\n if (this.bufferIndex >= this.bufferSize) {\n // 重采样 24kHz → 16kHz\n const resampled = this.resample(this.buffer);\n // Float32 → S16LE\n const pcmBuffer = this.float32ToS16LE(resampled);\n // 静音检测\n const hasAudio = this.detectAudio(this.buffer);\n // 回传主线程(Transferable,避免拷贝)\n this.port.postMessage(\n { pcmData: pcmBuffer.buffer, hasAudio: hasAudio },\n [pcmBuffer.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n\n // 线性插值重采样 24kHz → 16kHz (3:2 比率)\n resample(input) {\n const ratio = this.outputSampleRate / this.inputSampleRate; // 2/3\n const outputLength = Math.floor(input.length * ratio); // 1600\n const output = new Float32Array(outputLength);\n for (let i = 0; i < outputLength; i++) {\n const srcIndex = i / ratio;\n const srcIndexFloor = Math.floor(srcIndex);\n const frac = srcIndex - srcIndexFloor;\n const s1 = input[srcIndexFloor] || 0;\n const s2 = input[srcIndexFloor + 1] || 0;\n output[i] = s1 + (s2 - s1) * frac;\n }\n return output;\n }\n\n // Float32 → S16LE Int16Array\n float32ToS16LE(float32) {\n const int16 = new Int16Array(float32.length);\n for (let i = 0; i < float32.length; i++) {\n let s = Math.max(-1, Math.min(1, float32[i]));\n int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n return int16;\n }\n\n // 静音检测\n detectAudio(buffer) {\n for (let i = 0; i < buffer.length; i++) {\n if (Math.abs(buffer[i]) > 0.0001) return true;\n }\n return false;\n }\n}\nregisterProcessor('pcm-capture-processor', PCMCaptureProcessor);\n",workletBlob=new Blob([pcm_audio_script],{type:"application/javascript"}),workletUrl=URL.createObjectURL(workletBlob),captureWorkletBlob=new Blob([pcm_capture_script],{type:"application/javascript"}),captureWorkletUrl=URL.createObjectURL(captureWorkletBlob);class PCMAudioPlayer{constructor(){this.SAMPLE_RATE=24e3,this.FRAME_ALIGNMENT=2e3,this.WORKLET_SCRIPT_URL=workletUrl,this.audioCtx=null,this.audioWorkletNode=null,this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,this.unsubscribePlaybackSessionRestored=null,this.captureWorklet=null,this.captureCallback=null}async init(){if(this.isInitialized)return;configureWebAudioPlaybackSession();const t=window.AudioContext||window.webkitAudioContext;if(!t||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");this.audioCtx=new t({sampleRate:this.SAMPLE_RATE});const e=window.avatarSDKLogger||console;try{await this.audioCtx.audioWorklet.addModule(this.WORKLET_SCRIPT_URL),e.log(`[PCMAudioPlayer] Worklet脚本加载完成: ${this.WORKLET_SCRIPT_URL}`),this.audioWorkletNode=new AudioWorkletNode(this.audioCtx,"pcm-audio-processor"),this.audioWorkletNode.connect(this.audioCtx.destination),e.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),this.audioWorkletNode.port.onmessage=t=>{var n,i,r;switch(t.data.type){case"cacheStatus":e.log(`[PCMAudioPlayer] Worklet缓存状态: ${t.data.size}字节`);break;case"error":e.error("[PCMAudioPlayer] Worklet错误:",t.data.detail);break;case"destroyConfirmed":e.log("[PCMAudioPlayer] Worklet已确认销毁"),null==(n=this.destroyResolve)||n.call(this);break;case"syncVolume":void 0!==(null==(i=this.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("volume"))?void 0:i.value)&&(this.audioWorkletNode.parameters.get("volume").value=t.data.volume);break;case"syncSpeed":void 0!==(null==(r=this.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("speed"))?void 0:r.value)&&(this.audioWorkletNode.parameters.get("speed").value=t.data.speed);break;default:e.log("[PCMAudioPlayer] Worklet消息:",t.data)}},this.isInitialized=!0,this.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(()=>{this.refreshPlaybackRoute()}),e.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")}catch(t){throw e.error("[PCMAudioPlayer] 初始化失败:",t),t}}refreshPlaybackRoute(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;const t=window.avatarSDKLogger||console;try{return this.audioWorkletNode.disconnect(),this.audioWorkletNode.connect(this.audioCtx.destination),this.captureWorklet&&this.audioWorkletNode.connect(this.captureWorklet),"running"!==this.audioCtx.state&&this.audioCtx.resume().catch(e=>{t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}}receivePCMStream(t){const e=window.avatarSDKLogger||console;if(this.isInitialized&&this.audioWorkletNode)if(t instanceof Uint8Array){e.log(`[PCMAudioPlayer] 已下发PCM数据: ${t.length}字节`);try{this.audioWorkletNode.port.postMessage({type:"pcm",pcmData:t},[t.buffer])}catch(t){e.error("[PCMAudioPlayer] 下发PCM数据到Worklet失败:",t)}}else e.error("[PCMAudioPlayer] 输入PCM数据必须是非空的Uint8Array");else e.error("[PCMAudioPlayer] 播放器未初始化,无法接收PCM数据")}async start(){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");const t=window.avatarSDKLogger||console;"running"!==this.audioCtx.state&&(await this.audioCtx.resume(),t.log("[PCMAudioPlayer] AudioContext已恢复运行")),this.audioWorkletNode.port.postMessage({type:"start"}),this.isPlaying=!0,t.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")}pause(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}stop(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}async destroy(){var t;const e=window.avatarSDKLogger||console;null==(t=this.unsubscribePlaybackSessionRestored)||t.call(this),this.unsubscribePlaybackSessionRestored=null,this.detachCapture(),this.isInitialized&&this.audioCtx&&this.audioWorkletNode?(await new Promise(t=>{var n;this.destroyResolve=t,null==(n=this.audioWorkletNode)||n.port.postMessage({type:"destroy"});const i=setTimeout(()=>{var t;e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==(t=this.destroyResolve)||t.call(this)},300);this.audioWorkletNode&&(this.audioWorkletNode.port.onmessage=t=>{var e;"destroyConfirmed"===t.data.type&&(clearTimeout(i),null==(e=this.destroyResolve)||e.call(this))})}),this.audioWorkletNode.disconnect(),this.audioWorkletNode.port.close(),this.audioWorkletNode=null,"closed"!==this.audioCtx.state&&await this.audioCtx.close(),this.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")):e.log("[PCMAudioPlayer] 播放器未初始化或已销毁")}async attachCapture(t){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");if(!this.captureWorklet){this.captureCallback=t;try{var e;await this.audioCtx.audioWorklet.addModule(captureWorkletUrl),this.captureWorklet=new AudioWorkletNode(this.audioCtx,"pcm-capture-processor"),this.audioWorkletNode.connect(this.captureWorklet),this.captureWorklet.port.onmessage=t=>{this.captureCallback&&t.data.pcmData&&this.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(e=window.avatarSDKLogger)||e.log("[PCMAudioPlayer] 捕获节点已挂载")}catch(t){var n;throw null==(n=window.avatarSDKLogger)||n.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t}}}detachCapture(){if(this.captureWorklet){try{var t;this.captureWorklet.port.onmessage=null,null==(t=this.audioWorkletNode)||t.disconnect(this.captureWorklet),this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}this.captureCallback=null}resetCaptureBuffer(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})}getStatus(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}}setVolume(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})}setSpeed(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})}async resume(){const t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(()=>{window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(t=>{window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}}}class MediaSourceAudioPlayer{static getInstance(t){return MediaSourceAudioPlayer.instance||(MediaSourceAudioPlayer.instance=new MediaSourceAudioPlayer(t)),MediaSourceAudioPlayer.instance}constructor(t){this.mediaSource=null,this.audioElement=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.volume=1,this.MIME_TYPE="audio/webm;codecs=opus",this.queue=[],this.isUpdating=!1,this.currentObjectURL=null,this.isDestroyed=!1,this.playbackRate=1,this.firstFrameIndex=-1,this.createAudioElement(t),this.createNewMediaSource()}createAudioElement(t){if(this.audioElement)return;const e=document.getElementById("xmov-avatar-audio");if(e)return void(this.audioElement=e);const n=document.createElement("audio");n.id="xmov-avatar-audio",n.preload="auto",n.style.position="absolute",n.style.width="1px",n.style.height="1px",n.style.opacity="0",n.style.pointerEvents="none",n.style.zIndex="-9999",t.el.appendChild(n),this.audioElement=n}createNewMediaSource(){return new Promise((t,e)=>{try{if(!this.audioElement)return;this.mediaSource=new MediaSource,this.currentObjectURL=URL.createObjectURL(this.mediaSource),this.audioElement.src=this.currentObjectURL,this.mediaSource.addEventListener("sourceopen",()=>{try{if(!this.mediaSource)return;this.sourceBuffer=this.mediaSource.addSourceBuffer(this.MIME_TYPE),this.sourceBuffer.mode="sequence",this.sourceBuffer.addEventListener("updateend",()=>{this.isUpdating=!1,this.processQueue()}),this.isInitialized=!0,t()}catch(t){e(t)}}),this.mediaSource.addEventListener("sourceclose",()=>{this.isInitialized=!1})}catch(t){e(t)}})}async destroyCurrentMediaSource(t){try{this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load())}catch(t){}try{this.currentObjectURL&&(URL.revokeObjectURL(this.currentObjectURL),this.currentObjectURL=null)}catch(t){}this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,await this.createNewMediaSource(),t()}stop(t){this.destroyCurrentMediaSource(t)}async addAudioSegment(t){this.isDestroyed||(this.queue.push({data:t}),this.processQueue())}processQueue(){if(this.isDestroyed)return;if(!this.sourceBuffer||!this.mediaSource)return;if(this.isUpdating||0===this.queue.length)return;if(this.sourceBuffer.updating||"open"!==this.mediaSource.readyState)return;this.isUpdating=!0;const t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}async start(){if(!this.isDestroyed&&this.audioElement&&!this.isPlaying)try{this.audioElement.currentTime=0,this.isPlaying=!0,await this.audioElement.play(),window.avatarSDKLogger.log("mseAudioPlayer开始播放",this.getStats(),Date.now())}catch(t){}}getStats(){var t;return{isPlaying:this.isPlaying,isInitialized:this.isInitialized,queueLength:this.queue.length,bufferedRanges:this.getBufferedRanges(),mediaSourceReadyState:(null==(t=this.mediaSource)?void 0:t.readyState)||"null"}}setSpeed(t){this.setPlaybackRate(t)}getBufferedRanges(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const n=this.sourceBuffer.buffered.start(e).toFixed(2),i=this.sourceBuffer.buffered.end(e).toFixed(2);t.push(`[${n}-${i}]`)}return t.join(", ")}}catch(t){return"-"}return"-"}setVolume(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)}setPlaybackRate(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)}destroy(){if(this.isDestroyed=!0,this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load()),this.currentObjectURL){try{URL.revokeObjectURL(this.currentObjectURL)}catch(t){}this.currentObjectURL=null}this.audioElement&&(this.audioElement.remove(),this.audioElement=null),this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,MediaSourceAudioPlayer.instance=null}}class AudioRender{constructor(t){this.TAG="[AudioRenderer]",this.isPlaying=!1,this.lastFrameIndex=-1,this.audio=null,this.firstFrameIndex=-1,this.valume=1,this.speech_id=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.oldSpeechId=-1,this.mseCacheAudioData=[],this.mseAudioPlayer=null,this.options=t,this.resourceManager=t.resourceManager,this.resourceManager.config.raw_audio?(this.audio=new PCMAudioPlayer,this.audio.init()):this.mseAudioPlayer=MediaSourceAudioPlayer.getInstance(t.sdk)}updateAudioData(t){if(!this.resourceManager.config.raw_audio||t[0].sid===this.oldSpeechId)return;-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);let e=0;for(const i of t){var n;e+=(null==(n=i.ad)?void 0:n.length)||0}const i=new Uint8Array(e);let r=0;for(const e of t)e.ad&&(i.set(new Uint8Array(e.ad),r),r+=e.ad.length);var s,a;-1===this.speech_id?(this.speech_id=t[0].sid,null==(s=this.audio)||s.receivePCMStream(i)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(i)):null==(a=this.audio)||a.receivePCMStream(i)}_updateAudio(t){if(!this.mseAudioPlayer||0===t.length)return;const e=t[0];if(e.sid!==this.oldSpeechId)if(-1!==this.speech_id&&e.sid!==this.speech_id){var n;null==(n=window.avatarSDKLogger)||n.log(this.TAG,`检测到新的 speech_id: ${e.sid}, 当前 WebM 播放 (旧: ${this.speech_id}), 新: ${e.sid}, 缓存数据长度: ${this.mseCacheAudioData.length}`),-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=e.sf);for(const e of t)this.mseCacheAudioData.push({data:e.ad,frameIndex:e.sf,speechId:e.sid})}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(const e of t)if(e.ad){const t=e.ad instanceof ArrayBuffer?e.ad:e.ad.buffer.slice(e.ad.byteOffset,e.ad.byteOffset+e.ad.byteLength);this.mseAudioPlayer.addAudioSegment(t)}}}async render(t){if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",this.firstFrameIndex),-1===this.lastFrameIndex&&(this.lastFrameIndex=t),this.options.sdk.getStatus()!==AvatarStatus.offline){var e;if(t>=this.firstFrameIndex&&-1!=this.firstFrameIndex&&!this.isPlaying&&this.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),this.isPlaying=!0,void(null==(e=this.audio)||e.start());if(this.resourceManager.config.raw_audio||!this.mseAudioPlayer);else if(-1!==this.firstFrameIndex&&t>=this.firstFrameIndex&&!this.mseAudioPlayer.isPlaying&&!this.isPlaying){const e=this.mseAudioPlayer.getStats();if(e.queueLength>0||"-"!==e.bufferedRanges)try{window.avatarSDKLogger.log("开始播放",t),this.isPlaying=!0,await this.mseAudioPlayer.start(),window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")}catch(n){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:n,frameIndex:t,firstFrameIndex:this.firstFrameIndex,queueLength:e.queueLength})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]",`等待更多 WebM 音频数据 (frameIndex: ${t}, queueLength: ${e.queueLength})`)}}}resume(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())}pause(){var t,e;this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(this.speech_id),this.lastFrameIndex=-1,this.firstFrameIndex=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[],this.oldSpeechId=-1,null==(t=this.audio)||t.stop(),null==(e=this.mseAudioPlayer)||e.stop(this.addNewAudioSegment.bind(this)),this.speech_id=-1}stop(t){var e,n,i;if(!(-1!==t&&this.oldSpeechId>=t))if(this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(t),this.firstFrameIndex=-1,null==(e=window.avatarSDKLogger)||e.log(this.TAG,`清除缓存数据 (speech_id: ${this.speech_id}, PCM缓存数据长度: ${this.cacheAudioData.length}, WebM缓存数据长度: ${this.mseCacheAudioData.length})`),this.resourceManager.config.raw_audio?null==(n=this.audio)||n.stop():null==(i=this.mseAudioPlayer)||i.stop(this.addNewAudioSegment.bind(this)),this.oldSpeechId=t,this.speech_id=-1,-1===t)this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[];else if(this.cacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const t of this.cacheAudioData){var r;null==(r=this.audio)||r.receivePCMStream(t)}this.cacheAudioData=[]}}addNewAudioSegment(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const e of this.mseCacheAudioData){var t;e.data&&(null==(t=this.mseAudioPlayer)||t.addAudioSegment(e.data))}this.mseCacheAudioData=[]}}setVolume(t){var e,n;this.valume=t,this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setVolume(t):null==(n=this.mseAudioPlayer)||n.setVolume(t)}setSpeed(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)}getAudioPlayer(){return this.audio}destroy(){var t,e;this.stop(-1),this.cacheAudioData=[],this.mseCacheAudioData=[],null==(t=this.audio)||t.destroy(),null==(e=this.mseAudioPlayer)||e.destroy(),this.mseAudioPlayer=null}}class SaveAndDownload{constructor(t="avatarData.json",e=!1){this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}initDownloadButton(){this.enabled&&(this.downloadButton=document.createElement("a"),this.downloadButton.style.position="absolute",this.downloadButton.style.left="0",this.downloadButton.style.bottom="30px",this.downloadButton.style.background="#4CAF50",this.downloadButton.style.color="white",this.downloadButton.style.fontSize="12px",this.downloadButton.style.padding="10px",this.downloadButton.style.borderRadius="4px",this.downloadButton.style.textDecoration="none",this.downloadButton.style.zIndex="1000",this.downloadButton.style.cursor="pointer",this.downloadButton.innerHTML="下载数据提交开发回放",this.downloadButton.addEventListener("click",()=>{this.download()}),document.body.appendChild(this.downloadButton))}writeFields(t){this.enabled&&Object.assign(this.data,t)}appendMultipleToArray(t,e){this.enabled&&(this.data[t]||(this.data[t]=[]),this.data[t].push(...e))}download(){if(!this.enabled)return;const t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}generateJSONContent(){return JSON.stringify(this.data,null,2)}downloadFile(t,e,n){if(!this.enabled)return;const i=new Blob([t],{type:n}),r=URL.createObjectURL(i);this.downloadButton.href=r,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=r}}class RenderScheduler{constructor(t){this.TAG="[RenderScheduler]",this.currentSpeechId=-1,this.isStartPlay=!1,this.renderState=RenderState.init,this.lastSpeechId=-1,this.enableClientInterrupt=!1,this.audioOnlyMode=!1,this._speedResetTimer=null,this.offsetFrame=0,this.hasSendTimeJson=!1,this.config=t,this.setAudioInfo=t.setAudioInfo,this.setEventData=t.setEventData,this.reportMessage=t.reportMessage,this.sendSdkPoint=t.sendSdkPoint,this.onRenderChange=t.onRenderChange,this.sendMessage=t.sendMessage,this.enableClientInterrupt=t.enableClientInterrupt||!1,this.audioOnlyMode=t.audioOnlyMode||!1,this.saveAndDownload=new SaveAndDownload("avatarData.js",t.enableDebugger),this.resourceManager=t.resourceManager,this.sdk=t.sdkInstance,this.onDownloadProgress=t.onDownloadProgress,this.onFPSUpdate=t.onFPSUpdate,this.dataCacheQueue=new DataCacheQueue,this.decoder=new ParallelDecoder({hardwareAcceleration:t.hardwareAcceleration,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,dataCacheQueue:this.dataCacheQueue,reportMessage:this.reportMessage}),this.avatarRenderer=new AvatarRender({dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,forceSyncDecoder:this.forceSyncDecoder.bind(this),reportMessage:this.reportMessage,sendSdkPoint:this.sendSdkPoint,onDownloadProgress:t=>{this.onDownloadProgress(t)},onStateChange:e=>{t.onStateChange(e)},onRenderChange:e=>{t.onRenderChange(e,this.renderState),this.renderState=e},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:e=>{t.onWalkStateChange(e)},onVoiceStart:(e,n)=>{t.onVoiceStateChange("start",e,n)},onVoiceEnd:(e,n)=>{this.stopAudio(n),t.onVoiceStateChange("end",void 0,e)},onSpeakStateChange:(e,n,i)=>{"speak_start"===e?(this.currentSpeechId=i,this.avatarRenderer.setInterrupt(!1)):"speak_end"===e&&(this.dataCacheQueue.clearSubtitleOn(i),i>=this.currentSpeechId&&this.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(e,n)},sendSdkPoint:(e,n,i)=>{t.sendSdkPoint(e,n,i)}}),this.audioRenderer=new AudioRender({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager}),this.composition=new Composition({container:t.container,avatarRenderer:this.avatarRenderer,restRenderers:[this.uiRenderer],audioRenderer:this.audioRenderer,audioOnlyMode:this.audioOnlyMode,onFPSUpdate:t=>{this.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:(e,n)=>{if(!this.hasSendTimeJson&&n&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",n),this.sendMessage("client_error",n),this.hasSendTimeJson=!0),t.renderFrameCallback(e+=this.offsetFrame),this.isStartPlay&&(this.composition.compose(e),this.decoder._tryStartNext(),t.onFrameDataUpdate)){const n=this.avatarRenderer._getCurrentFrameData(e);t.onFrameDataUpdate({frameIndex:e,body:n.body,face:n.face})}}})}init(){if(this.audioOnlyMode)return;const t=this.resourceManager.getMouthShapeLib();this.saveAndDownload.writeFields({resource_pack:this.resourceManager.resource_pack}),this.avatarRenderer.init({char:t.char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4})}async handleData(t,e){var n,i,r;if(this.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return;const s=this.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:{this.decoder.clearOldQueue(s);const t=s;let n=[...e].filter(e=>e.ef>t);window.avatarSDKLogger.log(n,"mp4List"),n.length>0&&(this.renderState!==RenderState.paused&&s&&s>e[0].sf&&s>10&&this.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:`Error: 身体数据过期 cur:${s}-sf:${e[0].sf}`,e}),this.decoder.decode(n,(t,e,n)=>{var i,r;t.start<=n&&t.end>=n&&(this.dataCacheQueue._updateBodyImageBitmap({frame:e,frameIndex:t.startFrameIndex+n,frameState:t.frameState,id:t.id,body_id:t.body_id,name:t.name,hfd:t.hfd,sf:t.startFrameIndex,offset:(null==t?void 0:t.x_offset[n])||0}),t.endFrameIndex<=t.startFrameIndex+n&&this.decoder.abortOne(`${null!=(i=null!=(r=t.body_id)?r:t.id)?i:0}_${t.name}`))}));break}case EFrameDataType.FACE:this.dataCacheQueue.clearOldFaceData(s);const m=this.handleFaceData(e);m.length>0&&this.saveAndDownload.appendMultipleToArray("faceData",m),this.dataCacheQueue.checkValidData(m,t);let g=[],y=[];for(let t=0;t<m.length;t++){var a;null!=(a=m[t])&&a.face_frame_type?y.push(m[t]):g.push(m[t])}y.length&&this.dataCacheQueue._updateFacial(y),g.length&&this.dataCacheQueue._updateRealFacial(g);break;case EFrameDataType.AUDIO:if(this.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),this.renderState!==RenderState.paused&&s>e[0].sf){const t=s?s-e[0].sf:0;this.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:`Error: 音频数据过期 cur:${s}-sf:${e[0].sf}`,e:{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()}}),this.sendSdkPoint("audio_data_expired",{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()})}const v=1e3/24,{sf:b,ef:S}=e[0],E=S-b;if(E<=0)return;const w=(s||0)-b;if(w>E)return;let x=1;if(w>0&&(x=E/Math.max(E-w,.1)),this._speedResetTimer&&clearTimeout(this._speedResetTimer),x>4)return;this.audioRenderer.setSpeed(x),this._speedResetTimer=setTimeout(()=>{this.audioRenderer.setSpeed(1),this._speedResetTimer=null},E*v/x),this.dataCacheQueue.checkValidData(e,t);const T=e.map(t=>this.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)}));if(T[0].sid<=this.lastSpeechId)return;var o;this.resourceManager.config.raw_audio?(null==(o=window.avatarSDKLogger)||o.log(this.TAG,"processedAudioData[0].sid",T[0].sid,this.currentSpeechId,this.renderState),this.audioRenderer.updateAudioData(T)):this.audioRenderer._updateAudio(T);break;case EFrameDataType.EVENT:this.dataCacheQueue.clearOldEvent(s);const A=e;this.setEventData({sf:A[0].sf,ef:A[0].ef,event:A[0].e});let R=!1,B=null,C=null;for(const t of A){var l;const e=null!=(l=t.e)?l:[];if(e.some(t=>"speak_start"===t.type)&&(R=!0),t.sf<s&&(B||(B=e.find(t=>"speak_start"===t.type)||null),C||(C=e.find(t=>"voice_start"===t.type)||null),B&&C))break}if(R&&this.audioRenderer.isPlaying){var h;this.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});const t=A.flatMap(t=>{var e;return null!=(e=t.e)?e:[]}).find(t=>"speak_start"===t.type),e=null!=(h=null==t?void 0:t.speech_id)?h:0,n=this.audioRenderer.speech_id;var d,c;-1!==n&&n<e&&(this.interrupt("new_speak_start",n),-1!==this.audioRenderer.speech_id&&this.audioRenderer.pause()),t&&(this.currentSpeechId=null!=(d=t.speech_id)?d:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=(c=t.speech_id)?c:0)}if(B){const{speech_id:t,client_speak_id:e}=B;this.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),this.currentSpeechId=null!=t?t:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=t?t:0,this.config.onSpeakStateChange("speak_start",null!=e?e:0)}if(C){var u,f;this.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});const t=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.config.onVoiceStateChange("start",t,null!=(u=null==(f=C)?void 0:f.client_speak_id)?u:"")}const k=A.filter(t=>-1===t.sf&&-1===t.ef);for(const t of k)for(let e=0;e<t.e.length;e++){const n=t.e[e];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(n);else if(WidgetDefaultRenderer.PROXY_WIDGET){var p,_;null==(p=WidgetDefaultRenderer.PROXY_WIDGET)||null==(_=p[n.type])||_.call(p,n)}}const I=A.filter(t=>-1!==t.sf);this.dataCacheQueue._updateUiEvent(I);break;case EFrameDataType.SYNC_FRAME:const P=e;if(null!=(n=this.sdk.getOptions().config)&&n.replay||(null==P?void 0:P.source)!==FRAME_SOURCE_SOURCE)return;const D=Date.now()/1e3,U=null!=(i=P.client_time)?i:0,O=((null!=(r=P.server_client_frame)?r:0)+(D-U)/2*24).toFixed(0);this.offsetFrame+=Number(O)-Number(null!=s?s:0);break;default:this.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}}setOffsetFrame(t){this.offsetFrame+=t}setVolume(t){this.audioRenderer.setVolume(t)}runStartFrameIndex(){var t;null==(t=this.frameAnimationController)||t.play()}stateChangeHandle(t){this.dataCacheQueue.currentPlayState=t}stopAudio(t){this.audioRenderer.stop(t)}render(){if(this.audioOnlyMode)return this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState),void this.onDownloadProgress(100);this.avatarRenderer.createPipeline(),this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState)}stop(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()}pauseRender(){var t,e;this.renderState!==RenderState.paused&&(null==(t=this.frameAnimationController)||t.pause(),this.decoder.abort(),this.audioRenderer.stop(-1),this.dataCacheQueue.clearAllFaceData(),this.renderState=RenderState.paused,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG,`渲染已暂停(已清空表情数据,等待恢复): ${this.renderState}`))}resumeRender(){var t,e;this.renderState===RenderState.paused&&(this.avatarRenderer.createPipeline(),this.avatarRenderer.resetFaceFrameState(),null==(t=this.frameAnimationController)||t.play(),this.isStartPlay=!0,this.forceSyncDecoder(),this.renderState=RenderState.resumed,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG," 渲染已恢复,状态: this.currentSpeechId==="))}switchInvisibleMode(){var t;if(this.renderState===RenderState.rendering||this.renderState===RenderState.resumed)null==(t=window.avatarSDKLogger)||t.log(this.TAG,"switchInvisibleMode: rendering to paused"),this.pauseRender();else if(this.renderState===RenderState.paused){var e;null==(e=window.avatarSDKLogger)||e.log(this.TAG,"switchInvisibleMode: paused to rendering"),this.resumeRender()}else{var n;null==(n=window.avatarSDKLogger)||n.warn(this.TAG,`渲染状态为 ${this.renderState},无法切换隐身模式`)}}getRenderState(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,`getRenderState: ${this.renderState}`),this.renderState}destroy(){var t;this.isStartPlay=!1,this.hasSendTimeJson=!1,this.offsetFrame=0,this._speedResetTimer=null,null==(t=this.frameAnimationController)||t.destroy(),this.frameAnimationController=void 0,this.dataCacheQueue.destroy(),this.composition.destroy(),this.decoder.destroy()}handleFaceData(t){try{var e;const n=this.resourceManager.resource_pack,i=this.resourceManager.getConfig().framedata_proto_version,r=[...null!=(e=n.blendshape_map)?e:[]];return t.map(t=>{let e=[];const{body_id:n,sf:s,ef:a,s:o,id:l,js:h,bsw:d,ms:c,face_frame_type:u,asf:f,aef:p,n:_,cs:m}=t;let g=[];if((null==r?void 0:r.length)>0){for(let t=0;t<r.length;t++){const n=r[t];if((null==n?void 0:n.length)>0)for(let i=0;i<n.length;i++)e[t]||(e[t]=[]),e[t][i]=d[n[i]]}g=Array.from({length:c.length},i?(t,n)=>{var i,r,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(i=null==(r=c[n])?void 0:r.index)?i:0,texturePCAWeights:null!=(s=null==(a=c[n])?void 0:a.weights)?s:[]}}:(t,n)=>{var i,r,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(i=null==(r=c[n])?void 0:r[0])?i:0,texturePCAWeights:null!=(s=null==(a=c[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:c.length},i?(t,e)=>{var n,i,r,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(i=c[e])?void 0:i.index)?n:0,texturePCAWeights:null!=(r=null==(s=c[e])?void 0:s.weights)?r:[]}}:(t,e)=>{var n,i,r,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(i=c[e])?void 0:i[0])?n:0,texturePCAWeights:null!=(r=null==(s=c[e])?void 0:s[1])?r:[]}});let y=[];return y=h.map(i?t=>formatMJT(t.translate,t.rotate):t=>formatMJT(t[0],t[1])),{body_id:n,frameIndex:s,sf:s,ef:a,asf:f,aef:p,n:_,cs:m,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:y,blendshapeWeights:d}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}}forceSyncDecoder(){const t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)}_reload(){this.decoder._reload()}_getResumeInfo(){const t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)}sendVoiceEnd(){var t,e,n;const i=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:i,ef:i+1,e:[{type:"speak_end",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1},{type:"voice_end",speech_id:null!=(n=this.uiRenderer.lastSpeechId)?n:-1}]}])}markReconnectRecover(){this.audioRenderer.resume(),this.decoder._reload()}_offlineMode(){var t,e;this.dataCacheQueue._clearEvent();const n=null!=(t=this.getCurrentFrameIndex())?t:0;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:n+1,ef:n+2,e:[{type:"subtitle_off",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1}]}]),this.audioRenderer.pause();const i=this.getCurrentFrameIndex();i&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),i),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1}_offlineRun(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()}ttsaStateChangeHandle(t){this.dataCacheQueue.currentTtsaState=t}resume(){this.audioRenderer.resume()}pauseForBackground(){this.audioRenderer.pause()}setAvatarCanvasVisible(t){this.avatarRenderer.setCanvasVisibility(t)}setCharacterCanvasLayout(t){this.avatarRenderer.setCharacterCanvasAnchor(t)}setWalkConfig(t){this.avatarRenderer.setWalkConfig(t)}interrupt(t,e){var n;const i=Date.now(),r=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:r,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(r),this.dataCacheQueue.clearSubtitleOn(r);const s=null!=(n=this.getCurrentFrameIndex())?n:0;return this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:s+1,ef:s+2,e:[{type:"subtitle_off",speech_id:null!=r?r:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(r),this.uiRenderer.setInterrupt(r),Date.now()-i}seekToFrame(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)}getCurrentFrameIndex(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame}getSpeechId(){return this.audioRenderer.speech_id}getAudioRenderer(){return this.audioRenderer}simulateContextLoss(t=5e3,e=!1){this.avatarRenderer.simulateContextLoss(t,e)}getRecoveryStatus(){return this.avatarRenderer.getRecoveryStatus()}async testStagedRecovery(){return this.avatarRenderer.testStagedRecovery()}restartWebGL(){return this.avatarRenderer.restartWebGL()}}const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(t){let e=t.length;for(;--e>=0;)t[e]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);const static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);function StaticTreeDesc(t,e,n,i,r){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=t&&t.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}zero$1(base_dist);const d_code=t=>t<256?_dist_code[t]:_dist_code[256+(t>>>7)],put_short=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},send_bits=(t,e,n)=>{t.bi_valid>Buf_size-n?(t.bi_buf|=e<<t.bi_valid&65535,put_short(t,t.bi_buf),t.bi_buf=e>>Buf_size-t.bi_valid,t.bi_valid+=n-Buf_size):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=n)},send_code=(t,e,n)=>{send_bits(t,n[2*e],n[2*e+1])},bi_reverse=(t,e)=>{let n=0;do{n|=1&t,t>>>=1,n<<=1}while(--e>0);return n>>>1},bi_flush=t=>{16===t.bi_valid?(put_short(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)},gen_bitlen=(t,e)=>{const n=e.dyn_tree,i=e.max_code,r=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,c,u,f,p,_=0;for(u=0;u<=MAX_BITS$1;u++)t.bl_count[u]=0;for(n[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<HEAP_SIZE$1;h++)d=t.heap[h],u=n[2*n[2*d+1]+1]+1,u>l&&(u=l,_++),n[2*d+1]=u,d>i||(t.bl_count[u]++,f=0,d>=o&&(f=a[d-o]),p=n[2*d],t.opt_len+=p*(u+f),s&&(t.static_len+=p*(r[2*d+1]+f)));if(0!==_){do{for(u=l-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[l]--,_-=2}while(_>0);for(u=l;0!==u;u--)for(d=t.bl_count[u];0!==d;)c=t.heap[--h],c>i||(n[2*c+1]!==u&&(t.opt_len+=(u-n[2*c+1])*n[2*c],n[2*c+1]=u),d--)}},gen_codes=(t,e,n)=>{const i=new Array(MAX_BITS$1+1);let r,s,a=0;for(r=1;r<=MAX_BITS$1;r++)a=a+n[r-1]<<1,i[r]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(i[e]++,e))}},tr_static_init=()=>{let t,e,n,i,r;const s=new Array(MAX_BITS$1+1);for(n=0,i=0;i<LENGTH_CODES$1-1;i++)for(base_length[i]=n,t=0;t<1<<extra_lbits[i];t++)_length_code[n++]=i;for(_length_code[n-1]=i,r=0,i=0;i<16;i++)for(base_dist[i]=r,t=0;t<1<<extra_dbits[i];t++)_dist_code[r++]=i;for(r>>=7;i<D_CODES$1;i++)for(base_dist[i]=r<<7,t=0;t<1<<extra_dbits[i]-7;t++)_dist_code[256+r++]=i;for(e=0;e<=MAX_BITS$1;e++)s[e]=0;for(t=0;t<=143;)static_ltree[2*t+1]=8,t++,s[8]++;for(;t<=255;)static_ltree[2*t+1]=9,t++,s[9]++;for(;t<=279;)static_ltree[2*t+1]=7,t++,s[7]++;for(;t<=287;)static_ltree[2*t+1]=8,t++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),t=0;t<D_CODES$1;t++)static_dtree[2*t+1]=5,static_dtree[2*t]=bi_reverse(t,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=t=>{let e;for(e=0;e<L_CODES$1;e++)t.dyn_ltree[2*e]=0;for(e=0;e<D_CODES$1;e++)t.dyn_dtree[2*e]=0;for(e=0;e<BL_CODES$1;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*END_BLOCK]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},bi_windup=t=>{t.bi_valid>8?put_short(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},smaller=(t,e,n,i)=>{const r=2*e,s=2*n;return t[r]<t[s]||t[r]===t[s]&&i[e]<=i[n]},pqdownheap=(t,e,n)=>{const i=t.heap[n];let r=n<<1;for(;r<=t.heap_len&&(r<t.heap_len&&smaller(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!smaller(e,i,t.heap[r],t.depth));)t.heap[n]=t.heap[r],n=r,r<<=1;t.heap[n]=i},compress_block=(t,e,n)=>{let i,r,s,a,o=0;if(0!==t.sym_next)do{i=255&t.pending_buf[t.sym_buf+o++],i+=(255&t.pending_buf[t.sym_buf+o++])<<8,r=t.pending_buf[t.sym_buf+o++],0===i?send_code(t,r,e):(s=_length_code[r],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(r-=base_length[s],send_bits(t,r,a)),i--,s=d_code(i),send_code(t,s,n),a=extra_dbits[s],0!==a&&(i-=base_dist[s],send_bits(t,i,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,i=e.stat_desc.static_tree,r=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,l,h=-1;for(t.heap_len=0,t.heap_max=HEAP_SIZE$1,a=0;a<s;a++)0!==n[2*a]?(t.heap[++t.heap_len]=h=a,t.depth[a]=0):n[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=h<2?++h:0,n[2*l]=1,t.depth[l]=0,t.opt_len--,r&&(t.static_len-=i[2*l+1]);for(e.max_code=h,a=t.heap_len>>1;a>=1;a--)pqdownheap(t,n,a);l=s;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],pqdownheap(t,n,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,n[2*l]=n[2*a]+n[2*o],t.depth[l]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,n[2*a+1]=n[2*o+1]=l,t.heap[1]=l++,pqdownheap(t,n,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],gen_bitlen(t,e),gen_codes(n,h,t.bl_count)},scan_tree=(t,e,n)=>{let i,r,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),e[2*(n+1)+1]=65535,i=0;i<=n;i++)r=a,a=e[2*(i+1)+1],++o<l&&r===a||(o<h?t.bl_tree[2*r]+=o:0!==r?(r!==s&&t.bl_tree[2*r]++,t.bl_tree[2*REP_3_6]++):o<=10?t.bl_tree[2*REPZ_3_10]++:t.bl_tree[2*REPZ_11_138]++,o=0,s=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4))},send_tree=(t,e,n)=>{let i,r,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),i=0;i<=n;i++)if(r=a,a=e[2*(i+1)+1],!(++o<l&&r===a)){if(o<h)do{send_code(t,r,t.bl_tree)}while(0!==--o);else 0!==r?(r!==s&&(send_code(t,r,t.bl_tree),o--),send_code(t,REP_3_6,t.bl_tree),send_bits(t,o-3,2)):o<=10?(send_code(t,REPZ_3_10,t.bl_tree),send_bits(t,o-3,3)):(send_code(t,REPZ_11_138,t.bl_tree),send_bits(t,o-11,7));o=0,s=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4)}},build_bl_tree=t=>{let e;for(scan_tree(t,t.dyn_ltree,t.l_desc.max_code),scan_tree(t,t.dyn_dtree,t.d_desc.max_code),build_tree(t,t.bl_desc),e=BL_CODES$1-1;e>=3&&0===t.bl_tree[2*bl_order[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e},send_all_trees=(t,e,n,i)=>{let r;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,i-4,4),r=0;r<i;r++)send_bits(t,t.bl_tree[2*bl_order[r]+1],3);send_tree(t,t.dyn_ltree,e-1),send_tree(t,t.dyn_dtree,n-1)},detect_data_type=t=>{let e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return Z_BINARY;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return Z_TEXT;for(e=32;e<LITERALS$1;e++)if(0!==t.dyn_ltree[2*e])return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=t=>{static_init_done||(tr_static_init(),static_init_done=!0),t.l_desc=new TreeDesc(t.dyn_ltree,static_l_desc),t.d_desc=new TreeDesc(t.dyn_dtree,static_d_desc),t.bl_desc=new TreeDesc(t.bl_tree,static_bl_desc),t.bi_buf=0,t.bi_valid=0,init_block(t)},_tr_stored_block$1=(t,e,n,i)=>{send_bits(t,(STORED_BLOCK<<1)+(i?1:0),3),bi_windup(t),put_short(t,n),put_short(t,~n),n&&t.pending_buf.set(t.window.subarray(e,e+n),t.pending),t.pending+=n},_tr_align$1=t=>{send_bits(t,STATIC_TREES<<1,3),send_code(t,END_BLOCK,static_ltree),bi_flush(t)},_tr_flush_block$1=(t,e,n,i)=>{let r,s,a=0;t.level>0?(t.strm.data_type===Z_UNKNOWN$1&&(t.strm.data_type=detect_data_type(t)),build_tree(t,t.l_desc),build_tree(t,t.d_desc),a=build_bl_tree(t),r=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=r&&(r=s)):r=s=n+5,n+4<=r&&-1!==e?_tr_stored_block$1(t,e,n,i):t.strategy===Z_FIXED$1||s===r?(send_bits(t,(STATIC_TREES<<1)+(i?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(i?1:0),3),send_all_trees(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),compress_block(t,t.dyn_ltree,t.dyn_dtree)),init_block(t),i&&bi_windup(t)},_tr_tally$1=(t,e,n)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=n,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(_length_code[n]+LITERALS$1+1)]++,t.dyn_dtree[2*d_code(e)]++),t.sym_next===t.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(t,e,n,i)=>{let r=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{r=r+e[i++]|0,s=s+r|0}while(--a);r%=65521,s%=65521}return r|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,i)=>{const r=crcTable,s=i+n;t^=-1;for(let n=i;n<s;n++)t=t>>>8^r[255&(t^e[n])];return-1^t};var crc32_1=crc32,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(t,e)=>(t.msg=messages[e],e),rank=t=>2*t-(t>4?9:0),zero=t=>{let e=t.length;for(;--e>=0;)t[e]=0},slide_hash=t=>{let e,n,i,r=t.w_size;e=t.hash_size,i=e;do{n=t.head[--i],t.head[i]=n>=r?n-r:0}while(--e);e=r,i=e;do{n=t.prev[--i],t.prev[i]=n>=r?n-r:0}while(--e)};let HASH_ZLIB=(t,e,n)=>(e<<t.hash_shift^n)&t.hash_mask,HASH=HASH_ZLIB;const flush_pending=t=>{const e=t.state;let n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+n),t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))},flush_block_only=(t,e)=>{_tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,flush_pending(t.strm)},put_byte=(t,e)=>{t.pending_buf[t.pending++]=e},putShortMSB=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},read_buf=(t,e,n,i)=>{let r=t.avail_in;return r>i&&(r=i),0===r?0:(t.avail_in-=r,e.set(t.input.subarray(t.next_in,t.next_in+r),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,r,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,r,n)),t.next_in+=r,t.total_in+=r,r)},longest_match=(t,e)=>{let n,i,r=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-MIN_LOOKAHEAD?t.strstart-(t.w_size-MIN_LOOKAHEAD):0,h=t.window,d=t.w_mask,c=t.prev,u=t.strstart+MAX_MATCH;let f=h[s+a-1],p=h[s+a];t.prev_length>=t.good_match&&(r>>=2),o>t.lookahead&&(o=t.lookahead);do{if(n=e,h[n+a]===p&&h[n+a-1]===f&&h[n]===h[s]&&h[++n]===h[s+1]){s+=2,n++;do{}while(h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&h[++s]===h[++n]&&s<u);if(i=MAX_MATCH-(u-s),s=u-MAX_MATCH,i>a){if(t.match_start=e,a=i,i>=o)break;f=h[s+a-1],p=h[s+a]}}}while((e=c[e&d])>l&&0!==--r);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,i,r;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),i+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=HASH(t,t.ins_h,t.window[r+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[r+MIN_MATCH-1]),t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,i,r,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,a=0,o=t.strm.avail_in;do{if(n=65535,r=t.bi_valid+42>>3,t.strm.avail_out<r)break;if(r=t.strm.avail_out-r,i=t.strstart-t.block_start,n>i+t.strm.avail_in&&(n=i+t.strm.avail_in),n>r&&(n=r),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==i+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===i+t.strm.avail_in?1:0,_tr_stored_block(t,0,0,a),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,flush_pending(t.strm),i&&(i>n&&(i=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,n-=i),n&&(read_buf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(0===a);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),a?BS_FINISH_DONE:e!==Z_NO_FLUSH$2&&e!==Z_FINISH$3&&0===t.strm.avail_in&&t.strstart===t.block_start?BS_BLOCK_DONE:(r=t.window_size-t.strstart,t.strm.avail_in>r&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,r+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),r>t.strm.avail_in&&(r=t.strm.avail_in),r&&(read_buf(t.strm,t.window,t.strstart,r),t.strstart+=r,t.insert+=r>t.w_size-t.insert?t.w_size-t.insert:r),t.high_water<t.strstart&&(t.high_water=t.strstart),r=t.bi_valid+42>>3,r=t.pending_buf_size-r>65535?65535:t.pending_buf_size-r,s=r>t.w_size?t.w_size:r,i=t.strstart-t.block_start,(i>=s||(i||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&i<=r)&&(n=i>r?r:i,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===i?1:0,_tr_stored_block(t,t.block_start,n,a),t.block_start+=n,flush_pending(t.strm)),a?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(t,e)=>{let n,i;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(i=_tr_tally(t,t.strstart-t.match_start,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=MIN_MATCH){t.match_length--;do{t.strstart++,t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+1]);else i=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(t,e)=>{let n,i,r;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=MIN_MATCH-1,0!==n&&t.prev_length<t.max_lazy_match&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n),t.match_length<=5&&(t.strategy===Z_FILTERED||t.match_length===MIN_MATCH&&t.strstart-t.match_start>4096)&&(t.match_length=MIN_MATCH-1)),t.prev_length>=MIN_MATCH&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-MIN_MATCH,i=_tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-MIN_MATCH),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=MIN_MATCH-1,t.strstart++,i&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(i=_tr_tally(t,0,t.window[t.strstart-1]),i&&flush_block_only(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return BS_NEED_MORE}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=_tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(t,e)=>{let n,i,r,s;const a=t.window;for(;;){if(t.lookahead<=MAX_MATCH){if(fill_window(t),t.lookahead<=MAX_MATCH&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=MIN_MATCH&&t.strstart>0&&(r=t.strstart-1,i=a[r],i===a[++r]&&i===a[++r]&&i===a[++r])){s=t.strstart+MAX_MATCH;do{}while(i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&r<s);t.match_length=MAX_MATCH-(s-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=MIN_MATCH?(n=_tr_tally(t,1,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(t,e)=>{let n;for(;;){if(0===t.lookahead&&(fill_window(t),0===t.lookahead)){if(e===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(t.match_length=0,n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(t,e,n,i,r){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=i,this.func=r}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=t=>{t.window_size=2*t.w_size,zero(t.head),t.max_lazy_match=configuration_table[t.level].max_lazy,t.good_match=configuration_table[t.level].good_length,t.nice_match=configuration_table[t.level].nice_length,t.max_chain_length=configuration_table[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=MIN_MATCH-1,t.match_available=0,t.ins_h=0};function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*HEAP_SIZE),this.dyn_dtree=new Uint16Array(2*(2*D_CODES+1)),this.bl_tree=new Uint16Array(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==INIT_STATE&&e.status!==GZIP_STATE&&e.status!==EXTRA_STATE&&e.status!==NAME_STATE&&e.status!==COMMENT_STATE&&e.status!==HCRC_STATE&&e.status!==BUSY_STATE&&e.status!==FINISH_STATE?1:0},deflateResetKeep=t=>{if(deflateStateCheck(t))return err(t,Z_STREAM_ERROR$2);t.total_in=t.total_out=0,t.data_type=Z_UNKNOWN;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?GZIP_STATE:e.wrap?INIT_STATE:BUSY_STATE,t.adler=2===e.wrap?0:1,e.last_flush=-2,_tr_init(e),Z_OK$3},deflateReset=t=>{const e=deflateResetKeep(t);return e===Z_OK$3&&lm_init(t.state),e},deflateSetHeader=(t,e)=>deflateStateCheck(t)||2!==t.state.wrap?Z_STREAM_ERROR$2:(t.state.gzhead=e,Z_OK$3),deflateInit2=(t,e,n,i,r,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),r<1||r>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||i<8||i>15||e<0||e>9||s<0||s>Z_FIXED||8===i&&1!==a)return err(t,Z_STREAM_ERROR$2);8===i&&(i=9);const o=new DeflateState;return t.state=o,o.strm=t,o.status=INIT_STATE,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=n,deflateReset(t)},deflateInit=(t,e)=>deflateInit2(t,e,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(t,e)=>{if(deflateStateCheck(t)||e>Z_BLOCK$1||e<0)return t?err(t,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=t.state;if(!t.output||0!==t.avail_in&&!t.input||n.status===FINISH_STATE&&e!==Z_FINISH$3)return err(t,0===t.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const i=n.last_flush;if(n.last_flush=e,0!==n.pending){if(flush_pending(t),0===t.avail_out)return n.last_flush=-1,Z_OK$3}else if(0===t.avail_in&&rank(e)<=rank(i)&&e!==Z_FINISH$3)return err(t,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&0!==t.avail_in)return err(t,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&0===n.wrap&&(n.status=BUSY_STATE),n.status===INIT_STATE){let e=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=i<<6,0!==n.strstart&&(e|=PRESET_DICT),e+=31-e%31,putShortMSB(n,e),0!==n.strstart&&(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),t.adler=1,n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE)if(t.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,255&n.gzhead.time),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,255&n.gzhead.extra.length),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;if(n.status===EXTRA_STATE){if(n.gzhead.extra){let e=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex+=r,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let e,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;i=0}e=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;i=0}e=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>i&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-i,i))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(t),0!==n.pending))return n.last_flush=-1,Z_OK$3;put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),t.adler=0}if(n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(0!==t.avail_in||0!==n.lookahead||e!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let i=0===n.level?deflate_stored(n,e):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,e):n.strategy===Z_RLE?deflate_rle(n,e):configuration_table[n.level].func(n,e);if(i!==BS_FINISH_STARTED&&i!==BS_FINISH_DONE||(n.status=FINISH_STATE),i===BS_NEED_MORE||i===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(i===BS_BLOCK_DONE&&(e===Z_PARTIAL_FLUSH?_tr_align(n):e!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),e===Z_FULL_FLUSH$1&&(zero(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(t),0===t.avail_out))return n.last_flush=-1,Z_OK$3}return e!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(2===n.wrap?(put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),put_byte(n,t.adler>>16&255),put_byte(n,t.adler>>24&255),put_byte(n,255&t.total_in),put_byte(n,t.total_in>>8&255),put_byte(n,t.total_in>>16&255),put_byte(n,t.total_in>>24&255)):(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),flush_pending(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd=t=>{if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const e=t.state.status;return t.state=null,e===BUSY_STATE?err(t,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(t,e)=>{let n=e.length;if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const i=t.state,r=i.wrap;if(2===r||1===r&&i.status!==INIT_STATE||i.lookahead)return Z_STREAM_ERROR$2;if(1===r&&(t.adler=adler32_1(t.adler,e,n,0)),i.wrap=0,n>=i.w_size){0===r&&(zero(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(n-i.w_size,n),0),e=t,n=i.w_size}const s=t.avail_in,a=t.next_in,o=t.input;for(t.avail_in=n,t.next_in=0,t.input=e,fill_window(i);i.lookahead>=MIN_MATCH;){let t=i.strstart,e=i.lookahead-(MIN_MATCH-1);do{i.ins_h=HASH(i,i.ins_h,i.window[t+MIN_MATCH-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=MIN_MATCH-1,fill_window(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=MIN_MATCH-1,i.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,i.wrap=r,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var assign=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const e in n)_has(n,e)&&(t[e]=n[e])}}return t},flattenChunks=t=>{let e=0;for(let n=0,i=t.length;n<i;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,i=0,r=t.length;e<r;e++){let r=t[e];n.set(r,i),i+=r.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let t=0;t<256;t++)_utf8len[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,n,i,r,s,a=t.length,o=0;for(r=0;r<a;r++)n=t.charCodeAt(r),55296==(64512&n)&&r+1<a&&(i=t.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,r=0;s<o;r++)n=t.charCodeAt(r),55296==(64512&n)&&r+1<a&&(i=t.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?e[s++]=n:n<2048?(e[s++]=192|n>>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e};const buf2binstring=(t,e)=>{if(e<65534&&t.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let n="";for(let i=0;i<e;i++)n+=String.fromCharCode(t[i]);return n};var buf2string=(t,e)=>{const n=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,r;const s=new Array(2*n);for(r=0,i=0;i<n;){let e=t[i++];if(e<128){s[r++]=e;continue}let a=_utf8len[e];if(a>4)s[r++]=65533,i+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&i<n;)e=e<<6|63&t[i++],a--;a>1?s[r++]=65533:e<65536?s[r++]=e:(e-=65536,s[r++]=55296|e>>10&1023,s[r++]=56320|1023&e)}}return buf2binstring(s,r)},utf8border=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let n=e-1;for(;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+_utf8len[t[n]]>e?n:e},strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(t){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(e.header&&deflate_1$2.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$1.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,t),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}function deflate$1(t,e){const n=new Deflate$1(e);if(n.push(t,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(t,e){return(e=e||{}).raw=!0,deflate$1(t,e)}function gzip$1(t,e){return(e=e||{}).gzip=!0,deflate$1(t,e)}Deflate$1.prototype.push=function(t,e){const n=this.strm,i=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Z_FINISH$2:Z_NO_FLUSH$1,n.input="string"==typeof t?strings.string2buf(t):"[object ArrayBuffer]"===toString$1.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=deflate_1$2.deflate(n,s),r===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=deflate_1$2.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===Z_OK$2;if(0!==n.avail_out){if(s>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},Deflate$1.prototype.onData=function(t){this.chunks.push(t)},Deflate$1.prototype.onEnd=function(t){t===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function(t,e){let n,i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x,T;const A=t.state;n=t.next_in,x=t.input,i=n+(t.avail_in-5),r=t.next_out,T=t.output,s=r-(e-t.avail_out),a=r+(t.avail_out-257),o=A.dmax,l=A.wsize,h=A.whave,d=A.wnext,c=A.window,u=A.hold,f=A.bits,p=A.lencode,_=A.distcode,m=(1<<A.lenbits)-1,g=(1<<A.distbits)-1;t:do{f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),y=p[u&m];e:for(;;){if(v=y>>>24,u>>>=v,f-=v,v=y>>>16&255,0===v)T[r++]=65535&y;else{if(!(16&v)){if(64&v){if(32&v){A.mode=TYPE$1;break t}t.msg="invalid literal/length code",A.mode=BAD$1;break t}y=p[(65535&y)+(u&(1<<v)-1)];continue e}for(b=65535&y,v&=15,v&&(f<v&&(u+=x[n++]<<f,f+=8),b+=u&(1<<v)-1,u>>>=v,f-=v),f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),y=_[u&g];;){if(v=y>>>24,u>>>=v,f-=v,v=y>>>16&255,16&v){if(S=65535&y,v&=15,f<v&&(u+=x[n++]<<f,f+=8,f<v&&(u+=x[n++]<<f,f+=8)),S+=u&(1<<v)-1,S>o){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(u>>>=v,f-=v,v=r-s,S>v){if(v=S-v,v>h&&A.sane){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(E=0,w=c,0===d){if(E+=l-v,v<b){b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}}else if(d<v){if(E+=l+d-v,v-=d,v<b){b-=v;do{T[r++]=c[E++]}while(--v);if(E=0,d<b){v=d,b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}}}else if(E+=d-v,v<b){b-=v;do{T[r++]=c[E++]}while(--v);E=r-S,w=T}for(;b>2;)T[r++]=w[E++],T[r++]=w[E++],T[r++]=w[E++],b-=3;b&&(T[r++]=w[E++],b>1&&(T[r++]=w[E++]))}else{E=r-S;do{T[r++]=T[E++],T[r++]=T[E++],T[r++]=T[E++],b-=3}while(b>2);b&&(T[r++]=T[E++],b>1&&(T[r++]=T[E++]))}break}if(64&v){t.msg="invalid distance code",A.mode=BAD$1;break t}y=_[(65535&y)+(u&(1<<v)-1)]}}break}}while(n<i&&r<a);b=f>>3,n-=b,f-=b<<3,u&=(1<<f)-1,t.next_in=n,t.next_out=r,t.avail_in=n<i?i-n+5:5-(n-i),t.avail_out=r<a?a-r+257:257-(r-a),A.hold=u,A.bits=f};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table=(t,e,n,i,r,s,a,o)=>{const l=o.bits;let h,d,c,u,f,p,_=0,m=0,g=0,y=0,v=0,b=0,S=0,E=0,w=0,x=0,T=null;const A=new Uint16Array(MAXBITS+1),R=new Uint16Array(MAXBITS+1);let B,C,k,I=null;for(_=0;_<=MAXBITS;_++)A[_]=0;for(m=0;m<i;m++)A[e[n+m]]++;for(v=l,y=MAXBITS;y>=1&&0===A[y];y--);if(v>y&&(v=y),0===y)return r[s++]=20971520,r[s++]=20971520,o.bits=1,0;for(g=1;g<y&&0===A[g];g++);for(v<g&&(v=g),E=1,_=1;_<=MAXBITS;_++)if(E<<=1,E-=A[_],E<0)return-1;if(E>0&&(t===CODES$1||1!==y))return-1;for(R[1]=0,_=1;_<MAXBITS;_++)R[_+1]=R[_]+A[_];for(m=0;m<i;m++)0!==e[n+m]&&(a[R[e[n+m]]++]=m);if(t===CODES$1?(T=I=a,p=20):t===LENS$1?(T=lbase,I=lext,p=257):(T=dbase,I=dext,p=0),x=0,m=0,_=g,f=s,b=v,S=0,c=-1,w=1<<v,u=w-1,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;for(;;){B=_-S,a[m]+1<p?(C=0,k=a[m]):a[m]>=p?(C=I[a[m]-p],k=T[a[m]-p]):(C=96,k=0),h=1<<_-S,d=1<<b,g=d;do{d-=h,r[f+(x>>S)+d]=B<<24|C<<16|k}while(0!==d);for(h=1<<_-1;x&h;)h>>=1;if(0!==h?(x&=h-1,x+=h):x=0,m++,0===--A[_]){if(_===y)break;_=e[n+a[m]]}if(_>v&&(x&u)!==c){for(0===S&&(S=v),f+=g,b=_-S,E=1<<b;b+S<y&&(E-=A[b+S],!(E<=0));)b++,E<<=1;if(w+=1<<b,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;c=x&u,r[c]=v<<24|b<<16|f-s}}return 0!==x&&(r[f+x]=_-S<<24|64<<16),o.bits=v,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<HEAD||e.mode>SYNC?1:0},inflateResetKeep=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=HEAD,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(ENOUGH_LENS),e.distcode=e.distdyn=new Int32Array(ENOUGH_DISTS),e.sane=1,e.back=-1,Z_OK$1},inflateReset=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,inflateResetKeep(t)},inflateReset2=(t,e)=>{let n;if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const i=t.state;return e<0?(n=0,e=-e):(n=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Z_STREAM_ERROR$1:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=n,i.wbits=e,inflateReset(t))},inflateInit2=(t,e)=>{if(!t)return Z_STREAM_ERROR$1;const n=new InflateState;t.state=n,n.strm=t,n.window=null,n.mode=HEAD;const i=inflateReset2(t,e);return i!==Z_OK$1&&(t.state=null),i},inflateInit=t=>inflateInit2(t,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=t=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(inftrees(LENS,t.lens,0,288,lenfix,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;inftrees(DISTS,t.lens,0,32,distfix,0,t.work,{bits:5}),virgin=!1}t.lencode=lenfix,t.lenbits=9,t.distcode=distfix,t.distbits=5},updatewindow=(t,e,n,i)=>{let r;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>i&&(r=i),s.window.set(e.subarray(n-i,n-i+r),s.wnext),(i-=r)?(s.window.set(e.subarray(n-i,n),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0},inflate$2=(t,e)=>{let n,i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x=0;const T=new Uint8Array(4);let A,R;const B=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(t)||!t.output||!t.input&&0!==t.avail_in)return Z_STREAM_ERROR$1;n=t.state,n.mode===TYPE&&(n.mode=TYPEDO),a=t.next_out,r=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=n.hold,d=n.bits,c=o,u=l,w=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&n.wrap&&35615===h){0===n.wbits&&(n.wbits=15),n.check=0,T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0),h=0,d=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",n.mode=BAD;break}if((15&h)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(h>>>=4,d-=4,E=8+(15&h),0===n.wbits&&(n.wbits=E),E>15||E>n.wbits){t.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,t.adler=n.check=1,n.mode=512&h?DICTID:TYPE,h=0,d=0;break;case FLAGS:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(n.flags=h,(255&n.flags)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(57344&n.flags){t.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=h>>8&1),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.head&&(n.head.time=h),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,T[2]=h>>>16&255,T[3]=h>>>24&255,n.check=crc32_1(n.check,T,4,0)),h=0,d=0,n.mode=OS;case OS:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.head&&(n.head.xflags=255&h,n.head.os=h>>8),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.length=h,n.head&&(n.head.extra_len=h),512&n.flags&&4&n.wrap&&(T[0]=255&h,T[1]=h>>>8&255,n.check=crc32_1(n.check,T,2,0)),h=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(1024&n.flags&&(f=n.length,f>o&&(f=o),f&&(n.head&&(E=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(s,s+f),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,n.length-=f),n.length))break t;n.length=0,n.mode=NAME;case NAME:if(2048&n.flags){if(0===o)break t;f=0;do{E=i[s+f++],n.head&&E&&n.length<65536&&(n.head.name+=String.fromCharCode(E))}while(E&&f<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,E)break t}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(4096&n.flags){if(0===o)break t;f=0;do{E=i[s+f++],n.head&&E&&n.length<65536&&(n.head.comment+=String.fromCharCode(E))}while(E&&f<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,i,f,s)),o-=f,s+=f,E)break t}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(512&n.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&n.wrap&&h!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}h=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=n.check=zswap32(h),h=0,d=0,n.mode=DICT;case DICT:if(0===n.havedict)return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,Z_NEED_DICT$1;t.adler=n.check=1,n.mode=TYPE;case TYPE:if(e===Z_BLOCK||e===Z_TREES)break t;case TYPEDO:if(n.last){h>>>=7&d,d-=7&d,n.mode=CHECK;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(n.last=1&h,h>>>=1,d-=1,3&h){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){h>>>=2,d-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}h>>>=2,d-=2;break;case STORED:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&h,h=0,d=0,n.mode=COPY_,e===Z_TREES)break t;case COPY_:n.mode=COPY;case COPY:if(f=n.length,f){if(f>o&&(f=o),f>l&&(f=l),0===f)break t;r.set(i.subarray(s,s+f),a),o-=f,s+=f,l-=f,a+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(n.nlen=257+(31&h),h>>>=5,d-=5,n.ndist=1+(31&h),h>>>=5,d-=5,n.ncode=4+(15&h),h>>>=4,d-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.lens[B[n.have++]]=7&h,h>>>=3,d-=3}for(;n.have<19;)n.lens[B[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,A={bits:n.lenbits},w=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,A),n.lenbits=A.bits,w){t.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;x=n.lencode[h&(1<<n.lenbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(y<16)h>>>=m,d-=m,n.lens[n.have++]=y;else{if(16===y){for(R=m+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=m,d-=m,0===n.have){t.msg="invalid bit length repeat",n.mode=BAD;break}E=n.lens[n.have-1],f=3+(3&h),h>>>=2,d-=2}else if(17===y){for(R=m+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,E=0,f=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,E=0,f=11+(127&h),h>>>=7,d-=7}if(n.have+f>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=BAD;break}for(;f--;)n.lens[n.have++]=E}}if(n.mode===BAD)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,A={bits:n.lenbits},w=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,A),n.lenbits=A.bits,w){t.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,A={bits:n.distbits},w=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,A),n.distbits=A.bits,w){t.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,e===Z_TREES)break t;case LEN_:n.mode=LEN;case LEN:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,inffast(t,u),a=t.next_out,r=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;x=n.lencode[h&(1<<n.lenbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g&&!(240&g)){for(v=m,b=g,S=y;x=n.lencode[S+((h&(1<<v+b)-1)>>v)],m=x>>>24,g=x>>>16&255,y=65535&x,!(v+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=v,d-=v,n.back+=v}if(h>>>=m,d-=m,n.back+=m,n.length=y,0===g){n.mode=LIT;break}if(32&g){n.back=-1,n.mode=TYPE;break}if(64&g){t.msg="invalid literal/length code",n.mode=BAD;break}n.extra=15&g,n.mode=LENEXT;case LENEXT:if(n.extra){for(R=n.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.length+=h&(1<<n.extra)-1,h>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;x=n.distcode[h&(1<<n.distbits)-1],m=x>>>24,g=x>>>16&255,y=65535&x,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(!(240&g)){for(v=m,b=g,S=y;x=n.distcode[S+((h&(1<<v+b)-1)>>v)],m=x>>>24,g=x>>>16&255,y=65535&x,!(v+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=v,d-=v,n.back+=v}if(h>>>=m,d-=m,n.back+=m,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(R=n.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}n.offset+=h&(1<<n.extra)-1,h>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(0===l)break t;if(f=u-l,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=BAD;break}f>n.wnext?(f-=n.wnext,p=n.wsize-f):p=n.wnext-f,f>n.length&&(f=n.length),_=n.window}else _=r,p=a-n.offset,f=n.length;f>l&&(f=l),l-=f,n.length-=f;do{r[a++]=_[p++]}while(--f);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;r[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(u-=l,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,r,u,a-u):adler32_1(n.check,r,u,a-u)),u=l,4&n.wrap&&(n.flags?h:zswap32(h))!==n.check){t.msg="incorrect data check",n.mode=BAD;break}h=0,d=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&n.wrap&&h!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}h=0,d=0}n.mode=DONE;case DONE:w=Z_STREAM_END$1;break t;case BAD:w=Z_DATA_ERROR$1;break t;case MEM:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=h,n.bits=d,(n.wsize||u!==t.avail_out&&n.mode<BAD&&(n.mode<CHECK||e!==Z_FINISH$1))&&updatewindow(t,t.output,t.next_out,u-t.avail_out),c-=t.avail_in,u-=t.avail_out,t.total_in+=c,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,r,u,t.next_out-u):adler32_1(n.check,r,u,t.next_out-u)),t.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(0===c&&0===u||e===Z_FINISH$1)&&w===Z_OK$1&&(w=Z_BUF_ERROR),w},inflateEnd=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;let e=t.state;return e.window&&(e.window=null),t.state=null,Z_OK$1},inflateGetHeader=(t,e)=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const n=t.state;return 2&n.wrap?(n.head=e,e.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(t,e)=>{const n=e.length;let i,r,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(i=t.state,0!==i.wrap&&i.mode!==DICT?Z_STREAM_ERROR$1:i.mode===DICT&&(r=1,r=adler32_1(r,e,n,0),r!==i.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(i.mode=MEM,Z_MEM_ERROR$1):(i.havedict=1,Z_OK$1)))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString$2=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(t){this.options=common.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(15&e.windowBits||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,e.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$2.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,e.dictionary),n!==Z_OK)))throw new Error(messages[n])}function inflate$1(t,e){const n=new Inflate$1(e);if(n.push(t),n.err)throw n.msg||messages[n.err];return n.result}function inflateRaw$1(t,e){return(e=e||{}).raw=!0,inflate$1(t,e)}Inflate$1.prototype.push=function(t,e){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:!0===e?Z_FINISH:Z_NO_FLUSH,n.input="[object ArrayBuffer]"===toString$2.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&r&&(s=inflate_1$2.inflateSetDictionary(n,r),s===Z_OK?s=inflate_1$2.inflate(n,a):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&0!==t[n.next_in];)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,a);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(0===n.avail_out||s===Z_STREAM_END))if("string"===this.options.to){let t=strings.utf8border(n.output,n.next_out),e=n.next_out-t,r=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=i-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(r)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(s!==Z_OK||0!==o){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},Inflate$1.prototype.onData=function(t){this.chunks.push(t)},Inflate$1.prototype.onEnd=function(t){t===Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Inflate_1$1=Inflate$1,inflate_2=inflate$1,inflateRaw_1$1=inflateRaw$1,ungzip$1=inflate$1,constants=constants$2,inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1,{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate,deflate_1=deflate,deflateRaw_1=deflateRaw,gzip_1=gzip,Inflate_1=Inflate,inflate_1=inflate,inflateRaw_1=inflateRaw,ungzip_1=ungzip,constants_1=constants$2,pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};async function request(t,e={}){const{method:n="GET",data:i,headers:r={}}=e,s={method:n,headers:_extends({"Content-Type":"application/json"},r)};if("GET"===n&&i){const e=new URLSearchParams(i).toString();t+=`${t.includes("?")?"&":"?"}${e}`}"GET"!==n&&i&&(s.body=JSON.stringify(i));try{const e=await fetch(t,s);if(!e.ok)throw{status:e.status,statusText:e.statusText,message:`HTTP error! status: ${e.status}`};return e}catch(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}}function XMLRequest(t){return new Promise((e,n)=>{var i;const r=new XMLHttpRequest;r.open("GET",t.url),r.responseType="arraybuffer",r.timeout=null!=(i=t.timeout)?i:6e4,r.onload=function(){4===r.readyState&&200===r.status?e([!1,r.response]):n([!0,`HTTP ${r.status} ${r.statusText}`])},r.onerror=function(){n([!0,"network error"])},r.ontimeout=function(){n([!0,`timeout after ${r.timeout}ms`])},r.onabort=function(){n([!0,"aborted"])},r.onprogress=e=>{if(e.lengthComputable){const n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},r.send()})}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t){var e={exports:{}};return t(e,e.exports),e.exports}var md5=createCommonjsModule(function(t){!function(e){function n(t,e){var n=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(n>>16)<<16|65535&n}function i(t,e,i,r,s,a){return n((o=n(n(e,t),n(r,a)))<<(l=s)|o>>>32-l,i);var o,l}function r(t,e,n,r,s,a,o){return i(e&n|~e&r,t,e,s,a,o)}function s(t,e,n,r,s,a,o){return i(e&r|n&~r,t,e,s,a,o)}function a(t,e,n,r,s,a,o){return i(e^n^r,t,e,s,a,o)}function o(t,e,n,r,s,a,o){return i(n^(e|~r),t,e,s,a,o)}function l(t,e){var i,l,h,d,c;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,f=-271733879,p=-1732584194,_=271733878;for(i=0;i<t.length;i+=16)l=u,h=f,d=p,c=_,u=r(u,f,p,_,t[i],7,-680876936),_=r(_,u,f,p,t[i+1],12,-389564586),p=r(p,_,u,f,t[i+2],17,606105819),f=r(f,p,_,u,t[i+3],22,-1044525330),u=r(u,f,p,_,t[i+4],7,-176418897),_=r(_,u,f,p,t[i+5],12,1200080426),p=r(p,_,u,f,t[i+6],17,-1473231341),f=r(f,p,_,u,t[i+7],22,-45705983),u=r(u,f,p,_,t[i+8],7,1770035416),_=r(_,u,f,p,t[i+9],12,-1958414417),p=r(p,_,u,f,t[i+10],17,-42063),f=r(f,p,_,u,t[i+11],22,-1990404162),u=r(u,f,p,_,t[i+12],7,1804603682),_=r(_,u,f,p,t[i+13],12,-40341101),p=r(p,_,u,f,t[i+14],17,-1502002290),u=s(u,f=r(f,p,_,u,t[i+15],22,1236535329),p,_,t[i+1],5,-165796510),_=s(_,u,f,p,t[i+6],9,-1069501632),p=s(p,_,u,f,t[i+11],14,643717713),f=s(f,p,_,u,t[i],20,-373897302),u=s(u,f,p,_,t[i+5],5,-701558691),_=s(_,u,f,p,t[i+10],9,38016083),p=s(p,_,u,f,t[i+15],14,-660478335),f=s(f,p,_,u,t[i+4],20,-405537848),u=s(u,f,p,_,t[i+9],5,568446438),_=s(_,u,f,p,t[i+14],9,-1019803690),p=s(p,_,u,f,t[i+3],14,-187363961),f=s(f,p,_,u,t[i+8],20,1163531501),u=s(u,f,p,_,t[i+13],5,-1444681467),_=s(_,u,f,p,t[i+2],9,-51403784),p=s(p,_,u,f,t[i+7],14,1735328473),u=a(u,f=s(f,p,_,u,t[i+12],20,-1926607734),p,_,t[i+5],4,-378558),_=a(_,u,f,p,t[i+8],11,-2022574463),p=a(p,_,u,f,t[i+11],16,1839030562),f=a(f,p,_,u,t[i+14],23,-35309556),u=a(u,f,p,_,t[i+1],4,-1530992060),_=a(_,u,f,p,t[i+4],11,1272893353),p=a(p,_,u,f,t[i+7],16,-155497632),f=a(f,p,_,u,t[i+10],23,-1094730640),u=a(u,f,p,_,t[i+13],4,681279174),_=a(_,u,f,p,t[i],11,-358537222),p=a(p,_,u,f,t[i+3],16,-722521979),f=a(f,p,_,u,t[i+6],23,76029189),u=a(u,f,p,_,t[i+9],4,-640364487),_=a(_,u,f,p,t[i+12],11,-421815835),p=a(p,_,u,f,t[i+15],16,530742520),u=o(u,f=a(f,p,_,u,t[i+2],23,-995338651),p,_,t[i],6,-198630844),_=o(_,u,f,p,t[i+7],10,1126891415),p=o(p,_,u,f,t[i+14],15,-1416354905),f=o(f,p,_,u,t[i+5],21,-57434055),u=o(u,f,p,_,t[i+12],6,1700485571),_=o(_,u,f,p,t[i+3],10,-1894986606),p=o(p,_,u,f,t[i+10],15,-1051523),f=o(f,p,_,u,t[i+1],21,-2054922799),u=o(u,f,p,_,t[i+8],6,1873313359),_=o(_,u,f,p,t[i+15],10,-30611744),p=o(p,_,u,f,t[i+6],15,-1560198380),f=o(f,p,_,u,t[i+13],21,1309151649),u=o(u,f,p,_,t[i+4],6,-145523070),_=o(_,u,f,p,t[i+11],10,-1120210379),p=o(p,_,u,f,t[i+2],15,718787259),f=o(f,p,_,u,t[i+9],21,-343485551),u=n(u,l),f=n(f,h),p=n(p,d),_=n(_,c);return[u,f,p,_]}function h(t){var e,n="",i=32*t.length;for(e=0;e<i;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function d(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var i=8*t.length;for(e=0;e<i;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function c(t){var e,n,i="0123456789abcdef",r="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),r+=i.charAt(e>>>4&15)+i.charAt(15&e);return r}function u(t){return unescape(encodeURIComponent(t))}function f(t){return function(t){return h(l(d(t),8*t.length))}(u(t))}function p(t,e){return function(t,e){var n,i,r=d(t),s=[],a=[];for(s[15]=a[15]=void 0,r.length>16&&(r=l(r,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^r[n],a[n]=1549556828^r[n];return i=l(s.concat(d(e)),512+8*e.length),h(l(a.concat(i),640))}(u(t),u(e))}function _(t,e,n){return e?n?p(e,t):c(p(e,t)):n?f(t):c(f(t))}t.exports?t.exports=_:e.md5=_}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function compareUnicodeCodePoints(t,e){const n=Array.from(t,t=>t.codePointAt(0)),i=Array.from(e,t=>t.codePointAt(0)),r=Math.min(n.length,i.length);for(let t=0;t<r;t+=1)if(n[t]!==i[t])return n[t]-i[t];return n.length-i.length}function parseUrlWithoutBase(t){try{const e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){let n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,i,r){const s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(i).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(e=>t(e));if("object"!=typeof e)return e;const n=Object.keys(e).sort(compareUnicodeCodePoints),i={};for(const r of n)i[r]=t(e[r]);return i}(r),h=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),d=encodeWithMd5(`${o.toLowerCase()}${n.toLowerCase()}${h}${e}${a}`);return s["X-APP-ID"]=t,s["X-TOKEN"]=d,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}class CacheManager{constructor(t){this.cacheServer=t}getVideo(t){return`${this.cacheServer}/get_video?url=${encodeURIComponent(t)}`}}class ResourceManager{constructor(t){this.TAG="[ResourceManager]",this.offlineIdle=[],this.offlineCache=new Map,this.networkInfos=[],this.bg=null,this.destroyed=!1,this.progress=0,this.videoCache=new Map,this.maxCacheSize=10485760,this.maxCacheEntries=20,this.cacheCleanupInterval=null,this.isProcessingVideo=!1,this.startSessionTimer=null,this.audioOnlyMode=!1,this.downloadingVideos=new Map,this.first_load=!0,this.options=t,this.audioOnlyMode=t.audioOnlyMode||!1,this.sdk=t.sdkInstance,this.mouthShapeLib={char_info:null},this.config=t.config||{},this.resource_pack={enable_robot_expression:!1,body_data_dir:"",face_ani_char_data:"",face_ani_preload_data:"",interpolate_joints:[[4,3]]},t.cacheServer&&(this.cacheServer=new CacheManager(t.cacheServer)),this.startCacheCleanup()}getAppInfo(){return{appId:this.options.appId}}getBackgroundImage(){return new Promise((t,e)=>{try{var n,i;const e=new Image;if(e.crossOrigin="anonymous",e.src=(null==(n=this.config)?void 0:n.background_img)||"",null==(i=this.config)||!i.background_img)return;e.onload=()=>{this.bg=e,t()},e.onerror=n=>{this.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:e}}),this.bg=null,t()}}catch(t){}})}getIsEnableRobotExpression(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression}getBackgroundImageElement(){return this.bg}getConfig(){return this.config}async load(t){var e;this.destroyed=!1,null==t||t(this.progress),this.startSessionTimer&&(clearInterval(this.startSessionTimer),this.startSessionTimer=null),this.startSessionTimer=setInterval(()=>{if(this.destroyed||this.progress>=14)return clearInterval(this.startSessionTimer),void(this.startSessionTimer=null);this.progress+=1,null==t||t(this.progress)},100);const n=await this.startSession(),i=n;return null!=i&&i.session_id&&(this.session_id=i.session_id),this.destroyed?(window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after startSession"),await this.stopSession("destroy_during_init"),null):n?(clearInterval(this.startSessionTimer),this.startSessionTimer=null,this.progress=15,null==t||t(this.progress),this.resource_pack=i.resource_pack,this.config=i.config,this.offlineIdle=(null==(e=i.resource_pack)?void 0:e.offline_idle)||[],!this.resource_pack||(this.audioOnlyMode||await this.loadMouthShapeLib(t),this.getBackgroundImage(),null!=(r=this.mouthShapeLib)&&r.char_info||null==i||null==(s=i.resource_pack)||!s.face_ani_char_data||this.audioOnlyMode)?i:null):(clearInterval(this.startSessionTimer),this.startSessionTimer=null,null);var r,s}async startSession(){try{const n=await this._startSession();var t,e;return null!=n&&n.verify_res&&(null==(t=(e=this.options).onStartSessionWarning)||t.call(e,n.verify_res)),n}catch(t){return null}}_startSession(){var t;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;const e=`${this.options.gatewayServer}`,n=_extends({tag:this.options.tag,gateway_type:this.options.gateway_type},void 0!==this.options.asr_id?{asr_id:this.options.asr_id}:{},void 0!==this.options.llm_id?{llm_id:this.options.llm_id}:{},void 0!==this.options.session_speak_req_id?{session_speak_req_id:this.options.session_speak_req_id}:{},null!=(t=this.options.sessionRequestData)?t:{},{config:_extends({},this.config,{framedata_proto_version:2,walk_version:3})}),{headers:i,data:r}=headersNeedSign(this.options.appId,this.options.appSecret,"POST",e,n);return request(e,{method:"POST",data:r,headers:_extends({},i,this.options.headers)}).then(t=>t.json()).then(t=>{var e;return null!=t&&null!=(e=t.data)&&e.resource_pack?null==t?void 0:t.data:(this.sdk.onMessage({code:null==t?void 0:t.error_code,message:`Error: ${null==t?void 0:t.error_code}, ${null==t?void 0:t.error_reason}`}),null)}).catch(t=>(this.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null))}async stopSession(t){try{const e=`${this.options.gatewayServer}`;if(!this.session_id)return;const n={session_id:this.session_id,stop_reason:t},{headers:i,data:r}=headersNeedSign(this.options.appId,this.options.appSecret,"DELETE",e,n),s=await request(e,{method:"DELETE",data:r,headers:_extends({},i,this.options.headers)});return await s.json()}catch(t){this.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}}async loadMouthShapeLib(t){try{var e,n;if(!this.resource_pack.face_ani_char_data)return this.progress+=60,void(null==t||t(this.progress));let s=null,a=null,o="",l=0,h=0,d=0,c=0;const u=()=>(e,n)=>{var i,r;if(!n)return;const s=performance.now(),a=s-d,o=n.loaded-c;null==(i=(r=this.options).onNetworkInfo)||i.call(r,{rtt:a,downlink:a>0&&o>0?8*o/(a/1e3)/1e6:0,networkStatus:navigator.onLine}),c=n.loaded,d=s,null==t||t(this.progress+.65*e)};try{const t=`${this.resource_pack.face_ani_char_data}.gz`;o=t,h=performance.now(),d=h,c=0;const[,e]=await XMLRequest({url:t,onProgress:u()}),n=pako.ungzip(new Uint8Array(e)),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n),s=i}catch(t){a=t,s=null}if(!s)try{const t=this.resource_pack.face_ani_char_data;o=t,h=performance.now(),d=h,c=0;const[,e]=await XMLRequest({url:t,onProgress:u()});s=e}catch(t){var i,r;return this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),void(null==(i=(r=this.sdk).onMessage)||i.call(r,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:a,binError:t}}))}const f=performance.now()-h;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:f,downlink:l>0&&f>0?8*l/(f/1e3)/1e6:0,networkStatus:navigator.onLine}),this.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(s,{blendshapeMap:this.resource_pack.blendshape_map||[]})},this.progress+=65,null==t||t(this.progress)}catch(t){var s,a;this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),null==(s=(a=this.sdk).onMessage)||s.call(a,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}}getMouthShapeLib(){return this.mouthShapeLib}getVideoUrl(t){if(!this.resource_pack.body_data_dir)return"";if(!t)return this.first_load&&(this.first_load=!1,this.stopSession("no_video_name_error")),this.sdk.onMessage({code:EErrorCode.INVALID_BODY_NAME,message:"Error: 视频地址获取失败",e:t}),"";const e=`${this.resource_pack.body_data_dir}${t}.mp4`;var n;return this.cacheServer?null==(n=this.cacheServer)?void 0:n.getVideo(e):e}async preloadVideo(t){if(!this.videoCache.has(t))return this.loadVideo(t)}async loadVideo(t){const e=this.videoCache.get(t)||this.offlineCache.get(t);if(e){if(e.data)return this.updateCacheAccess(t),e.data;window.avatarSDKLogger.warn(this.TAG,`发现无效缓存条目: ${t},正在删除`),this.videoCache.delete(t)}if(this.downloadingVideos.has(t))try{return await this.downloadingVideos.get(t)}catch(e){throw this.downloadingVideos.delete(t),window.avatarSDKLogger.warn(this.TAG,`${t} 视频下载失败,从下载列表移除`),e}this.isProcessingVideo=!0;const n=this.downloadVideo(t);this.downloadingVideos.set(t,n);try{return await n}finally{this.downloadingVideos.delete(t),this.isProcessingVideo=!1}}async downloadVideo(t){const e=this.getVideoUrl(t);if(e)try{const{response:n,arrayBuffer:i}=await this._fetchVideo(e);return n.ok?(this.addToCache(t,i),i):(this.first_load&&(this.first_load=!1,this.stopSession("load_video_error")),void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,res:n}}))}catch(n){return void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,error:n}})}}async _fetchVideo(t){if(this.networkInfos.length>=4){var e,n;const t=this.networkInfos.reduce((t,e)=>t+e.rtt,0)/this.networkInfos.length,i=this.networkInfos.reduce((t,e)=>t+e.downlink,0)/this.networkInfos.length;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:t,downlink:i,networkStatus:navigator.onLine}),this.networkInfos.length=0}const i=performance.now(),r=await fetch(t),s=parseFloat(r.headers.get("Content-Length")||"0"),a=performance.now(),o=await r.arrayBuffer(),l=a-i,h={rtt:l,downlink:8*s/(l/1e3*1e6),networkStatus:navigator.onLine};return this.networkInfos.push(h),{response:r,arrayBuffer:o}}addToCache(t,e){const n=Date.now();let i=0;for(const t of this.videoCache.values())i+=t.data.byteLength;if(i+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),i=0;for(const t of this.videoCache.values())i+=t.data.byteLength;if(i+e.byteLength>this.maxCacheSize&&e.byteLength>.5*this.maxCacheSize)return void window.avatarSDKLogger.warn(this.TAG,`视频文件过大(${(e.byteLength/1024/1024).toFixed(2)}MB),跳过缓存: ${t}`);if(i+e.byteLength>this.maxCacheSize){const t=.5*this.maxCacheSize,e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);for(const[n,r]of e){if(i<=t)break;this.videoCache.delete(n),i-=r.data.byteLength}}}this.videoCache.set(t,{data:e,lastAccessTime:n,accessCount:1})}startCacheCleanup(){this.cacheCleanupInterval=setInterval(()=>{this.cleanupCache()},3e5)}cleanupCache(){if(this.isProcessingVideo)return;const t=Date.now(),e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);let n=0;const i=[];for(const[t,e]of this.videoCache.entries())n+=e.data.byteLength;for(const[r,s]of e)t-s.lastAccessTime>6e5&&(i.push(r),n-=s.data.byteLength);if(n>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(const[t,r]of e)if(!i.includes(t)&&(i.push(t),n-=r.data.byteLength,this.videoCache.size-i.length<=2||n<=.8*this.maxCacheSize&&this.videoCache.size-i.length<=.8*this.maxCacheEntries))break;for(const t of i)this.videoCache.delete(t)}updateCacheAccess(t){const e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)}clearAllCache(){this.videoCache.clear()}_getOfflineIdle(){return this.offlineIdle}_getSessionId(){return this.session_id||""}async _reload(){var t;const e=await this.startSession();if(!e)return null;const n=e;return this.session_id=null==n?void 0:n.session_id,this.destroyed?(await this.stopSession("destroy_during_reload"),null):(this.resource_pack=n.resource_pack,this.config=n.config,this.offlineIdle=(null==(t=n.resource_pack)?void 0:t.offline_idle)||[],this.resource_pack&&this.getBackgroundImage(),n)}async _setOfflineCache(){if(!this.offlineIdle||0===this.offlineIdle.length)return;this.offlineCache.clear();const t=this.offlineIdle.map(t=>t.n);for(const e of t)try{await this._runOfflineCache(e)}catch(t){}}async _runOfflineCache(t){const e=this.getVideoUrl(t);if(e)return this._fetchVideo(e).then(({arrayBuffer:e})=>{this.offlineCache.set(t,{data:e})})}destroy(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0}}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){n.r(e),n.d(e,"encode",function(){return B}),n.d(e,"decode",function(){return G}),n.d(e,"decodeAsync",function(){return Y}),n.d(e,"decodeArrayStream",function(){return X}),n.d(e,"decodeStream",function(){return Z}),n.d(e,"Decoder",function(){return N}),n.d(e,"Encoder",function(){return A}),n.d(e,"ExtensionCodec",function(){return w}),n.d(e,"ExtData",function(){return f}),n.d(e,"EXT_TIMESTAMP",function(){return m}),n.d(e,"encodeDateToTimeSpec",function(){return y}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return b}),n.d(e,"encodeTimestampExtension",function(){return v}),n.d(e,"decodeTimestampExtension",function(){return S});var i=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,r,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return a},r=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(i(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,i=0;i<e;){var r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){var s=t.charCodeAt(i);56320==(64512&s)&&(++i,r=((1023&r)<<10)+(1023&s)+65536)}n+=4294901760&r?4:3}else n+=2;else n++}return n}var o=s?new TextEncoder:void 0,l="undefined"!=typeof process?200:0,h=(null==o?void 0:o.encodeInto)?function(t,e,n){o.encodeInto(t,e.subarray(n))}:function(t,e,n){e.set(o.encode(t),n)};function d(t,e,n){for(var i=e,s=i+n,a=[],o="";i<s;){var l=t[i++];if(128&l)if(192==(224&l)){var h=63&t[i++];a.push((31&l)<<6|h)}else if(224==(240&l)){h=63&t[i++];var d=63&t[i++];a.push((31&l)<<12|h<<6|d)}else if(240==(248&l)){var c=(7&l)<<18|(h=63&t[i++])<<12|(d=63&t[i++])<<6|63&t[i++];c>65535&&(a.push((c-=65536)>>>10&1023|55296),c=56320|1023&c),a.push(c)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,r(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,r(a))),o}var c=s?new TextDecoder:null,u="undefined"!=typeof process?200:0,f=function(t,e){this.type=t,this.data=e};function p(t,e,n){var i=Math.floor(n/4294967296),r=n;t.setUint32(e,i),t.setUint32(e+4,r)}function _(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var m=-1;function g(t){var e,n=t.sec,i=t.nsec;if(n>=0&&i>=0&&n<=17179869183){if(0===i&&n<=4294967295){var r=new Uint8Array(4);return(e=new DataView(r.buffer)).setUint32(0,n),r}var s=n/4294967296,a=4294967295&n;return r=new Uint8Array(8),(e=new DataView(r.buffer)).setUint32(0,i<<2|3&s),e.setUint32(4,a),r}return r=new Uint8Array(12),(e=new DataView(r.buffer)).setUint32(0,i),p(e,4,n),r}function y(t){var e=t.getTime(),n=Math.floor(e/1e3),i=1e6*(e-1e3*n),r=Math.floor(i/1e9);return{sec:n+r,nsec:i-1e9*r}}function v(t){return t instanceof Date?g(y(t)):null}function b(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:var n=e.getUint32(0);return{sec:4294967296*(3&n)+e.getUint32(4),nsec:n>>>2};case 12:return{sec:_(e,4),nsec:e.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+t.length)}}function S(t){var e=b(t);return new Date(1e3*e.sec+e.nsec/1e6)}var E={type:m,encode:v,decode:S},w=function(){function t(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(E)}return t.prototype.register=function(t){var e=t.type,n=t.encode,i=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{var r=1+e;this.builtInEncoders[r]=n,this.builtInDecoders[r]=i}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(i=this.builtInEncoders[n])&&null!=(r=i(t,e)))return new f(-1-n,r);for(n=0;n<this.encoders.length;n++){var i,r;if(null!=(i=this.encoders[n])&&null!=(r=i(t,e)))return new f(n,r)}return t instanceof f?t:null},t.prototype.decode=function(t,e,n){var i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,n):new f(e,t)},t.defaultCodec=new t,t}();function x(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer?new Uint8Array(t):Uint8Array.from(t)}var T=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A=function(){function t(t,e,n,i,r,s,a){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=100),void 0===i&&(i=2048),void 0===r&&(r=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=i,this.sortKeys=r,this.forceFloat32=s,this.ignoreUndefined=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return t.prototype.encode=function(t,e){if(e>this.maxDepth)throw new Error("Too deep objects in depth "+e);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.encodeObject(t,e)},t.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},t.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)},t.prototype.resizeBuffer=function(t){var e=new ArrayBuffer(t),n=new Uint8Array(e),i=new DataView(e);n.set(this.bytes),this.view=i,this.bytes=n},t.prototype.encodeNil=function(){this.writeU8(192)},t.prototype.encodeBoolean=function(t){this.writeU8(!1===t?194:195)},t.prototype.encodeNumber=function(t){Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},t.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too long string: "+t+" bytes in UTF-8");this.writeU8(219),this.writeU32(t)}},t.prototype.encodeString=function(t){if(s&&t.length>l){var e=a(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),h(t,this.bytes,this.pos),this.pos+=e}else e=a(t),this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),function(t,e,n){for(var i=t.length,r=n,s=0;s<i;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<i){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[r++]=a>>18&7|240,e[r++]=a>>12&63|128,e[r++]=a>>6&63|128):(e[r++]=a>>12&15|224,e[r++]=a>>6&63|128)}else e[r++]=a>>6&31|192;e[r++]=63&a|128}else e[r++]=a}}(t,this.bytes,this.pos),this.pos+=e},t.prototype.encodeObject=function(t,e){var n=this.extensionCodec.tryToEncode(t,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(t));this.encodeMap(t,e)}},t.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large binary: "+e);this.writeU8(198),this.writeU32(e)}var n=x(t);this.writeU8a(n)},t.prototype.encodeArray=function(t,e){var n,i,r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: "+r);this.writeU8(221),this.writeU32(r)}try{for(var s=T(t),a=s.next();!a.done;a=s.next())this.encode(a.value,e+1)}catch(t){n={error:t}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,i,r=0;try{for(var s=T(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&r++}catch(t){n={error:t}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return r},t.prototype.encodeMap=function(t,e){var n,i,r=Object.keys(t);this.sortKeys&&r.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error("Too large map object: "+s);this.writeU8(223),this.writeU32(s)}try{for(var a=T(r),o=a.next();!o.done;o=a.next()){var l=o.value,h=t[l];this.ignoreUndefined&&void 0===h||(this.encodeString(l),this.encode(h,e+1))}}catch(t){n={error:t}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}},t.prototype.encodeExtension=function(t){var e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large extension object: "+e);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)},t.prototype.writeU8=function(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++},t.prototype.writeU8a=function(t){var e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e},t.prototype.writeI8=function(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++},t.prototype.writeU16=function(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2},t.prototype.writeI16=function(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2},t.prototype.writeU32=function(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4},t.prototype.writeI32=function(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4},t.prototype.writeF32=function(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4},t.prototype.writeF64=function(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8},t.prototype.writeU64=function(t){this.ensureBufferSizeToWrite(8),function(t,e,n){var i=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,i)}(this.view,this.pos,t),this.pos+=8},t.prototype.writeI64=function(t){this.ensureBufferSizeToWrite(8),p(this.view,this.pos,t),this.pos+=8},t}(),R={};function B(t,e){void 0===e&&(e=R);var n=new A(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined);return n.encode(t,1),n.getUint8Array()}function C(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var k=function(){function t(t,e){void 0===t&&(t=16),void 0===e&&(e=16),this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return t.prototype.canBeCached=function(t){return t>0&&t<=this.maxKeyLength},t.prototype.get=function(t,e,n){var i=this.caches[n-1],r=i.length;t:for(var s=0;s<r;s++){for(var a=i[s],o=a.bytes,l=0;l<n;l++)if(o[l]!==t[e+l])continue t;return a.value}return null},t.prototype.store=function(t,e){var n=this.caches[t.length-1],i={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)},t.prototype.decode=function(t,e,n){var i=this.get(t,e,n);if(null!=i)return i;var r=d(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,r),r},t}(),I=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},P=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(n){e[n]=t[n]&&function(e){return new Promise(function(i,r){!function(t,e,n,i){Promise.resolve(i).then(function(e){t({value:e,done:n})},e)}(i,r,(e=t[n](e)).done,e.value)})}}},D=function(t){return this instanceof D?(this.v=t,this):new D(t)},U=new DataView(new ArrayBuffer(0)),O=new Uint8Array(U.buffer),F=function(){try{U.getInt8(0)}catch(t){return t.constructor}throw new Error("never reached")}(),L=new F("Insufficient data"),M=new k,N=function(){function t(t,e,n,i,r,s,a,o){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=4294967295),void 0===i&&(i=4294967295),void 0===r&&(r=4294967295),void 0===s&&(s=4294967295),void 0===a&&(a=4294967295),void 0===o&&(o=M),this.extensionCodec=t,this.context=e,this.maxStrLength=n,this.maxBinLength=i,this.maxArrayLength=r,this.maxMapLength=s,this.maxExtLength=a,this.cachedKeyDecoder=o,this.totalPos=0,this.pos=0,this.view=U,this.bytes=O,this.headByte=-1,this.stack=[]}return t.prototype.setBuffer=function(t){this.bytes=x(t),this.view=function(t){if(t instanceof ArrayBuffer)return new DataView(t);var e=x(t);return new DataView(e.buffer,e.byteOffset,e.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(t){if(-1!==this.headByte||this.hasRemaining()){var e=this.bytes.subarray(this.pos),n=x(t),i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),this.setBuffer(i)}else this.setBuffer(t)},t.prototype.hasRemaining=function(t){return void 0===t&&(t=1),this.view.byteLength-this.pos>=t},t.prototype.createNoExtraBytesError=function(t){return new RangeError("Extra "+(this.view.byteLength-this.pos)+" byte(s) found at buffer["+t+"]")},t.prototype.decodeSingleSync=function(){var t=this.decodeSync();if(this.hasRemaining())throw this.createNoExtraBytesError(this.pos);return t},t.prototype.decodeSingleAsync=function(t){var e,n,i,r;return function(t,e,n,i){return new(n||(n=Promise))(function(e,r){function s(t){try{o(i.next(t))}catch(t){r(t)}}function a(t){try{o(i.throw(t))}catch(t){r(t)}}function o(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(t){t(i)})).then(s,a)}o((i=i.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,h,d,c,u;return I(this,function(f){switch(f.label){case 0:s=!1,f.label=1;case 1:f.trys.push([1,6,7,12]),e=P(t),f.label=2;case 2:return[4,e.next()];case 3:if((n=f.sent()).done)return[3,5];if(o=n.value,s)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(o);try{a=this.decodeSync(),s=!0}catch(t){if(!(t instanceof F))throw t}this.totalPos+=this.pos,f.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=f.sent(),i={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),n&&!n.done&&(r=e.return)?[4,r.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw d=(h=this).headByte,c=h.pos,u=h.totalPos,new RangeError("Insufficient data in parcing "+C(d)+" at "+u+" ("+c+" in the current buffer)")}})})},t.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},t.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},t.prototype.decodeMultiAsync=function(t,e){return function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(t,e||[]),s=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(t){r[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||o(t,e)})})}function o(t,e){try{(n=r[t](e)).value instanceof D?Promise.resolve(n.value.v).then(l,h):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,i,r,s,a,o,l,h,d;return I(this,function(c){switch(c.label){case 0:n=e,i=-1,c.label=1;case 1:c.trys.push([1,13,14,19]),r=P(t),c.label=2;case 2:return[4,D(r.next())];case 3:if((s=c.sent()).done)return[3,12];if(a=s.value,e&&0===i)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(i=this.readArraySize(),n=!1,this.complete()),c.label=4;case 4:c.trys.push([4,9,,10]),c.label=5;case 5:return[4,D(this.decodeSync())];case 6:return[4,c.sent()];case 7:return c.sent(),0==--i?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=c.sent())instanceof F))throw o;return[3,10];case 10:this.totalPos+=this.pos,c.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=c.sent(),h={error:l},[3,19];case 14:return c.trys.push([14,,17,18]),s&&!s.done&&(d=r.return)?[4,D(d.call(r))]:[3,16];case 15:c.sent(),c.label=16;case 16:return[3,18];case 17:if(h)throw h.error;return[7];case 18:return[7];case 19:return[2]}})})},t.prototype.decodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){if(0!=(i=t-128)){this.pushMapState(i),this.complete();continue t}e={}}else if(t<160){if(0!=(i=t-144)){this.pushArrayState(i),this.complete();continue t}e=[]}else{var n=t-160;e=this.decodeUtf8String(n,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.readI64();else if(217===t)n=this.lookU8(),e=this.decodeUtf8String(n,1);else if(218===t)n=this.lookU16(),e=this.decodeUtf8String(n,2);else if(219===t)n=this.lookU32(),e=this.decodeUtf8String(n,4);else if(220===t){if(0!==(i=this.readU16())){this.pushArrayState(i),this.complete();continue t}e=[]}else if(221===t){if(0!==(i=this.readU32())){this.pushArrayState(i),this.complete();continue t}e=[]}else if(222===t){if(0!==(i=this.readU16())){this.pushMapState(i),this.complete();continue t}e={}}else if(223===t){if(0!==(i=this.readU32())){this.pushMapState(i),this.complete();continue t}e={}}else if(196===t){var i=this.lookU8();e=this.decodeBinary(i,1)}else if(197===t)i=this.lookU16(),e=this.decodeBinary(i,2);else if(198===t)i=this.lookU32(),e=this.decodeBinary(i,4);else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t)i=this.lookU8(),e=this.decodeExtension(i,1);else if(200===t)i=this.lookU16(),e=this.decodeExtension(i,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+C(t));i=this.lookU32(),e=this.decodeExtension(i,4)}this.complete();for(var r=this.stack;r.length>0;){var s=r[r.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;r.pop(),e=s.array}else{if(1===s.type){if("string"!=(a=typeof e)&&"number"!==a)throw new Error("The type of key must be string or number but "+typeof e);s.key=e,s.type=2;continue t}if(s.map[s.key]=e,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue t}r.pop(),e=s.map}}return e}var a},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new Error("Unrecognized array type byte: "+C(t))}},t.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new Error("Max length exceeded: map length ("+t+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new Error("Max length exceeded: array length ("+t+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:t,array:new Array(t),position:0})},t.prototype.decodeUtf8String=function(t,e){var n;if(t>this.maxStrLength)throw new Error("Max length exceeded: UTF-8 byte length ("+t+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+e+t)throw L;var i,r=this.pos+e;return i=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,r,t):s&&t>u?function(t,e,n){var i=t.subarray(e,e+n);return c.decode(i)}(this.bytes,r,t):d(this.bytes,r,t),this.pos+=e+t,i},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new Error("Max length exceeded: bin length ("+t+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(t+e))throw L;var n=this.pos+e,i=this.bytes.subarray(n,n+t);return this.pos+=e+t,i},t.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new Error("Max length exceeded: ext length ("+t+") > maxExtLength ("+this.maxExtLength+")");var n=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,n,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},t.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},t.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},t.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},t.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},t.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},t.prototype.readU64=function(){var t,e,n=4294967296*(t=this.view).getUint32(e=this.pos)+t.getUint32(e+4);return this.pos+=8,n},t.prototype.readI64=function(){var t=_(this.view,this.pos);return this.pos+=8,t},t.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},t.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},t}(),z={};function G(t,e){void 0===e&&(e=z);var n=new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.setBuffer(t),n.decodeSingleSync()}var $=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},W=function(t){return this instanceof W?(this.v=t,this):new W(t)},j=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(t,e||[]),s=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(t){r[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||o(t,e)})})}function o(t,e){try{(n=r[t](e)).value instanceof W?Promise.resolve(n.value.v).then(l,h):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function H(t){return null!=t[Symbol.asyncIterator]?t:function(t){return j(this,arguments,function(){var e,n,i;return $(this,function(r){switch(r.label){case 0:e=t.getReader(),r.label=1;case 1:r.trys.push([1,,9,10]),r.label=2;case 2:return[4,W(e.read())];case 3:return n=r.sent(),i=n.value,n.done?[4,W(void 0)]:[3,5];case 4:return[2,r.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(i),[4,W(i)];case 6:return[4,r.sent()];case 7:return r.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var V=function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function a(t){try{l(i.next(t))}catch(t){s(t)}}function o(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((i=i.apply(t,e||[])).next())})},K=function(t,e){var n,i,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,i=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}};function Y(t,e){return void 0===e&&(e=z),V(this,void 0,void 0,function(){var n;return K(this,function(i){return n=H(t),[2,new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeSingleAsync(n)]})})}function X(t,e){void 0===e&&(e=z);var n=H(t);return new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeArrayStream(n)}function Z(t,e){void 0===e&&(e=z);var n=H(t);return new N(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeStream(n)}}])});const PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(t=>{PACKET_TYPES_REVERSE[PACKET_TYPES[t]]=t});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),withNativeArrayBuffer$2="function"==typeof ArrayBuffer,isView$1=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,encodePacket=({type:t,data:e},n,i)=>withNativeBlob$1&&e instanceof Blob?n?i(e):encodeBlobAsBase64(e,i):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?i(e):encodeBlobAsBase64(new Blob([e]),i):i(PACKET_TYPES[t]+(e||"")),encodeBlobAsBase64=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function toArray(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(t,e){return withNativeBlob$1&&t.data instanceof Blob?t.data.arrayBuffer().then(toArray).then(e):withNativeArrayBuffer$2&&(t.data instanceof ArrayBuffer||isView$1(t.data))?e(toArray(t.data)):void encodePacket(t,!1,t=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),e(TEXT_ENCODER.encode(t))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<chars.length;t++)lookup$1[chars.charCodeAt(t)]=t;const decode$1=t=>{let e,n,i,r,s,a=.75*t.length,o=t.length,l=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],i=lookup$1[t.charCodeAt(e+1)],r=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],d[l++]=n<<2|i>>4,d[l++]=(15&i)<<4|r>>2,d[l++]=(3&r)<<6|63&s;return h},withNativeArrayBuffer$1="function"==typeof ArrayBuffer,decodePacket=(t,e)=>{if("string"!=typeof t)return{type:"message",data:mapBinary(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:decodeBase64Packet(t.substring(1),e)}:PACKET_TYPES_REVERSE[n]?t.length>1?{type:PACKET_TYPES_REVERSE[n],data:t.substring(1)}:{type:PACKET_TYPES_REVERSE[n]}:ERROR_PACKET},decodeBase64Packet=(t,e)=>{if(withNativeArrayBuffer$1){const n=decode$1(t);return mapBinary(n,e)}return{base64:!0,data:t}},mapBinary=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,SEPARATOR=String.fromCharCode(30),encodePayload=(t,e)=>{const n=t.length,i=new Array(n);let r=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{i[s]=t,++r===n&&e(i.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),i=[];for(let t=0;t<n.length;t++){const r=decodePacket(n[t],e);if(i.push(r),"error"===r.type)break}return i};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const i=n.length;let r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);const t=new DataView(r.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{r=new Uint8Array(9);const t=new DataView(r.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(n)})}})}let TEXT_DECODER;function totalLength(t){return t.reduce((t,e)=>t+e.length,0)}function concatChunks(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let r=0;r<e;r++)n[r]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let i=0,r=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===i){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(totalLength(n)<2)break;const t=concatChunks(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(totalLength(n)<8)break;const t=concatChunks(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(ERROR_PACKET);break}r=s*Math.pow(2,32)+e.getUint32(4),i=3}else{if(totalLength(n)<r)break;const t=concatChunks(n,r);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),i=0}if(0===r||r>t){o.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(t){if(t)return mixin(t)}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r=0;r<i.length;r++)if((n=i[r])===e||n.fn===e){i.splice(r,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var r=(n=n.slice(0)).length;i<r;++i)n[i].apply(this,e)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};const nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),defaultBinaryType="arraybuffer";function createCookieJar(){}function pick(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(t,e){e.useNativeTimers?(t.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),t.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(t.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),t.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(t){return"string"==typeof t?utf8Length(t):Math.ceil((t.byteLength||t.size)*BASE64_OVERHEAD)}function utf8Length(t){let e=0,n=0;for(let i=0,r=t.length;i<r;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}function randomString(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function encode(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function decode(t){let e={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class TransportError extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Transport extends Emitter{constructor(t){super(),this.writable=!1,installTimerFunctions(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new TransportError(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=decodePacket(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=encode(t);return e.length?"?"+e:""}}class Polling extends Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){decodePayload(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,encodePayload(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let value=!1;try{value="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(err){}const hasCORS=value;function empty(){}class BaseXHR extends Polling{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class Request extends Emitter{constructor(t,e,n){super(),this.createRequest=t,installTimerFunctions(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=pick(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=Request.requestsCount++,Request.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(null!=this._xhr){if(this._xhr.onreadystatechange=empty,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Request.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Request.requestsCount=0,Request.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",unloadHandler);else if("function"==typeof addEventListener){const t="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(t,unloadHandler,!1)}function unloadHandler(){for(let t in Request.requests)Request.requests.hasOwnProperty(t)&&Request.requests[t].abort()}const hasXHR2=function(){const t=newRequest({xdomain:!1});return t&&null!==t.responseType}();class XHR extends BaseXHR{constructor(t){super(t),this.supportsBinary=hasXHR2&&!(t&&t.forceBase64)}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Request(newRequest,this.uri(),t)}}function newRequest(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||hasCORS))return new XMLHttpRequest}catch(t){}if(!e)try{return new(globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class BaseWS extends Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const WebSocketCtor=globalThisShim.WebSocket||globalThisShim.MozWebSocket;class WS extends BaseWS{createSocket(t,e,n){return isReactNative?new WebSocketCtor(t,e,n):e?new WebSocketCtor(t,e):new WebSocketCtor(t)}doWrite(t,e){this.ws.send(e)}}class WT extends Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=createPacketEncoderStream();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const r=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=e===t.length-1;this._writer.write(t[e]).then(()=>{n&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}}const transports={websocket:WS,webtransport:WT,polling:XHR},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let r=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=r[a]||"";return-1!=n&&-1!=i&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=pathNames(s,s.path),s.queryKey=queryKey(s,s.query),s}function pathNames(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}function queryKey(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}const withEventListeners="function"==typeof addEventListener&&"function"==typeof removeEventListener,OFFLINE_EVENT_LISTENERS=[];withEventListeners&&addEventListener("offline",()=>{OFFLINE_EVENT_LISTENERS.forEach(t=>t())},!1);class SocketWithoutUpgrade extends Emitter{constructor(t,e){if(super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=Infinity,t&&"object"==typeof t&&(e=t,t=null),t){const n=parse(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=parse(e.host).host);installTimerFunctions(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=decode(this.opts.query)),withEventListeners&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=createCookieJar()),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=protocol$1,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&SocketWithoutUpgrade.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=byteLength(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,nextTick(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(SocketWithoutUpgrade.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),withEventListeners&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);-1!==t&&OFFLINE_EVENT_LISTENERS.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}SocketWithoutUpgrade.protocol=protocol$1;class SocketWithUpgrade extends SocketWithoutUpgrade{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;SocketWithoutUpgrade.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function r(){n||(n=!0,h(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&r()}const h=()=>{e.removeListener("open",i),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",i),e.once("error",s),e.once("close",a),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}class Socket$1 extends SocketWithUpgrade{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>transports[t]).filter(t=>!!t)),super(t,n)}}function url(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=parse(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+e,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}const withNativeArrayBuffer="function"==typeof ArrayBuffer,isView=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function isBinary(t){return withNativeArrayBuffer&&(t instanceof ArrayBuffer||isView(t))||withNativeBlob&&t instanceof Blob||withNativeFile&&t instanceof File}function hasBinary(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(hasBinary(t[e]))return!0;return!1}if(isBinary(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return hasBinary(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&hasBinary(t[e]))return!0;return!1}function deconstructPacket(t){const e=[],n=t;return n.data=_deconstructPacket(t.data,e),n.attachments=e.length,{packet:n,buffers:e}}function _deconstructPacket(t,e){if(!t)return t;if(isBinary(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=_deconstructPacket(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=_deconstructPacket(t[i],e));return n}return t}function reconstructPacket(t,e){return t.data=_reconstructPacket(t.data,e),delete t.attachments,t}function _reconstructPacket(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=_reconstructPacket(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=_reconstructPacket(t[n],e));return t}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(PacketType||(PacketType={}));class Encoder{constructor(t){this.replacer=t}encode(t){return t.type!==PacketType.EVENT&&t.type!==PacketType.ACK||!hasBinary(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==PacketType.BINARY_EVENT&&t.type!==PacketType.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=deconstructPacket(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}function isObject(t){return"[object Object]"===Object.prototype.toString.call(t)}class Decoder extends Emitter{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===PacketType.BINARY_EVENT;n||e.type===PacketType.BINARY_ACK?(e.type=n?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!isBinary(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===PacketType[n.type])throw new Error("unknown packet type "+n.type);if(n.type===PacketType.BINARY_EVENT||n.type===PacketType.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const r=t.substring(i,e);if(r!=Number(r)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(r)}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case PacketType.CONNECT:return isObject(e);case PacketType.DISCONNECT:return void 0===e;case PacketType.CONNECT_ERROR:return"string"==typeof e||isObject(e);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===RESERVED_EVENTS$1.indexOf(e[0]));case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var parser={__proto__:null,protocol,get PacketType(){return PacketType},Encoder,Decoder};function on(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[on(t,"open",this.onopen.bind(this)),on(t,"packet",this.onpacket.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,i,r;if(RESERVED_EVENTS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:PacketType.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const a=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,o=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),s=(...t)=>{this.io.clearTimeoutFn(r),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,i)=>{const r=(t,e)=>t?i(t):n(e);r.withError=!0,e.push(r),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{if(n===this._queue[0])return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(t);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(t);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...i){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function Backoff(t){this.ms=(t=t||{}).min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};class Manager extends Emitter{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,installTimerFunctions(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||Infinity),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||parser;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=on(e,"open",function(){n.onopen(),t&&t()}),r=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",r);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(i),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(on(t,"ping",this.onping.bind(this)),on(t,"data",this.ondata.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){nextTick(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Socket(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cache={};function lookup(t,e){"object"==typeof t&&(e=t,t=void 0);const n=url(t,(e=e||{}).path||"/socket.io"),i=n.source,r=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[r]&&n.path in cache[r].nsps?s=new Manager(i,e):(cache[r]||(cache[r]=new Manager(i,e)),s=cache[r]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;Object.assign(lookup,{Manager,Socket,io:lookup,connect:lookup}),function(rt){var r,e,i;r={1:[function(t,e,n){e.exports=function(t,e){for(var n=Array(arguments.length-1),i=0,r=2,s=!0;r<arguments.length;)n[i++]=arguments[r++];return new Promise(function(r,a){n[i]=function(t){if(s)if(s=!1,t)a(t);else{for(var e=Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];r.apply(null,e)}};try{t.apply(e||null,n)}catch(t){s&&(s=!1,a(t))}})}},{}],2:[function(t,e,n){n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;1<--e%4&&"="==(t[0|e]||"");)++n;return Math.ceil(3*t.length)/4-n};for(var i=Array(64),r=Array(123),s=0;s<64;)r[i[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(t,e,n){for(var r,s=null,a=[],o=0,l=0;e<n;){var h=t[e++];switch(l){case 0:a[o++]=i[h>>2],r=(3&h)<<4,l=1;break;case 1:a[o++]=i[r|h>>4],r=(15&h)<<2,l=2;break;case 2:a[o++]=i[r|h>>6],a[o++]=i[63&h],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=i[r],a[o++]=61,1===l&&(a[o++]=61)),s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))};var a="invalid encoding";n.decode=function(t,e,n){for(var i,s=n,o=0,l=0;l<t.length;){var h=t.charCodeAt(l++);if(61==h&&1<o)break;if((h=r[h])===rt)throw Error(a);switch(o){case 0:i=h,o=1;break;case 1:e[n++]=i<<2|(48&h)>>4,i=h,o=2;break;case 2:e[n++]=(15&i)<<4|(60&h)>>2,i=h,o=3;break;case 3:e[n++]=(3&i)<<6|h,o=0}}if(1===o)throw Error(a);return n-s},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,e,n){(e.exports=function t(e,n){"string"==typeof e&&(n=e,e=rt);var i=[];function r(e){if("string"!=typeof e){var n=s();if(t.verbose&&console.log("codegen: "+n),n="return "+n,e){for(var a=Object.keys(e),o=Array(a.length+1),l=Array(a.length),h=0;h<a.length;)o[h]=a[h],l[h]=e[a[h++]];return o[h]=n,Function.apply(null,o).apply(null,l)}return Function(n)()}for(var d=Array(arguments.length-1),c=0;c<d.length;)d[c]=arguments[++c];if(c=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=d[c++];switch(e){case"d":case"f":return""+ +(""+n);case"i":return""+Math.floor(n);case"j":return JSON.stringify(n);case"s":return""+n}return"%"}),c!==d.length)throw Error("parameter count mismatch");return i.push(e),r}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+i.join("\n ")+"\n}"}return r.toString=s,r}).verbose=!1},{}],4:[function(t,e,n){function i(){this.i={}}(e.exports=i).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},i.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],i=0;i<n.length;)n[i].fn===e?n.splice(i,1):++i;return this},i.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<e.length;)e[i].fn.apply(e[i++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var i=t(1),r=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&r&&r.readFile?r.readFile(t,function(i,r){return i&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):i?n(i):n(null,e.binary?r:r.toString("utf8"))}):s.xhr(t,e,n):i(s,this,t,e)}s.xhr=function(t,e,n){var i=new XMLHttpRequest;i.onreadystatechange=function(){if(4!==i.readyState)return rt;if(0!==i.status&&200!==i.status)return n(Error("status "+i.status));if(e.binary){if(!(t=i.response))for(var t=[],r=0;r<i.responseText.length;++r)t.push(255&i.responseText.charCodeAt(r));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,i.responseText)},e.binary&&("overrideMimeType"in i&&i.overrideMimeType("text/plain; charset=x-user-defined"),i.responseType="arraybuffer"),i.open("GET",t),i.send()}},{1:1,7:7}],6:[function(t,e,n){function i(t){function e(t,e,n,i){var r=e<0?1:0;t(0===(e=r?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(r<<31|2139095040)>>>0:e<11754943508222875e-54?(r<<31|Math.round(e/1401298464324817e-60))>>>0:(r<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,i)}function n(t,e,n){return e=2*((t=t(e,n))>>31)+1,n=t>>>23&255,t&=8388607,255==n?t?NaN:1/0*e:0==n?1401298464324817e-60*e*t:e*Math.pow(2,n-150)*(8388608+t)}function i(t,e,n){c[0]=t,e[n]=u[0],e[n+1]=u[1],e[n+2]=u[2],e[n+3]=u[3]}function l(t,e,n){c[0]=t,e[n]=u[3],e[n+1]=u[2],e[n+2]=u[1],e[n+3]=u[0]}function h(t,e){return u[0]=t[e],u[1]=t[e+1],u[2]=t[e+2],u[3]=t[e+3],c[0]}function d(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],c[0]}var c,u,f,p,_;function m(t,e,n,i,r,s){var a,o=i<0?1:0;0===(i=o?-i:i)?(t(0,r,s+e),t(0<1/i?0:2147483648,r,s+n)):isNaN(i)?(t(0,r,s+e),t(2146959360,r,s+n)):17976931348623157e292<i?(t(0,r,s+e),t((o<<31|2146435072)>>>0,r,s+n)):i<22250738585072014e-324?(t((a=i/5e-324)>>>0,r,s+e),t((o<<31|a/4294967296)>>>0,r,s+n)):(t(4503599627370496*(a=i*Math.pow(2,-(i=1024===(i=Math.floor(Math.log(i)/Math.LN2))?1023:i)))>>>0,r,s+e),t((o<<31|i+1023<<20|1048576*a&1048575)>>>0,r,s+n))}function g(t,e,n,i,r){return e=t(i,r+e),i=2*((t=t(i,r+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(r=t>>>20&2047)?n?NaN:1/0*i:0==r?5e-324*i*n:i*Math.pow(2,r-1075)*(n+4503599627370496)}function y(t,e,n){f[0]=t,e[n]=p[0],e[n+1]=p[1],e[n+2]=p[2],e[n+3]=p[3],e[n+4]=p[4],e[n+5]=p[5],e[n+6]=p[6],e[n+7]=p[7]}function v(t,e,n){f[0]=t,e[n]=p[7],e[n+1]=p[6],e[n+2]=p[5],e[n+3]=p[4],e[n+4]=p[3],e[n+5]=p[2],e[n+6]=p[1],e[n+7]=p[0]}function b(t,e){return p[0]=t[e],p[1]=t[e+1],p[2]=t[e+2],p[3]=t[e+3],p[4]=t[e+4],p[5]=t[e+5],p[6]=t[e+6],p[7]=t[e+7],f[0]}function S(t,e){return p[7]=t[e],p[6]=t[e+1],p[5]=t[e+2],p[4]=t[e+3],p[3]=t[e+4],p[2]=t[e+5],p[1]=t[e+6],p[0]=t[e+7],f[0]}return"undefined"!=typeof Float32Array?(c=new Float32Array([-0]),u=new Uint8Array(c.buffer),t.writeFloatLE=(_=128===u[3])?i:l,t.writeFloatBE=_?l:i,t.readFloatLE=_?h:d,t.readFloatBE=_?d:h):(t.writeFloatLE=e.bind(null,r),t.writeFloatBE=e.bind(null,s),t.readFloatLE=n.bind(null,a),t.readFloatBE=n.bind(null,o)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),p=new Uint8Array(f.buffer),t.writeDoubleLE=(_=128===p[7])?y:v,t.writeDoubleBE=_?v:y,t.readDoubleLE=_?b:S,t.readDoubleBE=_?S:b):(t.writeDoubleLE=m.bind(null,r,0,4),t.writeDoubleBE=m.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function r(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function s(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function a(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}e.exports=i(i)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,e,n){var i=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=i(t);t="",n&&(t=e.shift()+"/");for(var r=0;r<e.length;)".."===e[r]?0<r&&".."!==e[r-1]?e.splice(--r,2):n?e.splice(r,1):++r:"."===e[r]?e.splice(r,1):++r;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=r(e)),!i(e)&&(t=(t=n?t:r(t)).replace(/(?:\/|^)[^/]+$/,"")).length?r(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var i=n||8192,r=i>>>1,s=null,a=i;return function(n){return n<1||r<n?t(n):(i<a+n&&(s=t(i),a=0),n=e.call(s,a,a+=n),7&a&&(a=1+(7|a)),n)}}},{}],10:[function(t,e,n){n.length=function(t){for(var e,n=0,i=0;i<t.length;++i)(e=t.charCodeAt(i))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(i+1))?(++i,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var i,r=null,s=[],a=0;e<n;)(i=t[e++])<128?s[a++]=i:191<i&&i<224?s[a++]=(31&i)<<6|63&t[e++]:239<i&&i<365?(i=((7&i)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(i>>10),s[a++]=56320+(1023&i)):s[a++]=(15&i)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((r=r||[]).push(String.fromCharCode.apply(String,s)),a=0);return r?(a&&r.push(String.fromCharCode.apply(String,s.slice(0,a))),r.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var i,r,s=n,a=0;a<t.length;++a)(i=t.charCodeAt(a))<128?e[n++]=i:(i<2048?e[n++]=i>>6|192:(55296==(64512&i)&&56320==(64512&(r=t.charCodeAt(a+1)))?(++a,e[n++]=(i=65536+((1023&i)<<10)+(1023&r))>>18|240,e[n++]=i>>12&63|128):e[n++]=i>>12|224,e[n++]=i>>6&63|128),e[n++]=63&i|128);return n-s}},{}],11:[function(t,e,n){e.exports=r;var i=/\/|\./;function r(t,e){i.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),r[t]=e}r("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),r("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),r("timestamp",{Timestamp:e}),r("empty",{Empty:{fields:{}}}),r("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),r("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),r("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),r.get=function(t){return r[t]||null}},{}],12:[function(t,e,n){var i=t(15),r=t(37);function s(t,e,n,r){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof i){t("switch(d%s){",r);for(var a=e.resolvedType.values,o=Object.keys(a),l=0;l<o.length;++l)a[o[l]]!==e.typeDefault||s||(t("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',r,r,r),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",r,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',r)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",r,n,r);else{var h=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",r,r);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":h=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,h)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function a(t,e,n,r){if(e.resolvedType)e.resolvedType instanceof i?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,s?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=r.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!e.length)return n("return new this.ctor");n("var m=new this.ctor");for(var a=0;a<e.length;++a){var o=e[a].resolve(),l=r.safeProp(o.name);o.map?(n("if(d%s){",l)('if(typeof d%s!=="object")',l)("throw TypeError(%j)",o.fullName+": object expected")("m%s={}",l)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",l),s(n,o,a,l+"[ks[i]]")("}")("}")):o.repeated?(n("if(d%s){",l)("if(!Array.isArray(d%s))",l)("throw TypeError(%j)",o.fullName+": array expected")("m%s=[]",l)("for(var i=0;i<d%s.length;++i){",l),s(n,o,a,l+"[i]")("}")("}")):(o.resolvedType instanceof i||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof i||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(r.compareFieldsById);if(!e.length)return r.codegen()("return {}");for(var n=r.codegen(["m","o"],t.name+"$toObject")("if(!o)")("o={}")("var d={}"),s=[],o=[],l=[],h=0;h<e.length;++h)e[h].partOf||(e[h].resolve().repeated?s:e[h].map?o:l).push(e[h]);if(s.length){for(n("if(o.arrays||o.defaults){"),h=0;h<s.length;++h)n("d%s=[]",r.safeProp(s[h].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),h=0;h<o.length;++h)n("d%s={}",r.safeProp(o[h].name));n("}")}if(l.length){for(n("if(o.defaults){"),h=0;h<l.length;++h){var d,c=r.safeProp((f=l[h]).name);f.resolvedType instanceof i?n("d%s=o.enums===String?%j:%j",c,f.resolvedType.valuesById[f.typeDefault],f.typeDefault):f.long?n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",f.typeDefault.low,f.typeDefault.high,f.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",c)("}else")("d%s=o.longs===String?%j:%i",c,f.typeDefault.toString(),f.typeDefault.toNumber()):f.bytes?(d="["+Array.prototype.slice.call(f.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",c,String.fromCharCode.apply(String,f.typeDefault))("else{")("d%s=%s",c,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",c,c)("}")):n("d%s=%j",c,f.typeDefault)}n("}")}var u=!1;for(h=0;h<e.length;++h){var f,p=t.e.indexOf(f=e[h]);c=r.safeProp(f.name),f.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",c,c)("d%s={}",c)("for(var j=0;j<ks2.length;++j){"),a(n,f,p,c+"[ks2[j]]")("}")):f.repeated?(n("if(m%s&&m%s.length){",c,c)("d%s=[]",c)("for(var j=0;j<m%s.length;++j){",c),a(n,f,p,c+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",c,f.name),a(n,f,p,c),f.partOf&&n("if(o.oneofs)")("d%s=%j",r.safeProp(f.partOf.name),f.name)),n("}")}return n("return d")}},{15:15,37:37}],13:[function(t,e,n){e.exports=function(t){for(var e=s.codegen(["r","l","e"],t.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(t.fieldsArray.filter(function(t){return t.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),n=0;n<t.fieldsArray.length;++n){var a=t.e[n].resolve(),o=a.resolvedType instanceof i?"int32":a.type,l="m"+s.safeProp(a.name);e("case %i: {",a.id),a.map?(e("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),r.defaults[a.keyType]!==rt?e("k=%j",r.defaults[a.keyType]):e("k=null"),r.defaults[o]!==rt?e("value=%j",r.defaults[o]):e("value=null"),e("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),r.basic[o]===rt?e("value=types[%i].decode(r,r.uint32())",n):e("value=r.%s()",o),e("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),e(r.long[a.keyType]!==rt?'%s[typeof k==="object"?util.longToHash(k):k]=value':"%s[k]=value",l)):a.repeated?(e("if(!(%s&&%s.length))",l,l)("%s=[]",l),r.packed[o]!==rt&&e("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,o)("}else"),r.basic[o]===rt?e(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,n):e("%s.push(r.%s())",l,o)):r.basic[o]===rt?e(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,n):e("%s=r.%s()",l,o),e("break")("}")}for(e("default:")("r.skipType(t&7)")("break")("}")("}"),n=0;n<t.e.length;++n){var h=t.e[n];h.required&&e("if(!m.hasOwnProperty(%j))",h.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+h.name+"'")}return e("return m")};var i=t(15),r=t(36),s=t(37)},{15:15,36:36,37:37}],14:[function(t,e,n){e.exports=function(t){for(var e,n=s.codegen(["m","w"],t.name+"$encode")("if(!w)")("w=Writer.create()"),o=t.fieldsArray.slice().sort(s.compareFieldsById),l=0;l<o.length;++l){var h=o[l].resolve(),d=t.e.indexOf(h),c=h.resolvedType instanceof i?"int32":h.type,u=r.basic[c];e="m"+s.safeProp(h.name),h.map?(n("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",e,h.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",e)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(h.id<<3|2)>>>0,8|r.mapKey[h.keyType],h.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",d,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,c,e),n("}")("}")):h.repeated?(n("if(%s!=null&&%s.length){",e,e),h.packed&&r.packed[c]!==rt?n("w.uint32(%i).fork()",(h.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",c,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,h,d,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(h.id<<3|u)>>>0,c,e)),n("}")):(h.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,h.name),u===rt?a(n,h,d,e):n("w.uint32(%i).%s(%s)",(h.id<<3|u)>>>0,c,e))}return n("return w")};var i=t(15),r=t(36),s=t(37);function a(t,e,n,i){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,i,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,i,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var i=t(24),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,r,s,a){if(i.call(this,t,n),e&&"object"!=typeof e)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=s||{},this.valuesOptions=a,this.o={},this.reserved=rt,e)for(var o=Object.keys(e),l=0;l<o.length;++l)"number"==typeof e[o[l]]&&(this.valuesById[this.values[o[l]]=e[o[l]]]=o[l])}a.prototype.u=function(t){return i.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(t=>{var e=Object.assign({},this.h);this.o[t]=Object.assign(e,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},a.fromJSON=function(t,e){return(t=new a(t,e.values,e.options,e.comment,e.comments)).reserved=e.reserved,e.edition&&(t.f=e.edition),t.a="proto3",t},a.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,s.toObject(["edition",this.c(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"comment",t?this.comment:rt,"comments",t?this.comments:rt])},a.prototype.add=function(t,e,n,i){if(!s.isString(t))throw TypeError("name must be a string");if(!s.isInteger(e))throw TypeError("id must be an integer");if(this.values[t]!==rt)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(e))throw Error("id "+e+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[e]!==rt){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+e+" in "+this);this.values[t]=e}else this.valuesById[this.values[t]=e]=t;return i&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=i||null),this.comments[t]=n||null,this},a.prototype.remove=function(t){if(!s.isString(t))throw TypeError("name must be a string");var e=this.values[t];if(null==e)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[e],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},a.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=h;var i,r=t(24),s=(((h.prototype=Object.create(r.prototype)).constructor=h).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function h(t,e,n,i,s,h,d){if(o.isObject(i)?(d=s,h=i,i=s=rt):o.isObject(s)&&(d=h,h=s,s=rt),r.call(this,t,h),!o.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!o.isString(n))throw TypeError("type must be a string");if(i!==rt&&!l.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(s!==rt&&!o.isString(s))throw TypeError("extend must be a string");this.rule=(i="proto3_optional"===i?"optional":i)&&"optional"!==i?i:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!o.Long&&a.long[n]!==rt,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=d}h.fromJSON=function(t,e){return t=new h(t,e.id,e.type,e.rule,e.extend,e.options,e.comment),e.edition&&(t.f=e.edition),t.a="proto3",t},Object.defineProperty(h.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.h.field_presence}}),Object.defineProperty(h.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(h.prototype,"delimited",{get:function(){return this.resolvedType instanceof i&&"DELIMITED"===this.h.message_encoding}}),Object.defineProperty(h.prototype,"packed",{get:function(){return"PACKED"===this.h.repeated_field_encoding}}),Object.defineProperty(h.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.h.field_presence)}}),h.prototype.setOption=function(t,e,n){return r.prototype.setOption.call(this,t,e,n)},h.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,o.toObject(["edition",this.c(),"rule","optional"!==this.rule&&this.rule||rt,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},h.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===rt?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.typeDefault=this.resolvedType instanceof i?null:this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===rt||!this.resolvedType||this.resolvedType instanceof s||delete this.options.packed,Object.keys(this.options).length||(this.options=rt)),this.long?(this.typeDefault=o.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(o.base64.test(this.typeDefault)?o.base64.decode(this.typeDefault,t=o.newBuffer(o.base64.length(this.typeDefault)),0):o.utf8.write(this.typeDefault,t=o.newBuffer(o.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.defaultValue=this.map?o.emptyObject:this.repeated?o.emptyArray:this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),r.prototype.resolve.call(this))},h.prototype.l=function(t){var e;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&a.defaults[this.type]===rt&&(e=this.parent.get(this.type.split(".").pop()))&&e instanceof i&&e.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},h.prototype.u=function(t){return r.prototype.u.call(this,this.f||t)},h.d=function(t,e,n,i){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(r,s){o.decorateType(r.constructor).add(new h(s,t,e,n,{default:i}))}},h.p=function(t){i=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var i=e.exports=t(18);i.build="light",i.load=function(t,e,n){return(e="function"==typeof e?(n=e,new i.Root):e||new i.Root).load(t,n)},i.loadSync=function(t,e){return(e=e||new i.Root).loadSync(t)},i.encoder=t(14),i.decoder=t(13),i.verifier=t(40),i.converter=t(12),i.ReflectionObject=t(24),i.Namespace=t(23),i.Root=t(29),i.Enum=t(15),i.Type=t(35),i.Field=t(16),i.OneOf=t(25),i.MapField=t(20),i.Service=t(33),i.Method=t(22),i.Message=t(21),i.wrappers=t(41),i.types=t(36),i.util=t(37),i.ReflectionObject.p(i.Root),i.Namespace.p(i.Type,i.Service,i.Enum),i.Root.p(i.Type),i.Field.p(i.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,e,n){var i=n;function r(){i.util.p(),i.Writer.p(i.BufferWriter),i.Reader.p(i.BufferReader)}i.build="minimal",i.Writer=t(42),i.BufferWriter=t(43),i.Reader=t(27),i.BufferReader=t(28),i.util=t(39),i.rpc=t(31),i.roots=t(30),i.configure=r,r()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,e,n){(e=e.exports=t(17)).build="full",e.tokenize=t(34),e.parse=t(26),e.common=t(11),e.Root.p(e.Type,e.parse,e.common)},{11:11,17:17,26:26,34:34}],20:[function(t,e,n){e.exports=a;var i=t(16),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,r,a,o){if(i.call(this,t,e,r,rt,rt,a,o),!s.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(t,e){return new a(t,e.id,e.keyType,e.type,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.resolve=function(){if(this.resolved)return this;if(r.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return i.prototype.resolve.call(this)},a.d=function(t,e,n){return"function"==typeof n?n=s.decorateType(n).name:n&&"object"==typeof n&&(n=s.decorateEnum(n).name),function(i,r){s.decorateType(i.constructor).add(new a(r,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=r;var i=t(39);function r(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}r.create=function(t){return this.$type.create(t)},r.encode=function(t,e){return this.$type.encode(t,e)},r.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},r.decode=function(t){return this.$type.decode(t)},r.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},r.verify=function(t){return this.$type.verify(t)},r.fromObject=function(t){return this.$type.fromObject(t)},r.toObject=function(t,e){return this.$type.toObject(t,e)},r.prototype.toJSON=function(){return this.$type.toObject(this,i.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var i=t(24),r=(((s.prototype=Object.create(i.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,h,d){if(r.isObject(a)?(l=a,a=o=rt):r.isObject(o)&&(l=o,o=rt),e!==rt&&!r.isString(e))throw TypeError("type must be a string");if(!r.isString(n))throw TypeError("requestType must be a string");if(!r.isString(s))throw TypeError("responseType must be a string");i.call(this,t,l),this.type=e||"rpc",this.requestType=n,this.requestStream=!!a||rt,this.responseType=s,this.responseStream=!!o||rt,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=h,this.parsedOptions=d}s.fromJSON=function(t,e){return new s(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment,e.parsedOptions)},s.prototype.toJSON=function(t){return r.toObject(["type","rpc"!==this.type&&this.type||rt,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),i.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=c;var i,r,s,a=t(24),o=(((c.prototype=Object.create(a.prototype)).constructor=c).className="Namespace",t(16)),l=t(37),h=t(25);function d(t,e){if(!t||!t.length)return rt;for(var n={},i=0;i<t.length;++i)n[t[i].name]=t[i].toJSON(e);return n}function c(t,e){a.call(this,t,e),this.nested=rt,this.v=null,this.b={},this.w=!0,this.y=!0}function u(t){t.v=null,t.b={};for(var e=t;e=e.parent;)e.b={};return t}c.fromJSON=function(t,e){return new c(t,e.options).addJSON(e.nested)},c.arrayToJSON=d,c.isReservedId=function(t,e){if(t)for(var n=0;n<t.length;++n)if("string"!=typeof t[n]&&t[n][0]<=e&&t[n][1]>e)return!0;return!1},c.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),c.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",d(this.nestedArray,t)])},c.prototype.addJSON=function(t){if(t)for(var e,n=Object.keys(t),a=0;a<n.length;++a)this.add(((e=t[n[a]]).fields!==rt?i:e.values!==rt?s:e.methods!==rt?r:e.id!==rt?o:c).fromJSON(n[a],e));return this},c.prototype.get=function(t){return this.nested&&this.nested[t]||null},c.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},c.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof i||t instanceof h||t instanceof s||t instanceof r||t instanceof c))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof c&&t instanceof c)||e instanceof i||e instanceof r)throw Error("duplicate name '"+t.name+"' in "+this);for(var n=e.nestedArray,a=0;a<n.length;++a)t.add(n[a]);this.remove(e),this.nested||(this.nested={}),t.setOptions(e.options,!0)}}else this.nested={};this.nested[t.name]=t,this instanceof i||this instanceof r||this instanceof s||this instanceof o||t.f||(t.f=t.a),this.w=!0,this.y=!0;for(var l=this;l=l.parent;)l.w=!0,l.y=!0;return t.onAdd(this),u(this)},c.prototype.remove=function(t){if(!(t instanceof a))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=rt),t.onRemove(this),u(this)},c.prototype.define=function(t,e){if(l.isString(t))t=t.split(".");else if(!Array.isArray(t))throw TypeError("illegal path");if(t&&t.length&&""===t[0])throw Error("path must be relative");for(var n=this;0<t.length;){var i=t.shift();if(n.nested&&n.nested[i]){if(!((n=n.nested[i])instanceof c))throw Error("path conflicts with non-namespace objects")}else n.add(n=new c(i))}return e&&n.addJSON(e),n},c.prototype.resolveAll=function(){if(this.y){this.g(this.f);var t=this.nestedArray,e=0;for(this.resolve();e<t.length;)t[e]instanceof c?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},c.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(e=>{e.g(t)})),this},c.prototype.lookup=function(t,e,n){if("boolean"==typeof e?(n=e,e=rt):e&&!Array.isArray(e)&&(e=[e]),l.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var i=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var r=this.root.j&&this.root.j["."+i];if(r&&(!e||~e.indexOf(r.constructor)))return r;if((r=this.k(t,i))&&(!e||~e.indexOf(r.constructor)))return r;if(!n)for(var s=this;s.parent;){if((r=s.parent.k(t,i))&&(!e||~e.indexOf(r.constructor)))return r;s=s.parent}return null},c.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),i=null;if(n)1===t.length?i=n:n instanceof c&&(t=t.slice(1),i=n.k(t,t.join(".")));else for(var r=0;r<this.nestedArray.length;++r)this.v[r]instanceof c&&(n=this.v[r].k(t,e))&&(i=n);return this.b[e]=i},c.prototype.lookupType=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such type: "+t)},c.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},c.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[i,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},c.prototype.lookupService=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},c.p=function(t,e,n){i=t,r=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=h).className="ReflectionObject";const i=t(25);var r,s=t(37),a={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},o={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},l={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function h(t,e){if(!s.isString(t))throw TypeError("name must be a string");if(e&&!s.isObject(e))throw TypeError("options must be an object");this.options=e,this.parsedOptions=null,this.name=t,this.f=null,this.a="proto2",this.h={},this.O=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(h.prototype,{root:{get:function(){for(var t=this;null!==t.parent;)t=t.parent;return t}},fullName:{get:function(){for(var t=[this.name],e=this.parent;e;)t.unshift(e.name),e=e.parent;return t.join(".")}}}),h.prototype.toJSON=function(){throw Error()},h.prototype.onAdd=function(t){this.parent&&this.parent!==t&&this.parent.remove(this),this.parent=t,this.resolved=!1,(t=t.root)instanceof r&&t.A(this)},h.prototype.onRemove=function(t){(t=t.root)instanceof r&&t.T(this),this.parent=null,this.resolved=!1},h.prototype.resolve=function(){return this.resolved||this.root instanceof r&&(this.resolved=!0),this},h.prototype.g=function(t){return this.u(this.f||t)},h.prototype.u=function(t){if(!this.O){var e={};if(!t)throw Error("Unknown edition for "+this.fullName);var n=Object.assign(this.options?Object.assign({},this.options.features):{},this.l(t));if(this.f){if("proto2"===t)e=Object.assign({},o);else if("proto3"===t)e=Object.assign({},l);else{if("2023"!==t)throw Error("Unknown edition: "+t);e=Object.assign({},a)}this.h=Object.assign(e,n||{})}else{if(this.partOf instanceof i)t=Object.assign({},this.partOf.h),this.h=Object.assign(t,n||{});else if(!this.declaringField){if(!this.parent)throw Error("Unable to find a parent for "+this.fullName);e=Object.assign({},this.parent.h),this.h=Object.assign(e,n||{})}this.extensionField&&(this.extensionField.h=this.h)}this.O=!0}},h.prototype.l=function(){return{}},h.prototype.getOption=function(t){return this.options?this.options[t]:rt},h.prototype.setOption=function(t,e,n){return this.options||(this.options={}),/^features\./.test(t)?s.setProperty(this.options,t,e,n):n&&this.options[t]!==rt||(this.getOption(t)!==e&&(this.resolved=!1),this.options[t]=e),this},h.prototype.setParsedOption=function(t,e,n){this.parsedOptions||(this.parsedOptions=[]);var i,r,a=this.parsedOptions;return n?(i=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(r=i[t],n,e):((i={})[t]=s.setProperty({},n,e),a.push(i)):((r={})[t]=e,a.push(r)),this},h.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),i=0;i<n.length;++i)this.setOption(n[i],t[n[i]],e);return this},h.prototype.toString=function(){var t=this.constructor.className,e=this.fullName;return e.length?t+" "+e:t},h.prototype.c=function(){return this.f&&"proto3"!==this.f?this.f:rt},h.p=function(t){r=t}},{25:25,37:37}],25:[function(t,e,n){e.exports=a;var i=t(24),r=(((a.prototype=Object.create(i.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,r){if(Array.isArray(e)||(n=e,e=rt),i.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=r}function o(t){if(t.parent)for(var e=0;e<t.fieldsArray.length;++e)t.fieldsArray[e].parent||t.parent.add(t.fieldsArray[e])}a.fromJSON=function(t,e){return new a(t,e.oneof,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["options",this.options,"oneof",this.oneof,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.add=function(t){if(t instanceof r)return t.parent&&t.parent!==this.parent&&t.parent.remove(t),this.oneof.push(t.name),this.fieldsArray.push(t),o(t.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(t){if(!(t instanceof r))throw TypeError("field must be a Field");var e=this.fieldsArray.indexOf(t);if(e<0)throw Error(t+" is not a member of "+this);return this.fieldsArray.splice(e,1),-1<(e=this.oneof.indexOf(t.name))&&this.oneof.splice(e,1),t.partOf=null,this},a.prototype.onAdd=function(t){i.prototype.onAdd.call(this,t);for(var e=0;e<this.oneof.length;++e){var n=t.get(this.oneof[e]);n&&!n.partOf&&(n.partOf=this).fieldsArray.push(n)}o(this)},a.prototype.onRemove=function(t){for(var e,n=0;n<this.fieldsArray.length;++n)(e=this.fieldsArray[n]).parent&&e.parent.remove(e);i.prototype.onRemove.call(this,t)},Object.defineProperty(a.prototype,"isProto3Optional",{get:function(){var t;return null!=this.fieldsArray&&1===this.fieldsArray.length&&null!=(t=this.fieldsArray[0]).options&&!0===t.options.proto3_optional}}),a.d=function(){for(var t=Array(arguments.length),e=0;e<arguments.length;)t[e]=arguments[e++];return function(e,n){s.decorateType(e.constructor).add(new a(n,t)),Object.defineProperty(e,n,{get:s.oneOfGetter(t),set:s.oneOfSetter(t)})}}},{16:16,24:24,37:37}],26:[function(t,e,n){(e.exports=x).filename=null,x.defaults={keepCase:!1};var i=t(34),r=t(29),s=t(35),a=t(16),o=t(20),l=t(25),h=t(15),d=t(33),c=t(22),u=t(24),f=t(36),p=t(37),_=/^[1-9][0-9]*$/,m=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,b=/^-?0[0-7]+$/,S=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,w=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function x(t,e,n){e instanceof r||(n=e,e=new r);var T,A,R,B,C,k,I=(n=n||x.defaults).preferTrailingComment||!1,P=i(t,n.alternateCommentMode||!1),D=P.next,U=P.push,O=P.peek,F=P.skip,L=P.cmnt,M=!0,N="proto2",z=e,G=[],$={},W=n.keepCase?function(t){return t}:p.camelCase;function j(t,e,n){var i=x.filename;return n||(x.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(i?i+", ":"")+"line "+P.line+")")}function H(){var t,e=[];do{if('"'!==(t=D())&&"'"!==t)throw j(t)}while(e.push(D()),F(t),'"'===(t=O())||"'"===t);return e.join("")}function V(t){var e=D();switch(e){case"'":case'"':return U(e),H();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,i=1;switch("-"==(n[0]||"")&&(i=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return i*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(_.test(n))return i*parseInt(n,10);if(g.test(n))return i*parseInt(n,16);if(v.test(n))return i*parseInt(n,8);if(S.test(n))return i*parseFloat(n);throw j(n,"number",!0)}catch(n){if(t&&w.test(e))return e;throw j(e,"value")}}function K(t,e){var n;do{if(!e||'"'!==(i=O())&&"'"!==i)try{t.push([n=Y(D()),F("to",!0)?Y(D()):n])}catch(n){if(!(e&&w.test(i)&&2023<=N))throw n;t.push(i)}else{var i=H();if(t.push(i),2023<=N)throw j(i,"id")}}while(F(",",!0));var r={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};Z(r,function(t){if("option"!==t)throw j(t);tt(r,t),F(";")},function(){nt(r)})}function Y(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(m.test(t))return parseInt(t,10);if(y.test(t))return parseInt(t,16);if(b.test(t))return parseInt(t,8)}throw j(t,"id")}function X(t,e){switch(e){case"option":return tt(t,e),F(";"),1;case"message":return q(t),1;case"enum":return J(t),1;case"service":var n,i,r=t;if(E.test(i=D()))return Z(n=new d(i),function(t){if(!X(n,t)){if("rpc"!==t)throw j(t);var e=n,i=L(),r=t;if(!E.test(t=D()))throw j(t,"name");var s,a,o,l=t;if(F("("),F("stream",!0)&&(a=!0),!w.test(t=D()))throw j(t);if(s=t,F(")"),F("returns"),F("("),F("stream",!0)&&(o=!0),!w.test(t=D()))throw j(t);F(")");var h=new c(l,r,s,t,a,o);h.comment=i,Z(h,function(t){if("option"!==t)throw j(t);tt(h,t),F(";")}),e.add(h)}}),r.add(n),r===z&&G.push(n),1;throw j(i,"service name");case"extend":var s,a=t;if(r=e,w.test(r=D()))return s=r,Z(null,function(t){switch(t){case"required":case"repeated":Q(a,t,s);break;case"optional":Q(a,"proto3"===N?"proto3_optional":"optional",s);break;default:if("proto2"===N||!w.test(t))throw j(t);U(t),Q(a,"optional",s)}}),1;throw j(r,"reference")}}function Z(t,e,n){var i,r=P.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=x.filename),F("{",!0)){for(;"}"!==(i=D());)e(i);F(";",!0)}else n&&n(),F(";"),t&&("string"!=typeof t.comment||I)&&(t.comment=L(r)||t.comment)}function q(t,e){if(!E.test(e=D()))throw j(e,"type name");var n=new s(e);Z(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,i=(F("<"),D());if(f.mapKey[i]===rt)throw j(i,"type");F(",");var r=D();if(!w.test(r))throw j(r,"type");F(">");var s=D();if(!E.test(s))throw j(s,"name");F("=");var a=new o(W(s),Y(D()),i,r);Z(a,function(t){if("option"!==t)throw j(t);tt(a,t),F(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==N)throw j(t);case"repeated":Q(n,t);break;case"optional":if("proto3"===N)Q(n,"proto3_optional");else{if("proto2"!==N)throw j(t);Q(n,"optional")}break;case"oneof":if(s=n,i=t,!E.test(i=D()))throw j(i,"name");var h=new l(W(i));Z(h,function(t){"option"===t?(tt(h,t),F(";")):(U(t),Q(h,"optional"))}),s.add(h);break;case"extensions":K(n.extensions||(n.extensions=[]));break;case"reserved":K(n.reserved||(n.reserved=[]),!0);break;default:if("proto2"===N||!w.test(t))throw j(t);U(t),Q(n,"optional")}}),t.add(n),t===z&&G.push(n)}function Q(t,e,n){var i=D();if("group"===i){var r=t,o=e;if(2023<=N)throw j("group");var h,d,c=D();if(E.test(c))return c===(d=p.lcFirst(c))&&(c=p.ucFirst(c)),F("="),u=Y(D()),(h=new s(c)).group=!0,(d=new a(d,u,c,o)).filename=x.filename,Z(h,function(t){switch(t){case"option":tt(h,t),F(";");break;case"required":case"repeated":Q(h,t);break;case"optional":Q(h,"proto3"===N?"proto3_optional":"optional");break;case"message":q(h);break;case"enum":J(h);break;case"reserved":K(h.reserved||(h.reserved=[]),!0);break;default:throw j(t)}}),void r.add(h).add(d);throw j(c,"name")}for(;i.endsWith(".")||O().startsWith(".");)i+=D();if(!w.test(i))throw j(i,"type");var u=D();if(!E.test(u))throw j(u,"name");u=W(u),F("=");var f=new a(u,Y(D()),i,e,n);Z(f,function(t){if("option"!==t)throw j(t);tt(f,t),F(";")},function(){nt(f)}),"proto3_optional"===e?(o=new l("_"+u),f.setOption("proto3_optional",!0),o.add(f),t.add(o)):t.add(f),t===z&&G.push(f)}function J(t,e){if(!E.test(e=D()))throw j(e,"name");var n=new h(e);Z(n,function(t){switch(t){case"option":tt(n,t),F(";");break;case"reserved":K(n.reserved||(n.reserved=[]),!0),n.reserved===rt&&(n.reserved=[]);break;default:var e=n,i=t;if(!E.test(i))throw j(i,"name");F("=");var r=Y(D(),!0),s={options:rt,getOption:function(t){return this.options[t]},setOption:function(t,e){u.prototype.setOption.call(s,t,e)},setParsedOption:function(){return rt}};return Z(s,function(t){if("option"!==t)throw j(t);tt(s,t),F(";")},function(){nt(s)}),void e.add(i,r,s.comment,s.parsedOptions||s.options)}}),t.add(n),t===z&&G.push(n)}function tt(t,e){var n=!0;for("option"===e&&(e=D());"="!==e;){if("("===e&&(i=D(),F(")"),e="("+i+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var i=e.split("."),r=i[0]+".";e=i[1];continue}r=e}else a=a?a+e:e;e=D()}var s=function t(e,n){if(F("{",!0)){for(var i={};!F("}",!0);){if(!E.test(B=D()))throw j(B,"name");if(null===B)throw j(B,"end of input");var r,s,a=B;if(F(":",!0),"{"===O())r=t(e,n+"."+B);else if("["===O()){if(r=[],F("[",!0)){for(;s=V(!0),r.push(s),F(",",!0););F("]"),void 0!==s&&et(e,n+"."+B,s)}}else r=V(!0),et(e,n+"."+B,r);var o=i[a];o&&(r=[].concat(o).concat(r)),i[a]=r,F(",",!0),F(";",!0)}return i}var l=V(!0);return et(e,n,l),l}(t,s=a?r.concat(a):r),a=a&&"."===a[0]?a.slice(1):a;r=r&&"."===r[r.length-1]?r.slice(0,-1):r,t.setParsedOption&&t.setParsedOption(r,s,a)}function et(t,e,n){z===t&&/^features\./.test(e)?$[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(F("[",!0)){for(;tt(t,"option"),F(",",!0););F("]")}}for(;null!==(B=D());)switch(B){case"package":if(!M)throw j(B);if(T!==rt)throw j("package");if(T=D(),!w.test(T))throw j(T,"name");z=z.define(T),F(";");break;case"import":if(!M)throw j(B);switch(k=void 0,O()){case"weak":k=R=R||[],D();break;case"public":D();default:k=A=A||[]}C=H(),F(";"),k.push(C);break;case"syntax":if(!M)throw j(B);if(F("="),(N=H())<2023)throw j(N,"syntax");F(";");break;case"edition":if(!M)throw j(B);if(F("="),N=H(),!["2023"].includes(N))throw j(N,"edition");F(";");break;case"option":tt(z,B),F(";",!0);break;default:if(X(z,B)){M=!1;continue}throw j(B)}return G.forEach(t=>{t.f=N,Object.keys($).forEach(e=>{t.getOption(e)===rt&&t.setOption(e,$[e],!0)})}),x.filename=null,{package:T,imports:A,weakImports:R,root:e}}},{15:15,16:16,20:20,22:22,24:24,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,e,n){e.exports=l;var i,r=t(39),s=r.LongBits,a=r.utf8;function o(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function l(t){this.buf=t,this.pos=0,this.len=t.length}function h(){return r.Buffer?function(t){return(l.create=function(t){return r.Buffer.isBuffer(t)?new i(t):c(t)})(t)}:c}var d,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new l(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new l(t);throw Error("illegal buffer")};function u(){var t=new s(0,0),e=0;if(!(4<this.len-this.pos)){for(;e<3;++e){if(this.pos>=this.len)throw o(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,4<this.len-this.pos){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw o(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function f(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw o(this,8);return new s(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}l.create=h(),l.prototype._=r.Array.prototype.subarray||r.Array.prototype.slice,l.prototype.uint32=(d=4294967295,function(){if(d=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(d=(d|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return d;throw this.pos=this.len,o(this,10)}),l.prototype.int32=function(){return 0|this.uint32()},l.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},l.prototype.bool=function(){return 0!==this.uint32()},l.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return f(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|f(this.buf,this.pos+=4)},l.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=r.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},l.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=r.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},l.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?(t=r.Buffer)?t.alloc(0):new this.buf.constructor(0):this._.call(this.buf,e,n)},l.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},l.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},l.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},l.p=function(t){i=t,l.create=h(),i.p();var e=r.Long?"toLong":"toNumber";r.merge(l.prototype,{int64:function(){return u.call(this)[e](!1)},uint64:function(){return u.call(this)[e](!0)},sint64:function(){return u.call(this).zzDecode()[e](!1)},fixed64:function(){return p.call(this)[e](!0)},sfixed64:function(){return p.call(this)[e](!1)}})}},{39:39}],28:[function(t,e,n){e.exports=s;var i=t(27),r=((s.prototype=Object.create(i.prototype)).constructor=s,t(39));function s(t){i.call(this,t)}s.p=function(){r.Buffer&&(s.prototype._=r.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.p()},{27:27,39:39}],29:[function(t,e,n){e.exports=c;var i,r,s,a=t(23),o=(((c.prototype=Object.create(a.prototype)).constructor=c).className="Root",t(16)),l=t(15),h=t(25),d=t(37);function c(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}c.fromJSON=function(t,e){return e=e||new c,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},c.prototype.resolvePath=d.path.resolve,c.prototype.fetch=d.fetch,c.prototype.load=function t(e,n,i){"function"==typeof n&&(i=n,n=rt);var a=this;if(!i)return d.asPromise(t,a,e,n);var o=i===u;function l(t,e){if(i){if(o)throw t;e&&e.resolveAll();var n=i;i=null,n(t,e)}}function h(t){var e=t.lastIndexOf("google/protobuf/");return-1<e&&(t=t.substring(e))in s?t:null}function c(t,e){try{if(d.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),d.isString(e)){r.filename=t;var i,s=r(e,a,n),c=0;if(s.imports)for(;c<s.imports.length;++c)(i=h(s.imports[c])||a.resolvePath(t,s.imports[c]))&&f(i);if(s.weakImports)for(c=0;c<s.weakImports.length;++c)(i=h(s.weakImports[c])||a.resolvePath(t,s.weakImports[c]))&&f(i,!0)}else a.setOptions(e.options).addJSON(e.nested)}catch(t){l(t)}o||p||l(null,a)}function f(t,e){if(t=h(t)||t,!~a.files.indexOf(t))if(a.files.push(t),t in s)o?c(t,s[t]):(++p,setTimeout(function(){--p,c(t,s[t])}));else if(o){var n;try{n=d.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}c(t,n)}else++p,a.fetch(t,function(n,r){--p,i&&(n?e?p||l(null,a):l(n):c(t,r))})}var p=0;d.isString(e)&&(e=[e]);for(var _,m=0;m<e.length;++m)(_=a.resolvePath("",e[m]))&&f(_);return o?a.resolveAll():p||l(null,a),a},c.prototype.loadSync=function(t,e){if(d.isNode)return this.load(t,e,u);throw Error("not supported")},c.prototype.resolveAll=function(){if(!this.y)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(t){return"'extend "+t.extend+"' in "+t.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var f=/^[A-Z]/;function p(t,e){var n,i=e.parent.lookup(e.extend);if(i)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),i.get(n.name)||((n.declaringField=e).extensionField=n,i.add(n)),1}c.prototype.A=function(t){if(t instanceof o)t.extend===rt||t.extensionField||p(0,t)||this.deferred.push(t);else if(t instanceof l)f.test(t.name)&&(t.parent[t.name]=t.values);else if(!(t instanceof h)){if(t instanceof i)for(var e=0;e<this.deferred.length;)p(0,this.deferred[e])?this.deferred.splice(e,1):++e;for(var n=0;n<t.nestedArray.length;++n)this.A(t.v[n]);f.test(t.name)&&(t.parent[t.name]=t)}(t instanceof i||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},c.prototype.T=function(t){var e;if(t instanceof o)t.extend!==rt&&(t.extensionField?(t.extensionField.parent.remove(t.extensionField),t.extensionField=null):-1<(e=this.deferred.indexOf(t))&&this.deferred.splice(e,1));else if(t instanceof l)f.test(t.name)&&delete t.parent[t.name];else if(t instanceof a){for(var n=0;n<t.nestedArray.length;++n)this.T(t.v[n]);f.test(t.name)&&delete t.parent[t.name]}delete this.j[t.fullName]},c.p=function(t,e,n){i=t,r=e,s=n}},{15:15,16:16,23:23,25:25,37:37}],30:[function(t,e,n){e.exports={}},{}],31:[function(t,e,n){n.Service=t(32)},{32:32}],32:[function(t,e,n){e.exports=r;var i=t(39);function r(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");i.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((r.prototype=Object.create(i.EventEmitter.prototype)).constructor=r).prototype.rpcCall=function t(e,n,r,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return i.asPromise(t,o,e,n,r,s);if(!o.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),rt;try{return o.rpcImpl(e,n[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(t,n){if(t)return o.emit("error",t,e),a(t);if(null===n)return o.end(!0),rt;if(!(n instanceof r))try{n=r[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return o.emit("error",t,e),a(t)}return o.emit("data",n,e),a(null,n)})}catch(t){return o.emit("error",t,e),setTimeout(function(){a(t)},0),rt}},r.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{39:39}],33:[function(t,e,n){e.exports=o;var i=t(23),r=(((o.prototype=Object.create(i.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){i.call(this,t,e),this.methods={},this.x=null}function l(t){return t.x=null,t}o.fromJSON=function(t,e){var n=new o(t,e.options);if(e.methods)for(var i=Object.keys(e.methods),s=0;s<i.length;++s)n.add(r.fromJSON(i[s],e.methods[i[s]]));return e.nested&&n.addJSON(e.nested),e.edition&&(n.f=e.edition),n.comment=e.comment,n.a="proto3",n},o.prototype.toJSON=function(t){var e=i.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",i.arrayToJSON(this.methodsArray,t)||{},"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},Object.defineProperty(o.prototype,"methodsArray",{get:function(){return this.x||(this.x=s.toArray(this.methods))}}),o.prototype.get=function(t){return this.methods[t]||i.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){i.prototype.resolve.call(this);for(var t=this.methodsArray,e=0;e<t.length;++e)t[e].resolve()}return this},o.prototype.g=function(t){return this.w&&(i.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(e=>{e.g(t)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof r?l((this.methods[t.name]=t).parent=this):i.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof r){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,l(this)}return i.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var i,r=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((i=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");r[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:i,q:i.resolvedRequestType.ctor,s:i.resolvedResponseType.ctor})}return r}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=f;var i=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,h=/\s/,d=/\\(.?)/g,c={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(d,function(t,e){switch(e){case"\\":case"":return e;default:return c[e]||""}})}function f(t,e){t=t.toString();var n=0,d=t.length,c=1,f=0,p={},_=[],m=null;function g(t){return Error("illegal "+t+" (line "+c+")")}function y(e){return t[0|e]||""}function v(n,i,r){var s,h={type:t[0|n++]||"",lineEmpty:!1,leading:r},d=n-(r=e?2:3);do{if(--d<0||"\n"==(s=t[0|d]||"")){h.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,i).split(l),_=0;_<u.length;++_)u[_]=u[_].replace(e?o:a,"").trim();h.text=u.join("\n").trim(),p[c]=h,f=c}function b(e){var n=S(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function S(t){for(var e=t;e<d&&"\n"!==y(e);)e++;return e}function E(){if(0<_.length)return _.shift();if(m){var a="'"===m?s:r,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,w(m),m=null,u(o[1]);throw g("string")}var l,f,p,E,x,T=0===n;do{if(n===d)return null;for(l=!1;h.test(p=y(n));)if("\n"===p&&(T=!0,++c),++n===d)return null;if("/"===y(n)){if(++n===d)throw g("comment");if("/"===y(n))if(e){if(x=!1,b((E=n)-1))for(x=!0;(n=S(n))!==d&&(n++,T&&b(n)););else n=Math.min(d,S(n)+1);x&&(v(E,n,T),T=!0),c++}else{for(x="/"===y(E=n+1);"\n"!==y(++n);)if(n===d)return null;++n,x&&(v(E,n-1,T),T=!0),++c}else{if("*"!==(p=y(n)))return"/";E=n+1,x=e||"*"===y(E);do{if("\n"===p&&++c,++n===d)throw g("comment")}while(f=p,p=y(n),"*"!==f||"/"!==p);++n,x&&(v(E,n-2,T),T=!0)}l=!0}}while(l);var A=n;if(i.lastIndex=0,!i.test(y(A++)))for(;A<d&&!i.test(y(A));)++A;return'"'!=(a=t.substring(n,n=A))&&"'"!=a||(m=a),a}function w(t){_.push(t)}function x(){if(!_.length){var t=E();if(null===t)return null;w(t)}return _[0]}return Object.defineProperty({next:E,peek:x,push:w,skip:function(t,e){var n=x();if(n===t)return E(),!0;if(e)return!1;throw g("token '"+n+"', '"+t+"' expected")},cmnt:function(t){var n,i=null;return t===rt?(n=p[c-1],delete p[c-1],n&&(e||"*"===n.type||n.lineEmpty)&&(i=n.leading?n.text:null)):(f<t&&x(),n=p[t],delete p[t],!n||n.lineEmpty||!e&&"/"!==n.type||(i=n.leading?null:n.text)),i}},"line",{get:function(){return c}})}f.unescape=u},{}],35:[function(t,e,n){e.exports=y;var i=t(23),r=(((y.prototype=Object.create(i.prototype)).constructor=y).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),h=t(21),d=t(27),c=t(42),u=t(37),f=t(14),p=t(13),_=t(40),m=t(12),g=t(41);function y(t,e){i.call(this,t,e),this.fields={},this.oneofs=rt,this.extensions=rt,this.reserved=rt,this.group=rt,this.S=null,this.e=null,this.I=null,this.N=null}function v(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(y.prototype,{fieldsById:{get:function(){if(!this.S){this.S={};for(var t=Object.keys(this.fields),e=0;e<t.length;++e){var n=this.fields[t[e]],i=n.id;if(this.S[i])throw Error("duplicate id "+i+" in "+this);this.S[i]=n}}return this.S}},fieldsArray:{get:function(){return this.e||(this.e=u.toArray(this.fields))}},oneofsArray:{get:function(){return this.I||(this.I=u.toArray(this.oneofs))}},ctor:{get:function(){return this.N||(this.ctor=y.generateConstructor(this)())},set:function(t){for(var e=t.prototype,n=(e instanceof h||((t.prototype=new h).constructor=t,u.merge(t.prototype,e)),t.$type=t.prototype.$type=this,u.merge(t,h,!0),this.N=t,0);n<this.fieldsArray.length;++n)this.e[n].resolve();var i={};for(n=0;n<this.oneofsArray.length;++n)i[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,i)}}}),y.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),i=0;i<t.fieldsArray.length;++i)(e=t.e[i]).map?n("this%s={}",u.safeProp(e.name)):e.repeated&&n("this%s=[]",u.safeProp(e.name));return n("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},y.fromJSON=function(t,e){for(var n=new y(t,e.options),h=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),d=0;d<h.length;++d)n.add((void 0!==e.fields[h[d]].keyType?o:a).fromJSON(h[d],e.fields[h[d]]));if(e.oneofs)for(h=Object.keys(e.oneofs),d=0;d<h.length;++d)n.add(s.fromJSON(h[d],e.oneofs[h[d]]));if(e.nested)for(h=Object.keys(e.nested),d=0;d<h.length;++d){var c=e.nested[h[d]];n.add((c.id!==rt?a:c.fields!==rt?y:c.values!==rt?r:c.methods!==rt?l:i).fromJSON(h[d],c))}return e.extensions&&e.extensions.length&&(n.extensions=e.extensions),e.reserved&&e.reserved.length&&(n.reserved=e.reserved),e.group&&(n.group=!0),e.comment&&(n.comment=e.comment),e.edition&&(n.f=e.edition),n.a="proto3",n},y.prototype.toJSON=function(t){var e=i.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",i.arrayToJSON(this.oneofsArray,t),"fields",i.arrayToJSON(this.fieldsArray.filter(function(t){return!t.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:rt,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"group",this.group||rt,"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},y.prototype.resolveAll=function(){if(this.y){i.prototype.resolveAll.call(this);for(var t=this.oneofsArray,e=0;e<t.length;)t[e++].resolve();var n=this.fieldsArray;for(e=0;e<n.length;)n[e++].resolve()}return this},y.prototype.g=function(t){return this.w&&(i.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(e=>{e.u(t)}),this.fieldsArray.forEach(e=>{e.u(t)})),this},y.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},y.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof a&&t.extend===rt){if((this.S||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),v(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),v(this)):i.prototype.add.call(this,t)},y.prototype.remove=function(t){if(t instanceof a&&t.extend===rt){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),v(this);throw Error(t+" is not a member of "+this)}if(t instanceof s){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),v(this);throw Error(t+" is not a member of "+this)}return i.prototype.remove.call(this,t)},y.prototype.isReservedId=function(t){return i.isReservedId(this.reserved,t)},y.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)},y.prototype.create=function(t){return new this.ctor(t)},y.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var i;return this.encode=f(this)({Writer:c,types:e,util:u}),this.decode=p(this)({Reader:d,types:e,util:u}),this.verify=_(this)({types:e,util:u}),this.fromObject=m.fromObject(this)({types:e,util:u}),this.toObject=m.toObject(this)({types:e,util:u}),(t=g[t])&&((i=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(i),i.toObject=this.toObject,this.toObject=t.toObject.bind(i)),this},y.prototype.encode=function(t,e){return this.setup().encode(t,e)},y.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},y.prototype.decode=function(t,e){return this.setup().decode(t,e)},y.prototype.decodeDelimited=function(t){return t instanceof d||(t=d.create(t)),this.decode(t,t.uint32())},y.prototype.verify=function(t){return this.setup().verify(t)},y.prototype.fromObject=function(t){return this.setup().fromObject(t)},y.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},y.d=function(t){return function(e){u.decorateType(e,t)}}},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(t,e,n){t=t(37);var i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function r(t,e){var n=0,r={};for(e|=0;n<t.length;)r[i[n+e]]=t[n++];return r}n.basic=r([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=r([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=r([0,0,0,1,1],7),n.mapKey=r([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=r([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var i,r,s=e.exports=t(39),a=t(30),o=(s.codegen=t(3),s.fetch=t(5),s.path=t(8),s.fs=s.inquire("fs"),s.toArray=function(t){if(t){for(var e=Object.keys(t),n=Array(e.length),i=0;i<e.length;)n[i]=t[e[i++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var i=t[n++],r=t[n++];r!==rt&&(e[i]=r)}return e},/\\/g),l=/"/g,h=(s.isReserved=function(t){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t)},s.safeProp=function(t){return!/^[$\w_]+$/.test(t)||s.isReserved(t)?'["'+t.replace(o,"\\\\").replace(l,'\\"')+'"]':"."+t},s.ucFirst=function(t){return(t[0]||"").toUpperCase()+t.substring(1)},/_([a-z])/g),d=(s.camelCase=function(t){return t.substring(0,1)+t.substring(1).replace(h,function(t,e){return e.toUpperCase()})},s.compareFieldsById=function(t,e){return t.id-e.id},s.decorateType=function(e,n){return e.$type?(n&&e.$type.name!==n&&(s.decorateRoot.remove(e.$type),e.$type.name=n,s.decorateRoot.add(e.$type)),e.$type):(n=new(i=i||t(35))(n||e.name),s.decorateRoot.add(n),n.ctor=e,Object.defineProperty(e,"$type",{value:n,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:n,enumerable:!1}),n)},0);s.decorateEnum=function(e){var n;return e.$type||(n=new(r=r||t(15))("Enum"+d++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,i){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,r){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,r);else{if((n=e[s])&&i)return e;n&&(r=[].concat(n).concat(r)),e[s]=r}return e}(t,e=e.split("."),n);throw TypeError("path must be specified")},Object.defineProperty(s,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(t(29)))}})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(t,e,n){e.exports=r;var i=t(39);function r(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=r.zero=new r(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},r.zeroHash="\0\0\0\0\0\0\0\0",r.fromNumber=function(t){var e,n;return 0===t?s:(n=(t=(e=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,e&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new r(n,t))},r.from=function(t){if("number"==typeof t)return r.fromNumber(t);if(i.isString(t)){if(!i.Long)return r.fromNumber(parseInt(t,10));t=i.Long.fromString(t)}return t.low||t.high?new r(t.low>>>0,t.high>>>0):s},r.prototype.toNumber=function(t){var e;return!t&&this.hi>>>31?(e=~this.hi>>>0,-((t=1+~this.lo>>>0)+4294967296*(e=t?e:e+1>>>0))):this.lo+4294967296*this.hi},r.prototype.toLong=function(t){return i.Long?new i.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);r.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new r((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},r.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},r.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,e,n){var i=n;function r(t,e,n){for(var i=Object.keys(e),r=0;r<i.length;++r)t[i[r]]!==rt&&n||(t[i[r]]=e[i[r]]);return t}function s(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack||""}),n&&r(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:rt,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}i.asPromise=t(1),i.base64=t(2),i.EventEmitter=t(4),i.float=t(6),i.inquire=t(7),i.utf8=t(10),i.pool=t(9),i.LongBits=t(38),i.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),i.global=i.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,i.emptyArray=Object.freeze?Object.freeze([]):[],i.emptyObject=Object.freeze?Object.freeze({}):{},i.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},i.isString=function(t){return"string"==typeof t||t instanceof String},i.isObject=function(t){return t&&"object"==typeof t},i.isset=i.isSet=function(t,e){var n=t[e];return null!=n&&t.hasOwnProperty(e)&&("object"!=typeof n||0<(Array.isArray(n)?n:Object.keys(n)).length)},i.Buffer=function(){try{var t=i.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),i.L=null,i.V=null,i.newBuffer=function(t){return"number"==typeof t?i.Buffer?i.V(t):new i.Array(t):i.Buffer?i.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},i.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(t){return t?i.LongBits.from(t).toHash():i.LongBits.zeroHash},i.longFromHash=function(t,e){return t=i.LongBits.fromHash(t),i.Long?i.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},i.merge=r,i.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},i.newError=s,i.ProtocolError=s("ProtocolError"),i.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;-1<n;--n)if(1===e[t[n]]&&this[t[n]]!==rt&&null!==this[t[n]])return t[n]}},i.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},i.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},i.p=function(){var t=i.Buffer;t?(i.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},i.V=t.allocUnsafe||function(e){return new t(e)}):i.L=i.V=null}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(t,e,n){e.exports=function(t){var e=r.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var i=0;i<t.fieldsArray.length;++i){var o,l=t.e[i].resolve(),h="m"+r.safeProp(l.name);l.optional&&e("if(%s!=null&&m.hasOwnProperty(%j)){",h,l.name),l.map?(e("if(!util.isObject(%s))",h)("return%j",s(l,"object"))("var k=Object.keys(%s)",h)("for(var i=0;i<k.length;++i){"),function(t,e,n){switch(e.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.key32Re.test(%s))",n)("return%j",s(e,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.key64Re.test(%s))",n)("return%j",s(e,"integer|Long key"));break;case"bool":t("if(!util.key2Re.test(%s))",n)("return%j",s(e,"boolean key"))}}(e,l,"k[i]"),a(e,l,i,h+"[k[i]]")("}")):l.repeated?(e("if(!Array.isArray(%s))",h)("return%j",s(l,"array"))("for(var i=0;i<%s.length;++i){",h),a(e,l,i,h+"[i]")("}")):(l.partOf&&(o=r.safeProp(l.partOf.name),1===n[l.partOf.name]&&e("if(p%s===1)",o)("return%j",l.partOf.name+": multiple values"),n[l.partOf.name]=1,e("p%s=1",o)),a(e,l,i,h)),l.optional&&e("}")}return e("return null")};var i=t(15),r=t(37);function s(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function a(t,e,n,r){if(e.resolvedType)if(e.resolvedType instanceof i){t("switch(%s){",r)("default:")("return%j",s(e,"enum value"));for(var a=Object.keys(e.resolvedType.values),o=0;o<a.length;++o)t("case %i:",e.resolvedType.values[a[o]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,r)("if(e)")("return%j+e",e.name+".")("}");else switch(e.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",r)("return%j",s(e,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",r,r,r,r)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',r)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',r)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",r)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',r,r,r)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var i=t(21);n[".google.protobuf.Any"]={fromObject:function(t){if(t&&t["@type"]){var e,n=t["@type"].substring(1+t["@type"].lastIndexOf("/"));if(n=this.lookup(n))return~(e="."==(t["@type"][0]||"")?t["@type"].slice(1):t["@type"]).indexOf("/")||(e="/"+e),this.create({type_url:e,value:n.encode(n.fromObject(t)).finish()})}return this.fromObject(t)},toObject:function(t,e){var n,r,s="",a="";return e&&e.json&&t.type_url&&t.value&&(a=t.type_url.substring(1+t.type_url.lastIndexOf("/")),s=t.type_url.substring(0,1+t.type_url.lastIndexOf("/")),(n=this.lookup(a))&&(t=n.decode(t.value))),!(t instanceof this.ctor)&&t instanceof i?(n=t.$type.toObject(t,e),r="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+r,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=c;var i,r=t(39),s=r.LongBits,a=r.base64,o=r.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function h(){}function d(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function c(){this.len=0,this.head=new l(h,0,0),this.tail=this.head,this.states=null}function u(){return r.Buffer?function(){return(c.create=function(){return new i})()}:function(){return new c}}function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=rt,this.val=e}function _(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127<t.lo;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function m(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}c.create=u(),c.alloc=function(t){return new r.Array(t)},r.Array!==Array&&(c.alloc=r.pool(c.alloc,r.Array.prototype.subarray)),c.prototype.M=function(t,e,n){return this.tail=this.tail.next=new l(t,e,n),this.len+=e,this},(p.prototype=Object.create(l.prototype)).fn=function(t,e,n){for(;127<t;)e[n++]=127&t|128,t>>>=7;e[n]=t},c.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},c.prototype.int32=function(t){return t<0?this.M(_,10,s.fromNumber(t)):this.uint32(t)},c.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},c.prototype.int64=c.prototype.uint64=function(t){return t=s.from(t),this.M(_,t.length(),t)},c.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(_,t.length(),t)},c.prototype.bool=function(t){return this.M(f,1,t?1:0)},c.prototype.sfixed32=c.prototype.fixed32=function(t){return this.M(m,4,t>>>0)},c.prototype.sfixed64=c.prototype.fixed64=function(t){return t=s.from(t),this.M(m,4,t.lo).M(m,4,t.hi)},c.prototype.float=function(t){return this.M(r.float.writeFloatLE,4,t)},c.prototype.double=function(t){return this.M(r.float.writeDoubleLE,8,t)};var g=r.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var i=0;i<t.length;++i)e[n+i]=t[i]};c.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(r.isString(t)&&(e=c.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(f,1,0)},c.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(f,1,0)},c.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new l(h,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(h,0,0),this.len=0),this},c.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},c.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},c.p=function(t){i=t,c.create=u(),i.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var i=t(42),r=((s.prototype=Object.create(i.prototype)).constructor=s,t(39));function s(){i.call(this)}function a(t,e,n){t.length<40?r.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=r.V,s.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&"set"===r.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var i=0;i<t.length;)e[n++]=t[i++]}},s.prototype.bytes=function(t){var e=(t=r.isString(t)?r.L(t,"base64"):t).length>>>0;return this.uint32(e),e&&this.M(s.writeBytesBuffer,e,t),this},s.prototype.string=function(t){var e=r.Buffer.byteLength(t);return this.uint32(e),e&&this.M(a,e,t),this},s.p()},{39:39,42:42}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(19),i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}(),$protobuf=protobuf,$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.default||($protobuf.roots.default={}),$root.MeshData=function(){function t(t){if(this.weights=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.index=0,t.prototype.weights=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.index&&Object.hasOwnProperty.call(t,"index")&&e.uint32(8).int32(t.index),null!=t.weights&&t.weights.length){e.uint32(18).fork();for(var n=0;n<t.weights.length;++n)e.float(t.weights[n]);e.ldelim()}return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.MeshData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:r.index=t.int32();break;case 2:if(r.weights&&r.weights.length||(r.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)r.weights.push(t.float());else r.weights.push(t.float());break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.index&&t.hasOwnProperty("index")&&!$util.isInteger(t.index))return"index: integer expected";if(null!=t.weights&&t.hasOwnProperty("weights")){if(!Array.isArray(t.weights))return"weights: array expected";for(var e=0;e<t.weights.length;++e)if("number"!=typeof t.weights[e])return"weights: number[] expected"}return null},t.fromObject=function(t){if(t instanceof $root.MeshData)return t;var e=new $root.MeshData;if(null!=t.index&&(e.index=0|t.index),t.weights){if(!Array.isArray(t.weights))throw TypeError(".MeshData.weights: array expected");e.weights=[];for(var n=0;n<t.weights.length;++n)e.weights[n]=Number(t.weights[n])}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.weights=[]),e.defaults&&(n.index=0),null!=t.index&&t.hasOwnProperty("index")&&(n.index=t.index),t.weights&&t.weights.length){n.weights=[];for(var i=0;i<t.weights.length;++i)n.weights[i]=e.json&&!isFinite(t.weights[i])?String(t.weights[i]):t.weights[i]}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/MeshData"},t}(),$root.JointData=function(){function t(t){if(this.translate=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.translate=$util.emptyArray,t.prototype.rotate=$util.newBuffer([]),t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.translate&&t.translate.length){e.uint32(10).fork();for(var n=0;n<t.translate.length;++n)e.float(t.translate[n]);e.ldelim()}return null!=t.rotate&&Object.hasOwnProperty.call(t,"rotate")&&e.uint32(18).bytes(t.rotate),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.JointData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(r.translate&&r.translate.length||(r.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)r.translate.push(t.float());else r.translate.push(t.float());break;case 2:r.rotate=t.bytes();break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.translate&&t.hasOwnProperty("translate")){if(!Array.isArray(t.translate))return"translate: array expected";for(var e=0;e<t.translate.length;++e)if("number"!=typeof t.translate[e])return"translate: number[] expected"}return null!=t.rotate&&t.hasOwnProperty("rotate")&&!(t.rotate&&"number"==typeof t.rotate.length||$util.isString(t.rotate))?"rotate: buffer expected":null},t.fromObject=function(t){if(t instanceof $root.JointData)return t;var e=new $root.JointData;if(t.translate){if(!Array.isArray(t.translate))throw TypeError(".JointData.translate: array expected");e.translate=[];for(var n=0;n<t.translate.length;++n)e.translate[n]=Number(t.translate[n])}return null!=t.rotate&&("string"==typeof t.rotate?$util.base64.decode(t.rotate,e.rotate=$util.newBuffer($util.base64.length(t.rotate)),0):t.rotate.length>=0&&(e.rotate=t.rotate)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.translate=[]),e.defaults&&(e.bytes===String?n.rotate="":(n.rotate=[],e.bytes!==Array&&(n.rotate=$util.newBuffer(n.rotate)))),t.translate&&t.translate.length){n.translate=[];for(var i=0;i<t.translate.length;++i)n.translate[i]=e.json&&!isFinite(t.translate[i])?String(t.translate[i]):t.translate[i]}return null!=t.rotate&&t.hasOwnProperty("rotate")&&(n.rotate=e.bytes===String?$util.base64.encode(t.rotate,0,t.rotate.length):e.bytes===Array?Array.prototype.slice.call(t.rotate):t.rotate),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/JointData"},t}(),$root.FaceFrameData=function(){function t(t){if(this.js=[],this.ms=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.id=0,t.prototype.s="",t.prototype.sf=0,t.prototype.ef=0,t.prototype.bsw=$util.newBuffer([]),t.prototype.cs=$util.newBuffer([]),t.prototype.js=$util.emptyArray,t.prototype.ms=$util.emptyArray,t.prototype.bodyId=0,t.prototype.faceFrameType=0,t.prototype.asf=0,t.prototype.aef=0,t.prototype.n="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.id&&Object.hasOwnProperty.call(t,"id")&&e.uint32(8).int32(t.id),null!=t.s&&Object.hasOwnProperty.call(t,"s")&&e.uint32(18).string(t.s),null!=t.sf&&Object.hasOwnProperty.call(t,"sf")&&e.uint32(24).int32(t.sf),null!=t.ef&&Object.hasOwnProperty.call(t,"ef")&&e.uint32(32).int32(t.ef),null!=t.bsw&&Object.hasOwnProperty.call(t,"bsw")&&e.uint32(42).bytes(t.bsw),null!=t.cs&&Object.hasOwnProperty.call(t,"cs")&&e.uint32(90).bytes(t.cs),null!=t.js&&t.js.length)for(var n=0;n<t.js.length;++n)$root.JointData.encode(t.js[n],e.uint32(98).fork()).ldelim();if(null!=t.ms&&t.ms.length)for(n=0;n<t.ms.length;++n)$root.MeshData.encode(t.ms[n],e.uint32(106).fork()).ldelim();return null!=t.bodyId&&Object.hasOwnProperty.call(t,"bodyId")&&e.uint32(112).int32(t.bodyId),null!=t.faceFrameType&&Object.hasOwnProperty.call(t,"faceFrameType")&&e.uint32(120).int32(t.faceFrameType),null!=t.asf&&Object.hasOwnProperty.call(t,"asf")&&e.uint32(128).int32(t.asf),null!=t.aef&&Object.hasOwnProperty.call(t,"aef")&&e.uint32(136).int32(t.aef),null!=t.n&&Object.hasOwnProperty.call(t,"n")&&e.uint32(146).string(t.n),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.FaceFrameData;t.pos<i;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:r.id=t.int32();break;case 2:r.s=t.string();break;case 3:r.sf=t.int32();break;case 4:r.ef=t.int32();break;case 5:r.bsw=t.bytes();break;case 11:r.cs=t.bytes();break;case 12:r.js&&r.js.length||(r.js=[]),r.js.push($root.JointData.decode(t,t.uint32()));break;case 13:r.ms&&r.ms.length||(r.ms=[]),r.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:r.bodyId=t.int32();break;case 15:r.faceFrameType=t.int32();break;case 16:r.asf=t.int32();break;case 17:r.aef=t.int32();break;case 18:r.n=t.string();break;default:t.skipType(7&s)}}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.id&&t.hasOwnProperty("id")&&!$util.isInteger(t.id))return"id: integer expected";if(null!=t.s&&t.hasOwnProperty("s")&&!$util.isString(t.s))return"s: string expected";if(null!=t.sf&&t.hasOwnProperty("sf")&&!$util.isInteger(t.sf))return"sf: integer expected";if(null!=t.ef&&t.hasOwnProperty("ef")&&!$util.isInteger(t.ef))return"ef: integer expected";if(null!=t.bsw&&t.hasOwnProperty("bsw")&&!(t.bsw&&"number"==typeof t.bsw.length||$util.isString(t.bsw)))return"bsw: buffer expected";if(null!=t.cs&&t.hasOwnProperty("cs")&&!(t.cs&&"number"==typeof t.cs.length||$util.isString(t.cs)))return"cs: buffer expected";if(null!=t.js&&t.hasOwnProperty("js")){if(!Array.isArray(t.js))return"js: array expected";for(var e=0;e<t.js.length;++e)if(n=$root.JointData.verify(t.js[e]))return"js."+n}if(null!=t.ms&&t.hasOwnProperty("ms")){if(!Array.isArray(t.ms))return"ms: array expected";for(e=0;e<t.ms.length;++e){var n;if(n=$root.MeshData.verify(t.ms[e]))return"ms."+n}}return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&!$util.isInteger(t.bodyId)?"bodyId: integer expected":null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&!$util.isInteger(t.faceFrameType)?"faceFrameType: integer expected":null!=t.asf&&t.hasOwnProperty("asf")&&!$util.isInteger(t.asf)?"asf: integer expected":null!=t.aef&&t.hasOwnProperty("aef")&&!$util.isInteger(t.aef)?"aef: integer expected":null!=t.n&&t.hasOwnProperty("n")&&!$util.isString(t.n)?"n: string expected":null},t.fromObject=function(t){if(t instanceof $root.FaceFrameData)return t;var e=new $root.FaceFrameData;if(null!=t.id&&(e.id=0|t.id),null!=t.s&&(e.s=String(t.s)),null!=t.sf&&(e.sf=0|t.sf),null!=t.ef&&(e.ef=0|t.ef),null!=t.bsw&&("string"==typeof t.bsw?$util.base64.decode(t.bsw,e.bsw=$util.newBuffer($util.base64.length(t.bsw)),0):t.bsw.length>=0&&(e.bsw=t.bsw)),null!=t.cs&&("string"==typeof t.cs?$util.base64.decode(t.cs,e.cs=$util.newBuffer($util.base64.length(t.cs)),0):t.cs.length>=0&&(e.cs=t.cs)),t.js){if(!Array.isArray(t.js))throw TypeError(".FaceFrameData.js: array expected");e.js=[];for(var n=0;n<t.js.length;++n){if("object"!=typeof t.js[n])throw TypeError(".FaceFrameData.js: object expected");e.js[n]=$root.JointData.fromObject(t.js[n])}}if(t.ms){if(!Array.isArray(t.ms))throw TypeError(".FaceFrameData.ms: array expected");for(e.ms=[],n=0;n<t.ms.length;++n){if("object"!=typeof t.ms[n])throw TypeError(".FaceFrameData.ms: object expected");e.ms[n]=$root.MeshData.fromObject(t.ms[n])}}return null!=t.bodyId&&(e.bodyId=0|t.bodyId),null!=t.faceFrameType&&(e.faceFrameType=0|t.faceFrameType),null!=t.asf&&(e.asf=0|t.asf),null!=t.aef&&(e.aef=0|t.aef),null!=t.n&&(e.n=String(t.n)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.js=[],n.ms=[]),e.defaults&&(n.id=0,n.s="",n.sf=0,n.ef=0,e.bytes===String?n.bsw="":(n.bsw=[],e.bytes!==Array&&(n.bsw=$util.newBuffer(n.bsw))),e.bytes===String?n.cs="":(n.cs=[],e.bytes!==Array&&(n.cs=$util.newBuffer(n.cs))),n.bodyId=0,n.faceFrameType=0,n.asf=0,n.aef=0,n.n=""),null!=t.id&&t.hasOwnProperty("id")&&(n.id=t.id),null!=t.s&&t.hasOwnProperty("s")&&(n.s=t.s),null!=t.sf&&t.hasOwnProperty("sf")&&(n.sf=t.sf),null!=t.ef&&t.hasOwnProperty("ef")&&(n.ef=t.ef),null!=t.bsw&&t.hasOwnProperty("bsw")&&(n.bsw=e.bytes===String?$util.base64.encode(t.bsw,0,t.bsw.length):e.bytes===Array?Array.prototype.slice.call(t.bsw):t.bsw),null!=t.cs&&t.hasOwnProperty("cs")&&(n.cs=e.bytes===String?$util.base64.encode(t.cs,0,t.cs.length):e.bytes===Array?Array.prototype.slice.call(t.cs):t.cs),t.js&&t.js.length){n.js=[];for(var i=0;i<t.js.length;++i)n.js[i]=$root.JointData.toObject(t.js[i],e)}if(t.ms&&t.ms.length)for(n.ms=[],i=0;i<t.ms.length;++i)n.ms[i]=$root.MeshData.toObject(t.ms[i],e);return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&(n.bodyId=t.bodyId),null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&(n.faceFrameType=t.faceFrameType),null!=t.asf&&t.hasOwnProperty("asf")&&(n.asf=t.asf),null!=t.aef&&t.hasOwnProperty("aef")&&(n.aef=t.aef),null!=t.n&&t.hasOwnProperty("n")&&(n.n=t.n),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameData"},t}(),$root.FaceFrameDataList=function(){function t(t){if(this.data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.data=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.data&&t.data.length)for(var n=0;n<t.data.length;++n)$root.FaceFrameData.encode(t.data[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var i=void 0===e?t.len:t.pos+e,r=new $root.FaceFrameDataList;t.pos<i;){var s=t.uint32();if(s===n)break;s>>>3==1?(r.data&&r.data.length||(r.data=[]),r.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return r},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.data&&t.hasOwnProperty("data")){if(!Array.isArray(t.data))return"data: array expected";for(var e=0;e<t.data.length;++e){var n=$root.FaceFrameData.verify(t.data[e]);if(n)return"data."+n}}return null},t.fromObject=function(t){if(t instanceof $root.FaceFrameDataList)return t;var e=new $root.FaceFrameDataList;if(t.data){if(!Array.isArray(t.data))throw TypeError(".FaceFrameDataList.data: array expected");e.data=[];for(var n=0;n<t.data.length;++n){if("object"!=typeof t.data[n])throw TypeError(".FaceFrameDataList.data: object expected");e.data[n]=$root.FaceFrameData.fromObject(t.data[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.data=[]),t.data&&t.data.length){n.data=[];for(var i=0;i<t.data.length;++i)n.data[i]=$root.FaceFrameData.toObject(t.data[i],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameDataList"},t}();const proxyProtobuf=protobuf.roots.default,pointNameObj={connect_sdk:"连接SDK",connect_sdk_success:"连接SDK成功",llm_text_sdk_received:"大模型输出的文本SDK前端收到",rendering_data_received:"客户端收到音频数据时间",rendering_display:"客户端播放音频数据时间",close_session:"关闭会话",audio_data_expired:"音频数据过期"};class Ttsa{clearReconnectTimer(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()}clearSocketReconnectTimer(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(()=>{this.send("client_heartbeat",{timestamp:Date.now(),frame:this.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)}constructor(t){var e=this;this.TAG="[TTSA]",this._lastSessionId="",this.reconnectTimer=-1,this.socketReconnectTimer=-1,this.wsConnectTimer=0,this.enterOfflineFlag=!1,this.syncTimestampInterval=0,this.syncTimestampNum=5e3,this.SYNC_INTERVAL=3e5,this.lastSyncTime=Date.now(),this.heartbeatTimer=-1,this.HEARTBEAT_INTERVAL=2e3,this._isResume=!1,this.clearOldWsTimeoutTimer=()=>{this.wsConnectTimer&&(clearTimeout(this.wsConnectTimer),this.wsConnectTimer=0)},this.initWsTimeoutTimer=()=>{this.clearOldWsTimeoutTimer(),this.wsConnectTimer=window.setTimeout(async function(){try{e.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"}),e.session_id&&(await e.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT"),e.ws.disconnect()),e.reStartSDK()}finally{e.clearOldWsTimeoutTimer()}},1e3*(this.reconnect_client_timeout+10))},this.appInfo=t.appInfo,this.sdk=t.sdkInstance,this.room=t.room,this.session_id=t.session_id,this.token=t.token,this.framedata_proto_version=t.framedata_proto_version,this._uniqueSpeakId=0,this.runStartFrameIndex=t.runStartFrameIndex,this.ttsaStateChangeHandle=t.ttsaStateChangeHandle,this.reloadSuccess=t.reloadSuccess,this.session_speak_req_id=0,this.enterOfflineMode=t.enterOfflineMode,this.reStartSDK=t.reStartSDK,this.reconnect_client_timeout=t.reconnect_client_timeout,this.reconnect_timeout=t.reconnect_timeout,this.sendVoiceEnd=t.sendVoiceEnd,this.getCurrentFrameIndex=t.getCurrentFrameIndex;const n=lookup(t.url,{query:{token:this.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});n.on("connect",()=>{this.clearReconnectTimer(),this.initWsTimeoutTimer(),this.startHeartbeat(),this.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);const t={room:this.room,client_type:"web",invisible_mode:this.sdk.getPendingInvisibleMode()};this.send("enter_room",t),this.sdk.getStatus()===AvatarStatus.offline&&this.sdk.getIsInitialized()&&this.reloadSuccess()}),n.on("first_start_timestamp",e=>{window.avatarSDKLogger.log(this.TAG,"first_start_timestamp",e),this.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(this.TAG,"ready"),this.reloadSuccess(),t.onReady()}),n.on("state_change",t=>{this.ttsaStateChangeHandle(t)}),n.on("tts_audio",e=>{try{const n=msgpack_min.decode(e);this.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:n[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(this.TAG,"下发音频数据tts_audio",n),t.handleMessage(EFrameDataType.AUDIO,n)}catch(t){this.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),n.on("face_data",async function(n){try{if(e.framedata_proto_version){let i=[];const r=new Uint8Array(n),s=pako.inflate(r);i=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,()=>{}).toJSON()||{data:[]}).data.map(t=>{const e=(t.js||[]).map(t=>({translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]})),n=(t.ms||[]).map(t=>({index:t.index||0,weights:t.weights||[]}));return _extends({},t,{bsw:t.bsw?scaledInt16BytesToFloat32(t.bsw):[],js:e,ms:n,body_id:t.bodyId||0,face_frame_type:t.faceFrameType||0})}),t.handleMessage(EFrameDataType.FACE,i),"speak"!==i[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",i)}else{const i=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",i),"speak"!==i[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,i)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}}),n.on("body_data",e=>{try{let n=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,n[0].s);const i=n.map(t=>_extends({},t,{x_offset:[]}));window.avatarSDKLogger.log(this.TAG,"body_data",JSON.stringify(i),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,n)}catch(t){this.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),n.on("event_data",e=>{try{const n=msgpack_min.decode(e);window.avatarSDKLogger.log(this.TAG,"event_data",JSON.stringify(n)),t.handleMessage(EFrameDataType.EVENT,n)}catch(t){this.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),n.on("sync_frame",e=>{t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),n.on("aa_frame",e=>{window.avatarSDKLogger.log(this.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),n.on("error_message",t=>{this.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),n.on("disconnect",i=>{this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),"io client disconnect"!==i&&(this.enterOfflineFlag?window.avatarSDKLogger.warn(this.TAG,"已在离线处理中,忽略重复的disconnect事件"):(this.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:`client Warning: socket disconnect, ${i}`}),window.avatarSDKLogger.warn(this.TAG,`${t.url} 已断开`,"disconnect原因",i),this.enterOfflineFlag=!0,this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),-1===this.socketReconnectTimer&&this.reconnect_timeout>0&&(this.socketReconnectTimer=window.setTimeout(()=>{try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(this.TAG,"disconnect error",t)}this.socketReconnectTimer=-1},1e3*this.reconnect_timeout)),-1===this.reconnectTimer&&(this.reconnectTimer=window.setTimeout(async function(){try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(e.TAG,"disconnect error",t)}await e.sdk.stopSessionFromSocket("WS_TIMEOUT"),e.reStartSDK()},1e3*this.reconnect_client_timeout))))}),n.on("client_quit",t=>{window.avatarSDKLogger.warn(this.TAG,"client_quit","断开原因",t),n.disconnect(),this.session_speak_req_id=0,Object.keys(t).length&&this.sdk.onMessage({code:EErrorCode.SOCKET_QUIT,message:`ttsa主动关闭 reason: ${JSON.stringify({e:t})}`,e:t}),["user","char_bin_load_error","admin kick","nebula admin stop","no_time"].includes(null==t?void 0:t.stop_reason)?(this.sdk.destroyClient(),this.sdk.onStatusChange(AvatarStatus.close)):(this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),this.reStartSDK())}),n.on("connect_error",t=>{this.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),n.onAny((t,e)=>{this.ws.connected&&this.initWsTimeoutTimer()}),this.ws=n}start(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")}idle(){this.stateChange("idle")}listen(){this.stateChange("listen")}think(){this.stateChange("think")}interactiveidle(){this.stateChange("interactive_idle")}enterInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})}exitInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})}firstStartTimestamp(t){const e=Date.now()/1e3,n={server_time:t,client_time:e},i=this._getResumeInfo();this._isResume&&i&&i.client_frame>0?n.resume_from_offline_idle=i:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)}syncTimestamp(){this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(()=>{const t=Date.now();if(t-this.lastSyncTime>=this.SYNC_INTERVAL){const e=this.getCurrentFrameIndex();this.sendSyncTimestamp(e),this.lastSyncTime=t}},this.syncTimestampNum)}sendSyncTimestamp(t){const e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})}sendText(t,e,n,i={client_speak_id:""}){if(!this.ws.connected)return;const r=this.getUniqueSpeakId();null!=i&&i.client_speak_id||(i.client_speak_id=r);const s={ssml:t,is_start:e,is_end:n,extra:i,multi_turn_conversation_id:r,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.1.1"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},i,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:r,speak_id:this.session_speak_req_id++})),e&&(window.performanceTracker.markStart(performanceConstant.start_action_res,"speak"),window.performanceTracker.markStart(performanceConstant.start_action_render,"speak"),window.performanceTracker.markStart(performanceConstant.voice_response_play,"speak")),n&&this.updateUniqueSpeakId(),this.send("send_text",s),r}sendSdkPoint(t,e={},n){this.send("sdk_burial_point",_extends({},e,n,this.appInfo,{burial_type:1,session_id:this.session_id,event_en_name:t,event_cn_name:pointNameObj[t],device:navigator.userAgent,timestamp:e.timestamp||Date.now(),sdkVersion:"2.1.1"}))}stateChange(t,e){const n={state:t,params:e||{}};window.performanceTracker.markStart(performanceConstant.start_action_res,t),window.performanceTracker.markStart(performanceConstant.start_action_render,t),this.send("state_change",n)}sendPerfLog(t){}changeLayout(t){this.send("change_layout",t)}changeWalkConfig(t){this.send("walk_config",t)}send(t,e){this.ws.connected&&this.ws.emit(t,e)}sendDeviceInfo(t){this.send("stat_report",t)}getStatus(){return this.ws.connected}_setResumeInfoCallback(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e}_getResumeInfo(){if(this.getResumeInfo){const t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null}updateUniqueSpeakId(){this._uniqueSpeakId+=1}getUniqueSpeakId(){return`${this._uniqueSpeakId}-${this.session_id}`}close(){this.ws&&this.ws.disconnect(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.session_speak_req_id=0,-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0)}connect(){this.ws.connect()}seekToFrame(t){this.ws.emit("seek_to_frame",{frame:t})}}function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}`}catch(e){return window.avatarSDKLogger.error("Error formatting timestamp:",e),t}}class DebugOverlay{constructor(t,e){this.container=null,this.sdkContainer=null,this.updateInterval=null,this.errors=[],this.fps=0,this.frameCount=0,this.lastFpsUpdate=performance.now(),this.videoInfo={name:"",body_id:0,id:0},this.audioInfo={sf:0,ef:0,ad:new Uint8Array},this.eventInfo={sf:0,ef:0,event:[]},this.memoryInfo={},this.perfMetrics={},this.currentFrameIndex=0,this.domRefs={},this.sdk=t,this.sdkContainer=t.el,this.sessionInfo=e,this.startTime=Date.now(),this.trackFPS(),this.trackMemory()}setAudioInfo(t){this.audioInfo=t}setEventData(t){this.eventInfo=t}addError(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()}show(){this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(()=>this.updateTextOnly(),200)),this.updateTextOnly()}hide(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null}setVideoInfo(t){this.videoInfo=t}updateTextOnly(){var t,e;if(!this.container)return;this.sessionInfo.session_id=this.sdk.resourceManager.session_id,this.currentFrameIndex=null!=(t=null==(e=this.sdk.renderScheduler.frameAnimationController)?void 0:e.getCurrentFrame())?t:0,this.updatePerfMetrics(),this.updateMemory(),this.setText("look_name",this.sessionInfo.config.look_name),this.setText("video_name",`${this.videoInfo.name} - ${this.videoInfo.body_id}`),this.setText("session_id",this.sessionInfo.session_id),this.setText("frame_idx",String(this.currentFrameIndex)),this.setText("audio_info",`开始帧: ${this.audioInfo.sf} / 结束帧: ${this.audioInfo.ef} / 长度: ${this.audioInfo.ad.length}`),this.setText("event_info",`开始帧: ${this.eventInfo.sf} / 结束帧: ${this.eventInfo.ef} / 长度: ${this.eventInfo.event.length}`),this.setText("perf",this.formatPerfMetrics()),this.setText("fps",String(this.fps)),this.setText("mem",this.formatMemory());const n=((Date.now()-this.startTime)/1e3).toFixed(1);this.setText("session_start",formatTimestamp(this.sessionInfo.session_start_time)),this.setText("session_duration",`${n}s`),this.setText("network",this.getNetworkInfo()),this.setText("error_count",`(${this.errors.length})`),this.setText("error_log",this.formatErrors(!1)),this.setText("ttsa_error_log",this.formatErrors(!0))}setText(t,e){const n=this.domRefs[t];n&&(n.innerHTML=e)}copySessionId(){const t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(()=>{}).catch(t=>{console.warn("复制失败",t)})}createOverlay(){var t;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";const e=(t,e,n="")=>{const i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML=`<span style="color:#888;font-size:11px;">${e}:</span>`;const r=document.createElement("span");return r.style.color="#fff",r.style.fontSize="11px",r.style.marginLeft="4px",r.textContent=n,i.append(r),this.domRefs[t]=r,i},n=document.createElement("h3");n.textContent="🔍 调试信息",n.style.margin="0 0 12px 0",n.style.color="#00ff88",n.style.fontSize="14px";const i=document.createElement("div");i.append(n,e("look_name","角色look_name"),e("video_name","当前视频"),(()=>{const t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";const e=document.createElement("span");e.style.color="#888",e.style.fontSize="11px",e.textContent="会话 ID:";const n=document.createElement("span");n.style.color="#fff",n.style.fontSize="11px",n.style.wordBreak="break-all",n.style.flex="1",this.domRefs.session_id=n;const i=document.createElement("button");return i.textContent="复制",i.style.fontSize="10px",i.style.padding="2px 6px",i.style.borderRadius="3px",i.style.border="none",i.style.background="#007aff",i.style.color="#fff",i.style.cursor="pointer",i.onclick=()=>this.copySessionId(),t.append(e,n,i),t})(),e("frame_idx","当前帧"),e("audio_info","下发音频"),e("event_info","下发事件"),e("fps","FPS"));const r=document.createElement("div");r.style.marginBottom="8px",r.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';const s=document.createElement("div");s.style.fontSize="11px",s.style.background="rgba(0,0,0,0.2)",s.style.padding="4px",s.style.borderRadius="4px",s.style.color="#fff",this.domRefs.perf=s,i.append(r,s);const a=document.createElement("div");a.style.borderTop="1px solid #444",a.style.paddingTop="8px",a.style.marginBottom="8px";const o=document.createElement("h4");o.style.margin="0 0 6px 0",o.style.fontSize="12px",o.style.color="#888";const l=document.createElement("span");this.domRefs.error_count=l,o.append("✅ 错误日志 ",l),a.append(o);const h=t=>{const e=document.createElement("pre");return e.style.margin="0 0 4px 0",e.style.padding="6px",e.style.background="rgba(255,255,255,0.05)",e.style.borderRadius="4px",e.style.fontSize="10px",e.style.lineHeight="1.3",e.style.color="#888",e.style.maxHeight="120px",e.style.overflowY="auto",e.style.whiteSpace="pre-wrap",this.domRefs[t]=e,e},d=h("error_log"),c=h("ttsa_error_log");a.append(d,c),i.append(a),i.append(e("mem","内存占用"),e("session_start","会话开始时间"),e("session_duration","会话时长"),e("network","网络信息")),this.container.append(i),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)}formatErrors(t){let e=this.errors;return e=e.filter(t?t=>t.code===EErrorCode.TTSA_ERROR:t=>t.code!==EErrorCode.TTSA_ERROR),0===e.length?"暂无错误":e.map(t=>`[${new Date(t.timestamp).toLocaleTimeString()}] ${t.code}: ${t.message}`).join("\n")}updatePerfMetrics(){if(!window.performanceTracker)return;const t=window.performanceTracker.getVideoMetrics();for(const[n,i]of Object.entries(t)){var e;const t=null!=(e=null==i?void 0:i.time)?e:0;this.perfMetrics[n]||(this.perfMetrics[n]={times:[],avg:0,last:0,count:0});const r=this.perfMetrics[n];r.times.push(t),r.last=t,r.count++,r.avg=r.times.reduce((t,e)=>t+e,0)/r.times.length}}formatPerfMetrics(){const t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(([t,e])=>`${t}: 最近:${e.last.toFixed(2)}ms 平均:${e.avg.toFixed(2)}ms 次数:${e.count}`).join("<br>"):"暂无数据"}formatMemory(){const t=this.memoryInfo;return t.usedJSHeapSize?`${(t.usedJSHeapSize/1048576).toFixed(1)}MB / ${(t.totalJSHeapSize/1048576).toFixed(1)}MB / ${(t.jsHeapSizeLimit/1048576).toFixed(1)}MB`:"N/A"}trackFPS(){const t=e=>{this.frameCount++,e-this.lastFpsUpdate>=1e3&&(this.fps=this.frameCount,this.frameCount=0,this.lastFpsUpdate=e),requestAnimationFrame(t)};requestAnimationFrame(t)}updateMemory(){var t;if(null!=(t=window.performance)&&t.memory){const t=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:t.jsHeapSizeLimit,totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize}}}trackMemory(){var t;null!=(t=window.performance)&&t.memory&&setInterval(()=>this.updateMemory(),1e3)}getNetworkInfo(){const t=navigator.connection;return t?`类型:${t.effectiveType} 下行:${t.downlink}Mbps 延迟:${t.rtt}ms`:"N/A"}applyStyles(t){t.style.position="fixed",t.style.bottom="50px",t.style.right="10px",t.style.width="350px",t.style.maxHeight="400px",t.style.overflowY="auto",t.style.background="rgba(0,0,0,0.8)",t.style.borderRadius="8px",t.style.padding="10px",t.style.zIndex="99999",t.style.fontSize="12px",t.style.color="#fff",t.style.textAlign="left"}enableDrag(t){let e=!1,n=0,i=0,r=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",a=>{e=!0,n=a.clientX,i=a.clientY,r=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",a=>{e&&(t.style.left=r+a.clientX-n+"px",t.style.top=s+a.clientY-i+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",()=>{e=!1,document.body.style.userSelect=""})}}class NetworkMonitor{constructor(t){this.TAG="[NetworkMonitor]",this.retryCount=1,this.retryTimer=-1,this.options=t,this.bindHandleOnline=this._handleOnline.bind(this),this.bindHandleOffline=this._handleOffline.bind(this),this._initEventListeners()}_initEventListeners(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)}_handleOnline(){window.clearTimeout(this.retryTimer),NetworkMonitor.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")}_handleOffline(){NetworkMonitor.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()}_attempt(){let t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(()=>{},t)}setState(t){NetworkMonitor.ONLINE=t}destroy(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1}}function Errors(t){var e,n;return{code:t.code,error_code:null!=(e=ERROR_CODE_MAP[t.code])?e:t.code,error_name:null!=(n=ERROR_NAME_MAP[t.code])?n:"UNKNOWN_ERROR",message:t.message,session_id:t.session_id||"",client_speak_id:t.client_speak_id,timestamp:Date.now(),originalError:t.e?JSON.stringify(t.e):null}}NetworkMonitor.ONLINE=!0;let isLoggingEnabled=!1;function executeLog(t,...e){isLoggingEnabled&&"function"==typeof t&&t(...e)}const sdkLog={log:(...t)=>executeLog(console.log,...t),info:(...t)=>executeLog(console.info,...t),warn:(...t)=>executeLog(console.warn,...t),error:(...t)=>executeLog(console.error,...t)};function setLoggingEnabled(t){isLoggingEnabled=t,t?console.log("[AVATAR SDK] version:","2.1.1","日志已启用"):console.log("[AVATAR SDK] version:","2.1.1","日志已禁用")}function sampleUniformTensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function sampleUniformPCATensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255*2-1:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535*2-1:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295*2-1:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295*2-1:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function getVertices(t,e){let n=t.char,i=n.evalSkeleton(),r=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=r[t].apply(i[t].inv());s[t]=e.homogeneous_matrix()}let a=[];for(let t=0;t<n.mesh.length;t++){let i=[];for(let r=0;r<n.mesh[t].blendshapes.size[0];r++){let a=[],o=n.mesh[t].vertices,l=n.mesh[t].blendshapes,h=e.blendshapeWeights;for(let t=0;t<3;t++)a.push(o.data[r*o.size[1]+t]);for(let e=0;e<n.mesh[t].blendshapeIndices.length;e++)for(let i=0;i<3;i++)a[i]+=h[n.mesh[t].blendshapeIndices[e]]*Number(l.data[(r*l.size[1]+i)*l.size[2]+e]);a.push(1);let d=[0,0,0,0],c=n.mesh[t].jointIndex,u=n.mesh[t].jointWeight;for(let t=0;t<n.maxJointsPerVertex;t++){let e=c[r*n.maxJointsPerVertex+t];if(e<n.skeleton.length){let i=mvmul(s[e],a);for(let e=0;e<4;e++)d[e]+=u[r*n.maxJointsPerVertex+t]*i[e]}}for(let t=0;t<3;t++)d[t]/=d[3];i.push([d[0],d[1],d[2]])}a.push(i)}return a}function getPCATextures(t,e){let n=t.char,i=[];for(let t=0;t<n.mesh.length;t++){let r=n.mesh[t].textureModels[e.mesh[t].textureModelIndex],s=[],a=new Uint8ClampedArray(r.data.size[1]*r.data.size[2]*4),o=1;r.scalingFactor&&(o*=Number(r.scalingFactor.data[0]));for(let t=0;t<r.data.size[1];t++){let e=[];for(let n=0;n<r.data.size[2];n++){let i=[];for(let e=0;e<3;e++)i.push(o*sampleUniformPCATensor(r.data.data,3*(t*r.data.size[2]+n)+e));e.push(i)}s.push(e)}for(let n=1;n<r.data.size[0];n++){let i=e.mesh[t].texturePCAWeights[n-1];r.scalingFactor&&(i*=Number(r.scalingFactor.data[n]));for(let t=0;t<r.data.size[1];t++)for(let e=0;e<r.data.size[2];e++)for(let a=0;a<3;a++)s[t][e][a]+=i*sampleUniformPCATensor(r.data.data,3*((n*r.data.size[1]+t)*r.data.size[2]+e)+a)}for(let t=0;t<r.data.size[1];t++)for(let e=0;e<r.data.size[2];e++){for(let n=0;n<3;n++)a[4*(t*r.data.size[2]+e)+n]=Math.round(255*s[r.data.size[1]-1-t][e][2-n]);a[4*(t*r.data.size[2]+e)+3]=255}i.push(new ImageData(a,r.data.size[1],r.data.size[2]))}return i}function exportAsWavefrontObj(t){let e="",n="",i=1,r=0;for(const s of t){for(const t of s.vertices)e+=`v ${t[0]} ${t[1]} ${t[2]}\n`;for(const t of s.uv)e+=`vt ${t[0]} ${t[1]}}\n`;n+=`g Obj${r}\n`;for(const t of s.polygons)n+=`f ${t.map(t=>(t+i).toString()).map(t=>`${t}/${t}`).join(" ")}\n`;i+=s.vertices.length,r+=1}return e+n}function getWavefrontObjFromVertices(t,e){function n(t,e){let n=[];for(let i=0;i<t.length;i++)0==i%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,i));return n}function i(t,e){let n=[];for(let i=0;i<t.length;i++)0==i%e&&n.push([]),n[n.length-1].push(Number(t[i]));return n}let r=t.char,s=[];for(let t=0;t<r.mesh.length;t++)s.push({vertices:e[t],uv:n(r.mesh[t].UVCoord.data,2),polygons:i(r.mesh[t].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});class StreamingClient{constructor(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}connect(){if(!this.destroyed){try{this.ws=new WebSocket(this.options.url)}catch(t){return console.error("[StreamingClient] 创建 WebSocket 失败:",t),void this.scheduleRetry()}this.ws.onopen=()=>{this.connected=!0,this.retryCount=0,console.log("[StreamingClient] 已连接"),this.send({type:"join",role:"client"})},this.ws.onmessage=t=>{let e;try{e=JSON.parse(t.data)}catch(t){return}this.handleMessage(e)},this.ws.onclose=()=>{var t,e;this.connected=!1,this.destroyed||(null==(t=(e=this.options).onDisconnect)||t.call(e),this.scheduleRetry())},this.ws.onerror=()=>{var t,e;null==(t=(e=this.options).onError)||t.call(e,"WebSocket 连接错误")}}}handleMessage(t){var e,n,i,r,s,a,o,l,h,d;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(i=(r=this.options).onOffer)||i.call(r,t.sdp);break;case"answer":break;case"ice":null==(s=(a=this.options).onIce)||s.call(a,t.candidate);break;case"event_proxy":null==(o=(l=this.options).onEventProxy)||o.call(l,t.event_type,t.data,t.server_frame);break;case"error":null==(h=(d=this.options).onError)||h.call(d,t.message||"未知错误")}}send(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}sendApiCall(t,e=[]){this.send({type:"api_call",method:t,params:e})}scheduleRetry(){if(this.destroyed)return;var t,e;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(t=(e=this.options).onError)||t.call(e,"连接重试次数已达上限"));const n=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(()=>{this.connect()},n)}isConnected(){return this.connected}destroy(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}}class VideoPlayer{constructor(t){this.video=null,this.canvas=null,this.canvasCtx=null,this.pc=null,this.stream=null,this.destroyed=!1,this.animFrameId=0,this.tempCanvas=null,this.tempCtx=null,this.options=t,t.useAlphaMask?this.createCanvasElement():this.createVideoElement()}createVideoElement(){const t=document.createElement("video");t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.video=t,this.options.container.appendChild(t)}createCanvasElement(){const t=document.createElement("canvas");t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.canvas=t,this.canvasCtx=t.getContext("2d",{willReadFrequently:!0}),this.tempCanvas=document.createElement("canvas"),this.tempCtx=this.tempCanvas.getContext("2d",{willReadFrequently:!0}),this.options.container.appendChild(t);const e=document.createElement("video");e.autoplay=!0,e.playsInline=!0,e.muted=!0,e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.pointerEvents="none",e.style.zIndex="-1",this.video=e,this.options.container.appendChild(e)}async handleOffer(t){this.destroyPeer(),this.pc=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:openrelay.metered.ca:80",username:"openrelayproject",credential:"openrelayproject"},{urls:"turn:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"},{urls:"turns:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"}]}),this.pc.onicecandidate=t=>{t.candidate&&this.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},this.pc.ontrack=t=>{console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),this.stream||(this.stream=new MediaStream,this.video&&(this.video.srcObject=this.stream)),this.stream.addTrack(t.track),"audio"===t.track.kind&&this.video&&(this.video.muted=!1,this.video.play().catch(()=>{})),"video"===t.track.kind&&this.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),this.startAlphaRendering())},this.pc.onconnectionstatechange=()=>{var t,e;if(this.pc)if(console.log("[VideoPlayer] WebRTC 状态:",this.pc.connectionState),"connected"===this.pc.connectionState)null==(t=(e=this.options).onConnected)||t.call(e);else if("disconnected"===this.pc.connectionState||"failed"===this.pc.connectionState){var n,i;null==(n=(i=this.options).onDisconnected)||n.call(i)}},await this.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}));const e=await this.pc.createAnswer();await this.pc.setLocalDescription(e),this.options.streamingClient.send({type:"answer",sdp:e.sdp})}startAlphaRendering(){if(!(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx))return;const t=this.video,e=this.canvas,n=this.canvasCtx,i=this.tempCanvas,r=this.tempCtx;let s=0,a=0,o=0,l=null;l=setInterval(()=>{this.destroyed?l&&clearInterval(l):console.log(`[VideoPlayer] Alpha 渲染调试: frames=${o}, videoReadyState=${t.readyState}, videoSize=${t.videoWidth}x${t.videoHeight}, currentTime=${t.currentTime.toFixed(2)}s, paused=${t.paused}`)},2e3);const h=()=>{if(this.destroyed)l&&clearInterval(l);else{if(t.readyState>=2&&t.videoWidth>0){const l=t.videoWidth,h=t.videoHeight,d=l/2,c=h;l===s&&h===a||(e.width=d,e.height=c,i.width=l,i.height=c,s=l,a=h,console.log(`[VideoPlayer] Alpha Mask: 检测到双流 ${l}x${h} → 原始 ${d}x${c}`)),r.clearRect(0,0,2*d,c),r.drawImage(t,0,0),n.clearRect(0,0,d,c),n.drawImage(i,0,0,d,c,0,0,d,c);try{const t=n.getImageData(0,0,d,c),e=r.getImageData(d,0,d,c),i=t.data,s=e.data;if(0===o){let t=0,e=0;const n=Math.min(1e3,i.length/4);for(let r=0;r<4*n;r+=4)(i[r]>0||i[r+1]>0||i[r+2]>0)&&t++,s[r]>0&&e++;console.log(`[VideoPlayer] 首帧像素检查: RGB非零=${t}/${n}, Alpha非零=${e}/${n}`),0===t&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(let t=0;t<i.length;t+=4)i[t+3]=s[t];n.putImageData(t,0,0),o++}catch(e){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",e),n.drawImage(t,0,0,d,c,0,0,d,c),o++}}this.animFrameId=requestAnimationFrame(h)}};this.animFrameId=requestAnimationFrame(h)}async addIceCandidate(t){this.pc&&await this.pc.addIceCandidate(t).catch(t=>{console.warn("[VideoPlayer] addIceCandidate 失败:",t)})}getVideoElement(){return this.video}getCanvasElement(){return this.canvas}isConnected(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)}destroyPeer(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)}destroy(){this.destroyed=!0,this.destroyPeer(),this.video&&this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.video=null,this.canvas=null,this.canvasCtx=null,this.tempCanvas=null,this.tempCtx=null}}class EventDispatcher{constructor(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}dispatch(t,e,n){var i,r,s,a,o,l,h,d,c,u,f,p,_,m,g,y,v,b,S,E,w,x,T,A,R,B;switch(t){case"state_change":null==(i=(r=this.callbacks).onStateChange)||i.call(r,e.state||e);break;case"speak_state_change":null==(s=(a=this.callbacks).onSpeakStateChange)||s.call(a,e.state,e.client_speak_id);break;case"voice_state_change":null==(o=(l=this.callbacks).onVoiceStateChange)||o.call(l,e.state,e.duration,e.client_speak_id||"");break;case"status_change":null==(h=(d=this.callbacks).onStatusChange)||h.call(d,e.status);break;case"render_change":null==(c=(u=this.callbacks).onRenderChange)||c.call(u,e.state);break;case"walk_state_change":null==(f=(p=this.callbacks).onWalkStateChange)||f.call(p,e.state||e);break;case"widget_event":null==(_=(m=this.callbacks).onWidgetEvent)||_.call(m,e);break;case"message":case"error":null==(g=(y=this.callbacks).onMessage)||g.call(y,e);break;case"network_info":null==(v=(b=this.callbacks).onNetworkInfo)||v.call(b,e);break;case"fps_update":null==(S=(E=this.callbacks).onFPSUpdate)||S.call(E,e);break;case"download_progress":null==(w=(x=this.callbacks).onDownloadProgress)||w.call(x,e.progress);break;case"session_id":null==(T=(A=this.callbacks).onSessionId)||T.call(A,e.session_id);break;case"frame_data_update":null==(R=(B=this.callbacks).onFrameDataUpdate)||R.call(B,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}}getSubtitleText(){return this.subtitleText}isSubtitleVisible(){return this.subtitleVisible}}class APIForwarder{constructor(t){this.client=t}speak(t,e=!0,n=!0,i={}){this.client.sendApiCall("speak",[t,e,n,i])}idle(){this.client.sendApiCall("idle",[])}listen(){this.client.sendApiCall("listen",[])}think(){this.client.sendApiCall("think",[])}interactiveidle(){this.client.sendApiCall("interactiveidle",[])}interrupt(t){this.client.sendApiCall("interrupt",[t])}changeLayout(t){this.client.sendApiCall("changeLayout",[t])}changeWalkConfig(t){this.client.sendApiCall("changeWalkConfig",[t])}setVolume(t){this.client.sendApiCall("setVolume",[t])}changeAvatarVisible(t){this.client.sendApiCall("changeAvatarVisible",[t])}switchInvisibleMode(){this.client.sendApiCall("switchInvisibleMode",[])}destroy(t="user"){this.client.sendApiCall("destroy",[t])}init(t){this.client.send({type:"init",config:t})}}function checkSecureContextSync(){const t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{const t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};const e=t.getExtension("WEBGL_debug_renderer_info");return{name:"webgl2",supported:!0,severity:"fatal",detail:{version:t.getParameter(t.VERSION),vendor:t.getParameter(t.VENDOR),renderer:t.getParameter(t.RENDERER),gpuVendor:e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):void 0,gpuRenderer:e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):void 0}}}catch(t){return{name:"webgl2",supported:!1,severity:"fatal",reason:"WebGL2 初始化失败",detail:t}}}function checkAudioSystemSync(){const t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,i=void 0!==window.MediaSource,r={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:i,hasMediaSource:i}};return n||i?{name:"audio",supported:!0,severity:"fatal",detail:r}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:r}}function checkWebCodecsSync(){const t=void 0!==window.VideoDecoder,e=(navigator.userAgent||"").toLowerCase(),n=/android/.test(e)||/openharmony|arkweb/.test(e);return{name:"webcodecs",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t,isAndroid:n,hardwareAcceleration:n?"prefer-software":"default"}}}function checkWorkerSync(){const t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}function checkCapabilitySync(t=!1){const e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkWorkerSync());const n=e.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(t=>"warn"===t.severity&&!t.supported).length,items:e}}async function checkWebCodecsDetailed(){try{const t=void 0!==window.VideoDecoder;if(!t)return{name:"webcodecs",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t}};const e=(navigator.userAgent||"").toLowerCase(),n=/android/.test(e)||/openharmony|arkweb/.test(e),i=2160,r=1920;let s={};const a=["avc1.42E01E","avc1.4D001F","avc1.64001F"];let o=!1,l=!1,h=!1;for(const t of a)try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:i,codedHeight:r}),a=!(null==e||!e.supported);a&&(l=!0);let h=null;if(n){try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:i,codedHeight:r,hardwareAcceleration:"prefer-software"});h=!(null==e||!e.supported)}catch(t){h=!1}h&&(o=!0)}else a&&(o=!0);s[t]={default:a,software:h}}catch(e){h=!0,s[t]={default:!1,software:null,error:"probe-failed"}}const d=o||l,c=h&&!d?"warn":"fatal";return{name:"webcodecs",supported:d,severity:c,reason:d?void 0:"warn"===c?"WebCodecs 探测异常(运行时将以实际视频配置二次确认)":"浏览器不支持 H.264 解码(默认/软解配置均不可用)",detail:{hasVideoDecoder:t,isAndroid:n,hardwareAcceleration:n?"prefer-software":"default",codecSupport:s}}}catch(t){return{name:"webcodecs",supported:!1,severity:"fatal",reason:"WebCodecs 探测失败",detail:t}}}const WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(t=>{let e=null,n=null,i=!1,r=null;const s=s=>{var a;i||(i=!0,null!==r&&clearTimeout(r),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{const t=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(t),e=new Worker(n),e.onmessage=t=>{s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=t=>{s({status:"failed",reason:"Web Worker 创建失败",detail:t})},r=setTimeout(()=>{s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}async function checkWorkerDetailed(){if("undefined"==typeof Worker)return{name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"};for(let t=1;t<=WORKER_CHECK_MAX_ATTEMPTS;t+=1){const e=await probeWorkerExecution();if("supported"===e.status)return{name:"worker",supported:!0,severity:"fatal",detail:{attempts:t}};if("failed"===e.status)return{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}}return{name:"worker",supported:!1,severity:"warn",reason:`Web Worker 创建超时(已重试 ${WORKER_CHECK_MAX_ATTEMPTS} 次)`,detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}}async function checkCapability(t=!1){const e=checkCapabilitySync(t);if(t){const t=await Promise.all([Promise.resolve(e.items.find(t=>"secureContext"===t.name)),Promise.resolve(e.items.find(t=>"audio"===t.name)),checkWorkerDetailed()]),n=t.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:t.filter(t=>"warn"===t.severity&&!t.supported).length,items:t}}const n=await Promise.all([Promise.resolve(e.items.find(t=>"secureContext"===t.name)),Promise.resolve(e.items.find(t=>"webgl2"===t.name)),Promise.resolve(e.items.find(t=>"audio"===t.name)),checkWebCodecsDetailed(),checkWorkerDetailed()]),i=n.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===i,fatalCount:i,warnCount:n.filter(t=>"warn"===t.severity&&!t.supported).length,items:n}}const OPUS_FRAME_DURATION_US=2e4,ENCODE_TIMEOUT_MS=2e3;function buildAudioEncoderConfig(t){return{codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.channels,bitrate:t.bitrate,opus:{format:"opus",frameDuration:OPUS_FRAME_DURATION_US}}}class WebCodecOpusEncoder{constructor(t={}){this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=_extends({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},t)}static async isSupported(){if("undefined"==typeof AudioEncoder)return!1;try{var t;const e=await AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}));return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===OPUS_FRAME_DURATION_US}catch(t){return!1}}async init(){this.isInitialized||(this.encoder=this.createEncoder(),this.isInitialized=!0)}async encode(t){if(!this.isInitialized||!this.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(this.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));const e=new Int16Array(t),n=this.timestamp,i=Math.round(1e6*t.length/this.config.sampleRate),r=n+i,s=i/OPUS_FRAME_DURATION_US;if(!Number.isInteger(s))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));const a=new AudioData({format:"s16",sampleRate:this.config.sampleRate,numberOfFrames:e.length,numberOfChannels:this.config.channels,timestamp:n,data:e}),o=new Promise((t,e)=>{const i=globalThis.setTimeout(()=>{this.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);this.pendingEncode={startTimestampUs:n,endTimestampUs:r,expectedFrameCount:s,chunks:[],resolve:t,reject:e,timeoutId:i}});try{this.encoder.encode(a),this.timestamp=r}catch(t){this.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{a.close()}return o}reset(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}}async destroy(){const t=this.encoder;if(t){try{await t.flush()}catch(t){}this.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{t.close()}catch(t){}}this.encoder=null,this.isInitialized=!1}createEncoder(){let t;return t=new AudioEncoder({output:e=>{this.encoder===t&&this.handleOutput(e)},error:e=>{if(this.encoder!==t)return;const n=e instanceof Error?e:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",n),this.failPending(n)}}),t.configure(buildAudioEncoderConfig(this.config)),t}handleOutput(t){const e=this.pendingEncode;if(!e)return;if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.length<e.expectedFrameCount)return;const n=e.chunks.map((t,n)=>{var i,r;const s=new Uint8Array(t.byteLength);t.copyTo(s);const a=null!=(i=null==(r=e.chunks[n+1])?void 0:r.timestamp)?i:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),i=n.reduce((t,e)=>t+e.durationMs,0);n.some(t=>t.durationMs!==OPUS_FRAME_DURATION_US/1e3)||i!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}failPending(t){const e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))}}const EBML_ID={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SegmentInfo:357149030,TimecodeScale:2807729,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,Language:2274716,CodecID:134,CodecPrivate:25506,CodecDelay:22186,SeekPreRoll:22203,Audio:225,SamplingFrequency:181,Channels:159,Cluster:524531317,Timecode:231,SimpleBlock:163};class WebMMuxer{constructor(t=16e3){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}writeHeader(){if(this.hasHeader)return;const t=this.buildEBMLHeader(),e=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(t),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(e),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}feedOpusFrame(t,e=this.frameDuration){this.hasHeader||this.writeHeader();const n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e}flush(){if(0===this.chunks.length)return new ArrayBuffer(0);const t=this.chunks.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const t of this.chunks)e.set(t,n),n+=t.length;return this.chunks=[],e.buffer}reset(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0}encodeVINT(t,e){if(void 0!==e){const n=new Uint8Array(e);for(let i=e-1;i>=0;i--)n[i]=255&t,t>>>=8;return n[0]|=1<<8-e,n}if(t<127)return new Uint8Array([128|t]);if(t<16383)return new Uint8Array([64|t>>8,255&t]);if(t<2097151)return new Uint8Array([32|t>>16,t>>8&255,255&t]);if(t<268435455)return new Uint8Array([16|t>>24,t>>16&255,t>>8&255,255&t]);throw new Error(`VINT value too large: ${t}`)}encodeID(t){return t<=255?new Uint8Array([t]):t<=65535?new Uint8Array([t>>8,255&t]):t<=16777215?new Uint8Array([t>>16,t>>8&255,255&t]):new Uint8Array([t>>>24,t>>16&255,t>>8&255,255&t])}encodeUint(t){if(0===t)return new Uint8Array([0]);const e=[];let n=t;for(;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)}encodeString(t){return(new TextEncoder).encode(t)}encodeFloat32(t){const e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)}encodeElement(t,e){const n=this.encodeID(t),i=this.encodeVINT(e.length),r=new Uint8Array(n.length+i.length+e.length);return r.set(n,0),r.set(i,n.length),r.set(e,n.length+i.length),r}encodeUintElement(t,e){return this.encodeElement(t,this.encodeUint(e))}encodeStringElement(t,e){return this.encodeElement(t,this.encodeString(e))}encodeFloat32Element(t,e){return this.encodeElement(t,this.encodeFloat32(e))}concatArrays(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let i=0;for(const e of t)n.set(e,i),i+=e.length;return n}buildEBMLHeader(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.EBMLVersion,1),this.encodeUintElement(EBML_ID.EBMLReadVersion,1),this.encodeUintElement(EBML_ID.EBMLMaxIDLength,4),this.encodeUintElement(EBML_ID.EBMLMaxSizeLength,8),this.encodeStringElement(EBML_ID.DocType,"webm"),this.encodeUintElement(EBML_ID.DocTypeVersion,4),this.encodeUintElement(EBML_ID.DocTypeReadVersion,2)]);return this.encodeElement(EBML_ID.EBML,t)}buildSegmentInfo(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.TimecodeScale,1e6),this.encodeStringElement(EBML_ID.MuxingApp,"xmov-avatar-sdk"),this.encodeStringElement(EBML_ID.WritingApp,"xmov-avatar-sdk")]);return this.encodeElement(EBML_ID.SegmentInfo,t)}buildOpusTracks(){const t=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),e=this.concatArrays([this.encodeFloat32Element(EBML_ID.SamplingFrequency,this.sampleRate),this.encodeUintElement(EBML_ID.Channels,1)]),n=this.concatArrays([this.encodeUintElement(EBML_ID.TrackNumber,1),this.encodeUintElement(EBML_ID.TrackUID,1),this.encodeUintElement(EBML_ID.TrackType,2),this.encodeUintElement(EBML_ID.FlagLacing,0),this.encodeStringElement(EBML_ID.Language,"und"),this.encodeStringElement(EBML_ID.CodecID,"A_OPUS"),this.encodeElement(EBML_ID.CodecPrivate,t),this.encodeUintElement(EBML_ID.CodecDelay,0),this.encodeUintElement(EBML_ID.SeekPreRoll,8e7),this.encodeElement(EBML_ID.Audio,e)]),i=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,i)}buildCluster(t,e){const n=this.encodeUintElement(EBML_ID.Timecode,t),i=this.encodeVINT(1),r=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([i,r,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)}}class PcmWebMEncoder{constructor(){this.opusEncoder=new WebCodecOpusEncoder({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new WebMMuxer(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}static isSupported(){return WebCodecOpusEncoder.isSupported()}async init(){await this.opusEncoder.init()}async encode(t){var e=this;if(1600!==t.length)throw new Error(`PCM 音频块必须为 1600 samples,实际为 ${t.length}`);if(this.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");this.pendingBlocks+=1;const n=this.generation,i=new Int16Array(t),r=this.queue.then(async function(){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);const t=await e.opusEncoder.encode(i);if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(const n of t)e.muxer.feedOpusFrame(n.data,n.durationMs);return e.muxer.flush()}).finally(()=>{this.pendingBlocks-=1});return this.queue=r.then(()=>{},()=>{}),r}reset(){const t=++this.generation;this.queue=this.queue.then(()=>{this.destroyed||t!==this.generation||(this.opusEncoder.reset(),this.muxer.reset())})}async destroy(){this.destroyed=!0,this.generation+=1,await this.opusEncoder.destroy(),await this.queue,this.muxer.reset()}}class MediaRecorderEncoder{constructor(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}static isSupported(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")}async init(){const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=new t({sampleRate:16e3});const e=new Blob(["\n class PCMInjectorProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(0);\n this.port.onmessage = (e) => {\n if (e.data.type === 'pcm') {\n const int16 = new Int16Array(e.data.pcm);\n const float32 = new Float32Array(int16.length);\n for (let i = 0; i < int16.length; i++) {\n float32[i] = int16[i] / 32768;\n }\n const newBuffer = new Float32Array(this.buffer.length + float32.length);\n newBuffer.set(this.buffer);\n newBuffer.set(float32, this.buffer.length);\n this.buffer = newBuffer;\n }\n };\n }\n process(inputs, outputs) {\n const output = outputs[0][0];\n if (!output) return true;\n const len = Math.min(output.length, this.buffer.length);\n for (let i = 0; i < len; i++) {\n output[i] = this.buffer[i];\n }\n this.buffer = this.buffer.slice(len);\n for (let i = len; i < output.length; i++) {\n output[i] = 0;\n }\n return true;\n }\n }\n registerProcessor('pcm-injector-processor', PCMInjectorProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(e);await this.audioCtx.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-injector-processor"),this.destination=this.audioCtx.createMediaStreamDestination(),this.workletNode.connect(this.destination);const i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";this.recorder=new MediaRecorder(this.destination.stream,{mimeType:i,audioBitsPerSecond:24e3}),this.recorder.ondataavailable=t=>{t.data&&t.data.size>0&&t.data.arrayBuffer().then(t=>{if(this.nextResolve){const e=this.nextResolve;this.nextResolve=null,e(t)}else this.dataQueue.push(t)})},"suspended"===this.audioCtx.state&&await this.audioCtx.resume()}async feedPCM(t){return this.workletNode&&this.recorder?(this.isRecording||(this.recorder.start(100),this.isRecording=!0),this.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),this.dataQueue.length>0?this.dataQueue.shift():new Promise(t=>{const e=setTimeout(()=>{this.nextResolve=null,t(null)},200);this.nextResolve=n=>{clearTimeout(e),t(n)}})):null}reset(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}destroy(){var t,e;if(this.nextResolve=null,this.dataQueue=[],this.recorder)try{"inactive"!==this.recorder.state&&this.recorder.stop()}catch(t){}null==(t=this.workletNode)||t.disconnect(),null==(e=this.destination)||e.disconnect();try{var n;null==(n=this.audioCtx)||n.close()}catch(t){}this.recorder=null,this.workletNode=null,this.destination=null,this.audioCtx=null}}class XmovAvatar{constructor(t){if(this.TAG="[XMOV AVATAR]",this.el=null,this.status=-1,this.networkMonitor=null,this.ttsa=null,this.debugOverlay=null,this._offlineTimer=-1,this._offlineInterval=300,this._env="production",this.avatarCanvasVisible=!0,this.pendingInvisibleMode=!1,this.isInitialized=!1,this.onStateChange=()=>{},this.onDownloadProgress=null,this.replayData=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.enableClientInterrupt=!1,this.retryCount=1,this.retryTimer=-1,this.maxRetryCount=9,this.retryRound=1,this.maxRetryRound=3,this.isRetrying=!1,this.isStartRetry=!1,this.destroyed=!1,this.incompleteInitializationCleanupPromise=null,this.captureAudioCtx=null,this.captureWorklet=null,this.captureSource=null,this.captureSetupPromise=null,this.captureLastSpeechId=-2,this.restartPlaybackCaptureImpl=null,this.captureEncodeQueue=Promise.resolve(),this.captureGeneration=0,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmWebMEncoder=null,this.mediaRecorderEncoder=null,this.pcmCaptureMode="none",this.pcmEncodeId=0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this._isClientMode=!1,this._streamingClient=null,this._videoPlayer=null,this._eventDispatcher=null,this._apiForwarder=null,this._clientOnDownloadProgress=null,this._pendingInit=!1,this._pendingInitConfig=null,this._clientSessionId="",this.handleBeforeUnload=()=>{this.destroy("beforeunload")},window.avatarSDKLogger.setEnabled(t.enableLogger),this.options=t,this._env=t.env||"production",this.enableClientInterrupt=t.enableClientInterrupt||!1,this.boundVisibilityChange=this.visibilitychange.bind(this),"client"===t.renderMode)return this._isClientMode=!0,void this.initializeClient(t);this.initializeSDK(t),this.networkMonitor=new NetworkMonitor({offlineCallback:t=>{if(this.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_offline_before_init");this.status!==AvatarStatus.offline&&this.offlineHandle()},onlineCallback:t=>{var e;if(this.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_online_before_init");null==(e=this.ttsa)||e.clearReconnectTimer(),this.isStartRetry&&this.triggerReconnect()}})}getStatus(){return this.status}getIsInitialized(){return this.isInitialized}get businessENV(){return this._env}getUniqueSpeakId(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||`0-${this.getSessionId()}`}async initializeSDK(t){var e,n,i;if(!navigator.onLine)return void this.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"});const r=this,s=t,{containerId:a,container:o,appId:l,appSecret:h,gatewayServer:d,cacheServer:c,config:u}=t,{scale:f=1}=null!=(e=null==u||null==(n=u.layout)?void 0:n.avatar)?e:{};null!=u&&null!=(i=u.layout)&&null!=(i=i.avatar)&&i.scale&&(u.layout.avatar.scale=validateScaleWithDecimal(f,"initializeSDK"));const p=_extends({},u||{},{raw_audio:!isSupportMES()});if(o&&o instanceof HTMLElement)this.el=o;else{const t=document.querySelector(a);if(!t)return void this.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${a} 不存在`});this.el=t}const _=document.createElement("div");_.setAttribute("id","avatar-bg-container"),_.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),this.el.appendChild(_);const m=this.el.getAttribute("style");this.el.setAttribute("style",m?`position:relative;overflow:hidden;${m}`:"position:relative;overflow:hidden;"),this.resourceManager=new ResourceManager({sdkInstance:this,headers:t.headers,tag:t.tag,gateway_type:t.gateway_type||"default",asr_id:t.asr_id,llm_id:t.llm_id,session_speak_req_id:t.session_speak_req_id,sessionRequestData:s.sessionRequestData,appId:l,appSecret:h,gatewayServer:d,cacheServer:c,config:p,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo(e){r.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:t=>{var e,n;null==(e=(n=this.options).onStartSessionWarning)||e.call(n,t)}}),this.renderScheduler=new RenderScheduler({sdkInstance:this,container:this.el,resourceManager:this.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:this.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:t=>{var e,n,i,s;null==(e=this.onDownloadProgress)||e.call(this,t),null==(n=this.el)||n.setAttribute("style",(null==(i=this.el)?void 0:i.style.cssText)+`opacity:${100===t?"1":"0"};`),this.isInitialized=100===t,100===t&&(this.pendingInvisibleMode||this.status===AvatarStatus.online||this.status===AvatarStatus.invisible||this.onStatusChange(AvatarStatus.online),this.resourceManager._setOfflineCache(),null==(s=this.ttsa)||s.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(()=>{var t,e;null==(t=this.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.1.1",resolution:null==(e=this.resourceManager.getConfig())?void 0:e.resolution,download_speed:r.networkInfo.downlink||0}))},20),this.enableAudioPlaybackCapture())},onStateChange:e=>{this.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:(e,n)=>{null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&this.getStatus()!==AvatarStatus.online||!this.isInitialized||(window.avatarSDKLogger.log(this.TAG,"Status:===== 渲染中,状态: rendering",this.getSessionId()),this.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:(e,n,i)=>{null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,i)},onWalkStateChange:e=>{null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:t=>{var e;null==(e=this.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:(e,n)=>{null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:t=>{var e;null==(e=this.debugOverlay)||e.setAudioInfo(t)},setEventData:t=>{var e;null==(e=this.debugOverlay)||e.setEventData(t)},renderFrameCallback:t=>{this.renderFrameCallback(t),this.handleReplaySend(t)},reportMessage:t=>{this.onMessage(t)},sendSdkPoint:(t,e,n)=>{var i;null==(i=this.ttsa)||i.sendSdkPoint(t,e,n)},sendMessage:(t,e)=>{var n;null==(n=this.ttsa)||n.send(t,e)},onFPSUpdate:e=>{null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:e=>{null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=u&&u.walk_config&&this.changeWalkConfig(u.walk_config),null!=u&&u.layout&&this.changeLayout(u.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{}}initializeClient(t){const{containerId:e,container:n}=t;if(n&&n instanceof HTMLElement)this.el=n;else{const t=document.querySelector(e);var i,r;if(!t)return void(null==(i=(r=this.options).onMessage)||i.call(r,{code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${e} 不存在`}));this.el=t}const s=this.el.getAttribute("style");this.el.setAttribute("style",s?`position:relative;overflow:hidden;${s}`:"position:relative;overflow:hidden;"),this._eventDispatcher=new EventDispatcher({onStateChange:t.onStateChange,onSpeakStateChange:t.onSpeakStateChange,onVoiceStateChange:t.onVoiceStateChange,onStatusChange:t.onStatusChange,onRenderChange:t.onRenderChange,onWalkStateChange:t.onWalkStateChange,onWidgetEvent:t.onWidgetEvent,onMessage:t.onMessage,onNetworkInfo:t.onNetworkInfo,onFPSUpdate:t.onFPSUpdate,onFrameDataUpdate:t.onFrameDataUpdate,onDownloadProgress:t=>{var e;null==(e=this._clientOnDownloadProgress)||e.call(this,t),t>=100&&!this.isInitialized&&(this.isInitialized=!0)},onSessionId:t=>{this._clientSessionId=t,window.avatarSDKLogger.log(this.TAG,"[client] 收到 session_id:",t)}});const a=t.streamingServer||`ws://${location.hostname}:8080`;this._streamingClient=new StreamingClient({url:a,onReady:()=>{if(window.avatarSDKLogger.log(this.TAG,"[client] 双方就绪,等待 Server 推流..."),this._pendingInit){var t;this._pendingInit=!1;const e=this._pendingInitConfig;this._pendingInitConfig=null,window.avatarSDKLogger.log(this.TAG,"[client] 补发 init 命令"),null==(t=this._apiForwarder)||t.init(e)}},onOffer:t=>{var e;null==(e=this._videoPlayer)||e.handleOffer(t)},onIce:t=>{var e;null==(e=this._videoPlayer)||e.addIceCandidate(t)},onEventProxy:(t,e,n)=>{var i;null==(i=this._eventDispatcher)||i.dispatch(t,e,n)},onError:t=>{var e,n;null==(e=(n=this.options).onMessage)||e.call(n,{code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:()=>{window.avatarSDKLogger.log(this.TAG,"[client] WebRTC 已连接"),this.onStatusChange(AvatarStatus.online)},onDisconnected:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)}renderFrameCallback(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()}async init(t){const e=await checkCapability(this.options.audioOnlyMode);if(!e.supported){const t=`浏览器能力检查失败: ${e.items.filter(t=>"fatal"===t.severity&&!t.supported).map(t=>t.reason).join("; ")}`;return void this.onMessage({code:EErrorCode.INIT_ERROR,message:t})}if(this.destroyed=!1,this.isInitialized=!1,this.incompleteInitializationCleanupPromise=null,this.startConnectTime=Date.now(),this._isClientMode){var n;this._clientOnDownloadProgress=t.onDownloadProgress||null;const e={appId:this.options.appId,appSecret:this.options.appSecret,gatewayServer:this.options.gatewayServer,cacheServer:this.options.cacheServer,headers:this.options.headers,tag:this.options.tag,gateway_type:this.options.gateway_type,env:this.options.env,config:this.options.config,hardwareAcceleration:this.options.hardwareAcceleration,enableDebugger:this.options.enableDebugger,initModel:t.initModel,scaleDownBy:this.options.scaleDownBy||1,useAlphaMask:this.options.useAlphaMask};var i;return void(null!=(n=this._streamingClient)&&n.isConnected()?null==(i=this._apiForwarder)||i.init(e):(this._pendingInit=!0,this._pendingInitConfig=e,window.avatarSDKLogger.log(this.TAG,"[client] WebSocket 未连接,init 命令暂存")))}const{onDownloadProgress:r,initModel:s}=t;this.onDownloadProgress=t=>{15===t&&(this.sessionResTime=Date.now()),80===t&&(this.charbinResTime=Date.now()),r(t)},s===InitModel.invisible&&(this.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render);const a=await this.resourceManager.load(this.onDownloadProgress.bind(this));if(this.destroyed)window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after resourceManager load");else{if(null!=a&&a.socket_io_url&&null!=a&&a.token)return this.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),this.debugOverlay=new DebugOverlay(this,a),this.ttsa=this.connectTtsa(a),this.renderScheduler.init(),this.renderScheduler.setAvatarCanvasVisible(this.avatarCanvasVisible),window.performanceTracker.setReportFunc(this.ttsa),window.addEventListener("beforeunload",this.handleBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange),a;window.avatarSDKLogger.error(this.TAG,"init error, socket_io_url or token is empty reload")}}setAudioPlaybackDataHandler(t){this.options.onAudioPlaybackData=t}restartAudioPlaybackCapture(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)}enableAudioPlaybackCapture(){return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(()=>{this.captureSetupPromise=null}):this.setupAudioCapture().finally(()=>{this.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve();var t}async setupAudioCapture(){var t=this;const e=document.getElementById("xmov-avatar-audio");if(e&&this.options.onAudioPlaybackData&&!this.captureAudioCtx&&!this.captureSource)if(void 0!==window.AudioWorkletNode)try{var n;if(!await PcmWebMEncoder.isSupported())return void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"});if(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==this.captureAudioCtx.sampleRate)throw new Error(`浏览器无法创建 16000 Hz AudioContext: ${this.captureAudioCtx.sampleRate}`);this.captureSource=this.captureAudioCtx.createMediaElementSource(e),this.captureSource.connect(this.captureAudioCtx.destination);let i=!1,r=!0,s=0,a=0;const o=t=>{const e=++this.captureGeneration;i=!0,r=!0,s=Date.now()-100,a=0,this.captureLastSpeechId=t,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var t;e===this.captureGeneration&&(null==(t=this.pcmWebMEncoder)||t.reset())})},l=()=>{const t=++this.captureGeneration;i=!1,this.captureLastSpeechId=-2,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var e;t===this.captureGeneration&&(null==(e=this.pcmWebMEncoder)||e.reset())})};this.restartPlaybackCaptureImpl=()=>{i&&o(this.renderScheduler.getSpeechId())};const h=new Blob(["\n class AudioCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms @ 16kHz\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const input = inputs[0];\n if (input && input.length > 0 && input[0] && input[0].length > 0) {\n const frameCount = input[0].length;\n\n for (let i = 0; i < frameCount; i++) {\n let sample = 0;\n for (let channel = 0; channel < input.length; channel++) {\n sample += input[channel][i] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / input.length;\n\n // 缓冲区满 1600 采样点时,检测静音并发送到主线程\n if (this.bufferIndex >= 1600) {\n // 检测是否全是静音(全零或极低值)\n let hasAudio = false;\n for (let j = 0; j < 1600; j++) {\n if (Math.abs(this.buffer[j]) > 0.0001) {\n hasAudio = true;\n break;\n }\n }\n\n const pcm = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const value = Math.max(-1, Math.min(1, this.buffer[j]));\n pcm[j] = value < 0 ? value * 0x8000 : value * 0x7fff;\n }\n this.port.postMessage(\n { hasAudio: hasAudio, pcmData: pcm.buffer },\n [pcm.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n }\n return true;\n }\n }\n registerProcessor('audio-capture-processor', AudioCaptureProcessor);\n "],{type:"application/javascript"}),d=URL.createObjectURL(h);if(await this.captureAudioCtx.audioWorklet.addModule(d),URL.revokeObjectURL(d),this.captureWorklet=new AudioWorkletNode(this.captureAudioCtx,"audio-capture-processor"),this.captureSource.connect(this.captureWorklet),this.captureWorklet.connect(this.captureAudioCtx.destination),this.captureEncodeQueue=Promise.resolve(),this.captureWorklet.port.onmessage=e=>{if(!this.options.onAudioPlaybackData)return;const{hasAudio:n,pcmData:h}=e.data,d=this.renderScheduler.getSpeechId();if(n&&!i||n&&i&&d!==this.captureLastSpeechId?o(d):!n&&i&&l(),!(n&&i&&h instanceof ArrayBuffer))return;const c=this.captureGeneration,u=r;r=!1;const f=s+100*a;a+=1,this.captureEncodeQueue=this.captureEncodeQueue.then(async function(){var e;const n=await(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(h)));n&&0!==n.byteLength&&c===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:n,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:f,speech_id:d}))}).catch(t=>{var e;null==(e=window.avatarSDKLogger)||e.error(this.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",t)})},"suspended"===this.captureAudioCtx.state&&await this.captureAudioCtx.resume(),"running"!==this.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(n=window.avatarSDKLogger)||n.log(this.TAG,"[AudioCapture] 初始化成功,采样率:",this.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}catch(t){var i,r;if(this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}try{var s;null==(s=this.captureSource)||s.disconnect()}catch(t){}this.captureSource=null,this.captureAudioCtx&&"closed"!==this.captureAudioCtx.state&&await this.captureAudioCtx.close().catch(()=>{}),this.captureAudioCtx=null,null==(i=this.pcmWebMEncoder)||i.destroy(),this.pcmWebMEncoder=null,null==(r=window.avatarSDKLogger)||r.error(this.TAG,"[AudioCapture] 初始化失败:",t)}else this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"})}async setupPCMCapture(){var t,e=this;if(!this.options.onAudioPlaybackData)return;const n=null==(t=this.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();var i;if(!n)return void(null==(i=window.avatarSDKLogger)||i.error(this.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"));const r=await PcmWebMEncoder.isSupported(),s=MediaRecorderEncoder.isSupported();var a;if(!r&&!s)return null==(a=window.avatarSDKLogger)||a.warn(this.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});try{var o;r?(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.pcmCaptureMode="webcodec"):(this.mediaRecorderEncoder=new MediaRecorderEncoder,await this.mediaRecorderEncoder.init(),this.pcmCaptureMode="mediarecorder"),this.restartPlaybackCaptureImpl=()=>{var t,e;this.pcmCaptureFirstChunk=!0,this.pcmCaptureLastSpeechId=this.renderScheduler.getSpeechId(),this.pcmEncodeId++,null==(t=this.pcmWebMEncoder)||t.reset(),null==(e=this.mediaRecorderEncoder)||e.reset(),n.resetCaptureBuffer()},await n.attachCapture(async function({pcmData:t,hasAudio:i}){try{if(!e.options.onAudioPlaybackData)return;const d=Date.now()-100;if(!n.isPlaying)return void n.resetCaptureBuffer();const c=e.renderScheduler.getSpeechId();var r,s;if(c!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=c,e.pcmEncodeId++,null==(r=e.pcmWebMEncoder)||r.reset(),null==(s=e.mediaRecorderEncoder)||s.reset(),n.resetCaptureBuffer()),!i)return;const u=e.pcmEncodeId;let f=null;const p=performance.now();if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){const n=new Int16Array(t);var a;if(f=await e.pcmWebMEncoder.encode(n),u!==e.pcmEncodeId)return void(null==(a=window.avatarSDKLogger)||a.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(0===f.byteLength)return;const i=performance.now()-p;var o;i>10&&(null==(o=window.avatarSDKLogger)||o.warn(e.TAG,`[PCMCapture] WebCodecs 编码耗时过长: ${i.toFixed(2)}ms`))}else if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder){var l;if(f=await e.mediaRecorderEncoder.feedPCM(t),u!==e.pcmEncodeId)return void(null==(l=window.avatarSDKLogger)||l.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(!f)return;const n=performance.now()-p;var h;n>10&&(null==(h=window.avatarSDKLogger)||h.warn(e.TAG,`[PCMCapture] MediaRecorder 编码耗时过长: ${n.toFixed(2)}ms`))}if(!f)return;const _=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:f,codec:"opus",isFirstChunk:_,sampleRate:16e3,samples:1600,timestamp:d,speech_id:c})}catch(t){var d;null==(d=window.avatarSDKLogger)||d.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}}),null==(o=window.avatarSDKLogger)||o.log(this.TAG,`[PCMCapture] PCM 捕获初始化成功,编码路径: ${this.pcmCaptureMode}`)}catch(t){var l,h,d;null==(l=window.avatarSDKLogger)||l.error(this.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(h=this.pcmWebMEncoder)||h.destroy(),this.pcmWebMEncoder=null,null==(d=this.mediaRecorderEncoder)||d.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureMode="none"}}visibilitychange(){if(document.hidden){var t;const i=null==(t=this.renderScheduler)?void 0:t.getRenderState();var e,n;i===RenderState.rendering||i===RenderState.resumed?null==(e=this.renderScheduler)||e.pauseRender():null==(n=this.renderScheduler)||n.pauseForBackground()}else{var i,r,s,a;if((null==(i=this.renderScheduler)?void 0:i.getRenderState())===RenderState.paused)null==(a=this.renderScheduler)||a.resumeRender();else if(null!=(r=this.ttsa)&&r.getStatus()){var o;null==(o=this.renderScheduler)||o.forceSyncDecoder()}null!=(s=this.ttsa)&&s.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode()),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(()=>{})}}setReplayData(t){this.replayData=t}handleReplaySend(t){if(!this.replayData)return;const e=this.replayData.filter(e=>Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type);for(const t of e){var n;"state_change"===t.event_type?null==(n=this.ttsa)||n.stateChange(t.event_data.state,t.event_data.params):"send_text"===t.event_type?this.speak(t.event_data.ssml,t.event_data.is_start,t.event_data.is_end,t.event_data.extra):window.avatarSDKLogger.log(this.TAG,`[handleReplaySend] 未知事件类型: ${t}`)}}connectTtsa(t){return window.performanceTracker.markStart(performanceConstant.ttsa_connect),window.performanceTracker.markStart(performanceConstant.ttsa_ready),new Ttsa({sdkInstance:this,url:t.socket_io_url,room:t.room,session_id:t.session_id,token:t.token,framedata_proto_version:this.resourceManager.getConfig().framedata_proto_version,reconnect_client_timeout:(null==t?void 0:t.reconnect_client_timeout)||0,reconnect_timeout:(null==t?void 0:t.reconnect_timeout)||0,appInfo:_extends({},this.resourceManager.getAppInfo(),{env:this._env}),onReady:()=>{var e,n,i,r,s,a;null==(e=this.ttsa)||e.sendSdkPoint("connect_sdk",{timestamp:this.startConnectTime}),null==(n=this.ttsa)||n.sendSdkPoint("connect_sdk_success",{timestamp:this.connectSuccessTime}),null==(i=this.ttsa)||i.sendSdkPoint("session_processing_time",{timestamp:this.sessionResTime}),null==(r=this.ttsa)||r.sendSdkPoint("Char_bin_download_time",{timestamp:this.charbinResTime}),null==(s=this.ttsa)||s.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),this.onTtsaReady(t),null==(a=this.ttsa)||a.syncTimestamp()},handleMessage:(t,e)=>{var n;this.isfirstReceive&&t===EFrameDataType.BODY&&(null==(n=this.ttsa)||n.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),this.isfirstReceive=!1),this.renderScheduler.handleData(t,e)},handleAAFrame:t=>{var e,n;null==(e=(n=this.options).onAAFrameHandle)||e.call(n,t)},runStartFrameIndex:t=>{this.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:t=>{this.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:()=>{this.reloadSuccess()},enterOfflineMode:()=>{this.offlineHandle()},reStartSDK:()=>{this.reStartSession()},sendVoiceEnd:()=>{var t;null==(t=this.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:()=>{var t,e;return null!=(t=null==(e=this.renderScheduler)?void 0:e.getCurrentFrameIndex())?t:0}})}start(){var t;this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online),this.renderScheduler.render(),null==(t=this.ttsa)||t.start()}onTtsaReady(t){this.start()}async _reload(){const t=await this.resourceManager._reload();if(t&&!this.destroyed){if(await this.onSessionReloaded(t),this.destroyed)return null;this.ttsa=this.connectTtsa(t),this.ttsa._setResumeInfoCallback(this.resourceManager._getSessionId(),this.renderScheduler._getResumeInfo.bind(this.renderScheduler))}return t}async onSessionReloaded(t){}onSessionReloadExhausted(t){}async restartSessionForTransport(t){var e;this.renderScheduler.interrupt("in_offline_mode"),await this.resourceManager.stopSession(t),this.destroyed||(null==(e=this.ttsa)||e.close(),this.status!==AvatarStatus.offline&&this.offlineHandle(),this.reStartSession())}cancelSessionRestart(){this.resetRetryState(),this.clearAllRetryTimers()}reloadSuccess(){var t;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(()=>{window.clearInterval(this._offlineTimer)},1e3)}async stop(){await this.renderScheduler.stop()}isDestroyed(){return this.destroyed}async destroyClient(){var t,e,n;if(this.destroyed)return void window.avatarSDKLogger.warn(this.TAG,"SDK 已销毁,忽略重复销毁请求");if(this.destroyed=!0,this._isClientMode)return this._streamingClient&&(this._streamingClient.destroy(),this._streamingClient=null),this._videoPlayer&&(this._videoPlayer.destroy(),this._videoPlayer=null),this._eventDispatcher=null,this._apiForwarder=null,this.el=null,window.removeEventListener("beforeunload",this.handleBeforeUnload),void window.avatarSDKLogger.log(this.TAG,"薄客户端 SDK 已销毁");if(this.cancelSessionRestart(),-1!==this._offlineTimer&&(clearInterval(this._offlineTimer),this._offlineTimer=-1),this.ttsa&&(this.ttsa.close(),this.ttsa=null),this.renderScheduler&&this.renderScheduler.destroy(),this.resourceManager&&this.resourceManager.destroy(),this.debugOverlay&&(this.debugOverlay.destroy(),this.debugOverlay=null),this.networkMonitor)try{this.networkMonitor.destroy(),this.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(this.TAG,"销毁 networkMonitor 时出错",t)}if(this.pcmEncodeId++,this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}if(this.captureSource){try{this.captureSource.disconnect()}catch(t){}this.captureSource=null}if(this.captureAudioCtx){try{this.captureAudioCtx.close()}catch(t){}this.captureAudioCtx=null}const i=null==(t=this.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();i&&i.detachCapture(),null==(e=this.pcmWebMEncoder)||e.destroy(),this.pcmWebMEncoder=null,null==(n=this.mediaRecorderEncoder)||n.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmCaptureMode="none",this.el=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",this.handleBeforeUnload),document.removeEventListener("visibilitychange",this.boundVisibilityChange),window.avatarSDKLogger.log(this.TAG,"SDK 已销毁")}async destroy(t="user"){var e,n;if(this.replayData=null,this._isClientMode)return null==(n=this._apiForwarder)||n.destroy(t),await this.destroyClient(),void this.onStatusChange(AvatarStatus.close);null==(e=this.ttsa)||e.sendSdkPoint("close_session",{reason:t});const i=await this.resourceManager.stopSession(t);return await this.destroyClient(),i&&this.onStatusChange(AvatarStatus.close),i}idle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())}listen(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())}think(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())}interactiveidle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())}speak(t,e=!0,n=!0,i={client_speak_id:"",client_frame:0}){var r,s,a,o;if(this._isClientMode)return void(null==(o=this._apiForwarder)||o.speak(t,e,n,i));this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),i.client_frame=null!=(r=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?r:0;const l=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,i);return this.renderScheduler.resume(),l}setOffsetFrame(t){this.renderScheduler.setOffsetFrame(t)}syncTimestamp(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)}notifyEnterInvisibleMode(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()}notifyExitInvisibleMode(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()}setVolume(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)}getSessionId(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id}showDebugInfo(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())}hideDebugInfo(){var t;null==(t=this.debugOverlay)||t.hide()}changeAvatarVisible(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)}cleanupBeforeInitComplete(t){var e,n=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,`清理初始化未完成的资源,原因: ${t}`),this.isInitialized=!1;const i=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==i||i.catch(t=>{window.avatarSDKLogger.warn(this.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=async function(){try{await i,await n.destroyClient()}catch(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)}}(),this.incompleteInitializationCleanupPromise}reportInitializationFailure(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e})}offlineHandle(){this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(()=>{if(this.status!==AvatarStatus.offline)return clearInterval(this._offlineTimer),void(this._offlineTimer=-1);this.renderScheduler._offlineRun()},this._offlineInterval)}async stopSessionFromSocket(t){await this.resourceManager.stopSession(t)}offlineMode(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()}onlineMode(){NetworkMonitor.ONLINE&&this._reload()}onMessage(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(i){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",i)}const i=Errors(t);t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&this.options.onMessage(i),null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(i)}onStatusChange(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))}switchInvisibleMode(){var t,e;this._isClientMode?null==(t=this._apiForwarder)||t.switchInvisibleMode():this.renderScheduler?this.status===AvatarStatus.visible||this.status===AvatarStatus.online?this.setInvisibleMode():(this.notifyExitInvisibleMode(),this.renderScheduler.switchInvisibleMode(),this.listen()):null==(e=window.avatarSDKLogger)||e.warn(this.TAG,"RenderScheduler 未初始化,无法切换隐身模式")}setInvisibleMode(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)}getPendingInvisibleMode(){return this.pendingInvisibleMode||!1}getRenderState(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init}changeLayout(t){var e,n;if(this._isClientMode)return void(null==(n=this._apiForwarder)||n.changeLayout(t));const{scale:i=1}=t.avatar||{};t.avatar.scale=validateScaleWithDecimal(i,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}changeWalkConfig(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))}interrupt(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)}triggerReconnect(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()}reStartSession(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())}async _retryImpl(){var t=this;if(this.retryRound>this.maxRetryRound||!this.isRetrying)return;let e=1e3;this.retryCount>1&&(e=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(async function(){if(t.retryTimer=-1,t.isRetrying&&!t.destroyed)try{const e=await t._reload();if(!t.isRetrying||t.destroyed)return;if(null===e){if(t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试达最大轮次(${t.maxRetryRound})+每轮最大次数(${t.maxRetryCount}),总次数=${t.maxRetryRound*t.maxRetryCount},停止重试`),t.onSessionReloadExhausted(),void t.resetRetryState();window.avatarSDKLogger.warn(t.TAG,`第${t.retryRound}轮重试次数达上限(${t.maxRetryCount}),进入第${t.retryRound+1}轮重试`),t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t._retryImpl()}else t.renderScheduler.stopAudio(-1),window.avatarSDKLogger.log(t.TAG,`第${t.retryRound}轮第${t.retryCount}次重试成功,停止重试`),t.resetRetryState()}catch(e){if(window.avatarSDKLogger.error(t.TAG,"重试过程异常",e),t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试异常且达总次数上限(${t.maxRetryRound*t.maxRetryCount}),停止重试`),t.onSessionReloadExhausted(e),void t.resetRetryState();t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t.retryRound<=t.maxRetryRound&&t.isRetrying?t._retryImpl():t.resetRetryState()}},e)}clearAllRetryTimers(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)}resetRetryState(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1}seekToFrame(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)}async startRecoder(){try{var t,e;const n=null==(t=this.el)?void 0:t.querySelector("canvas"),i=null==(e=this.el)?void 0:e.querySelector("audio");if(!n||!i)return void console.error("找不到 canvas 或 audio 元素");const r=n.captureStream(60);let s=[];if(this.captureSource&&this.captureAudioCtx){const t=this.captureAudioCtx.createMediaStreamDestination();this.captureSource.connect(t),s=t.stream.getAudioTracks()}else if("function"==typeof i.captureStream)s=i.captureStream().getAudioTracks();else{if("function"!=typeof i.mozCaptureStream)return void window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频");s=i.mozCaptureStream().getAudioTracks()}this.stream=new MediaStream([...r.getVideoTracks(),...s]),this.recordedChunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),this.mediaRecorder.ondataavailable=t=>{t.data&&t.data.size>0&&this.recordedChunks.push(t.data)},this.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}}stopRecoder(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(t=>t.stop()),window.avatarSDKLogger.log("⏹ 停止录制"))}exportVideo(){if(!this.recordedChunks.length)return void window.avatarSDKLogger.error("没有录制到数据");const t=new Blob(this.recordedChunks,{type:"video/mp4"}),e=URL.createObjectURL(t),n=document.createElement("a");n.href=e,n.download=`录制_${(new Date).getTime()}.mp4`,n.click(),window.avatarSDKLogger.log("✅ 下载成功,大小:",t.size)}getOptions(){return this.options}simulateContextLoss(t=5e3,e=!1){this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}getRecoveryStatus(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null}async testStagedRecovery(){if(this.renderScheduler)return this.renderScheduler.testStagedRecovery();window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}restartWebGL(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)}}XmovAvatar.IBRAnimationGeneratorCharInfo_NN=IBRAnimationGeneratorCharInfo_NN,XmovAvatar.unpackIBRAnimation=unpackIBRAnimation,XmovAvatar.formatMJT=formatMJT,XmovAvatar.getVertices=getVertices,XmovAvatar.getPCATextures=getPCATextures,XmovAvatar.getWavefrontObjFromVertices=getWavefrontObjFromVertices,XmovAvatar.GLDevice=GLDevice,XmovAvatar.GLPipeline=GLPipeline,XmovAvatar.checkCapability=checkCapability;export{XmovAvatar as default};
2
2
  //# sourceMappingURL=index.modern.js.map