@xmov/avatar 2.0.0-beta.16 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.modern.js +1 -1
- package/dist/index.modern.js.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/utils/capability-checker.ts +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function _defineProperties(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,_toPropertyKey(r.key),r)}}function _createClass(t,e,n){return e&&_defineProperties(t.prototype,e),n&&_defineProperties(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function _createForOfIteratorHelperLoose(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=_unsupportedIterableToArray(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}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 r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_extends.apply(null,arguments)}function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPrimitive(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return"symbol"==typeof e?e:e+""}function _unsupportedIterableToArray(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(t,e):void 0}}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={}));var 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"},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={}));var FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk",DataCacheQueue=/*#__PURE__*/function(){function t(){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}var e=t.prototype;return e._updateBodyImageBitmap=function(t){var e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(var n,r=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(n=r()).done;){var i=n.value,s=i[0],a=i[1];a.body_id<t.body_id&&a.frameIndex>=t.frameIndex&&(a.frame.close(),this._bodyQueue.delete(s))}this._bodyQueue.set(t.frameIndex,t)},e.clearOldFrames=function(t){for(var e,n=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(e=n()).done;){var r=e.value,i=r[0];i>=t&&(r[1].frame.close(),this._bodyQueue.delete(i))}},e.clearOldFaceData=function(t){this._facialQueue=this._facialQueue.filter(function(e){return e.frameIndex>=t}),this._realFacialQueue=this._realFacialQueue.filter(function(e){return e.frameIndex>=t})},e.setVideoIdList=function(t){this.videoIdList.includes(t)||this.videoIdList.push(t)},e.getVideoIdList=function(){return this.videoIdList},e._getBodyImageBitmap=function(t){for(var e,n=this._bodyQueue.get(t),r=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(e=r()).done;){var i=e.value,s=i[0];s<t&&(i[1].frame.close(),this._bodyQueue.delete(s))}if(n)return n},e.getBodyVideoNameListLength=function(){var t=[];return this.bodyQueue.forEach(function(e){t.includes(e.name)||t.push(e.name)}),t.length},e._getFaceImageBitmap=function(t,e){for(var n=null,r=this._facialQueue.length-1;r>=0;r--){var i=this._facialQueue[r];if(i.frameIndex===t&&i.body_id===e){n=i;break}}return this._facialQueue=this._facialQueue.filter(function(e){return e.frameIndex>=t}),n},e._updateFacial=function(t){var e;(e=this._facialQueue).push.apply(e,t)},e._getRealFaceImageBitmap=function(t,e){for(var n=null,r=this._realFacialQueue.length-1;r>=0;r--){var i=this._realFacialQueue[r];if((null==i?void 0:i.frameIndex)===t&&(null==i?void 0:i.body_id)===e){n=i;break}}return this._realFacialQueue=this._realFacialQueue.filter(function(e){return(null==e?void 0:e.frameIndex)>=t}),n},e._updateRealFacial=function(t){var e;(e=this._realFacialQueue).push.apply(e,t)},e.clearAllFaceData=function(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")},e._updateAudio=function(t){var e;(e=this.audioQueue).push.apply(e,t)},e._clearAudio=function(t){this.audioQueue=-1!==t?this.audioQueue.filter(function(e){return e.sid!==t}):[]},e._getAudio=function(t){var e=this.audioQueue.findIndex(function(e){return e.sf===t});if(-1!==e)return this.audioQueue.splice(e,1)[0]},e._getAudioInterval=function(t,e){var n=this.audioQueue.filter(function(n){return n.sf>=t&&n.sf<=e});if(0!==n.length){var r=n[n.length-1],i=this.audioQueue.findIndex(function(t){return t.id===r.id});return this.audioQueue.splice(i,1),r}},e._updateUiEvent=function(t){var e;(e=this.eventQueue).push.apply(e,t)},e.clearOldEvent=function(t){this.eventQueue=this.eventQueue.filter(function(e){return e.sf>=t})},e.clearSubtitleOn=function(t){this.eventQueue=this.eventQueue.map(function(e){var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(function(e){return e.speech_id>t||"subtitle_on"!==e.type})})})},e._clearEvent=function(){this.eventQueue=[]},e._getEvent=function(t){var e=this.eventQueue.filter(function(e){return e.sf===t});if(0!==e.length)return this.eventQueue=this.eventQueue.filter(function(e){return e.sf!==t}),this._mergeEventsBySf(e)},e._getEventInterval=function(t,e){var n=this.eventQueue.filter(function(n){return n.sf>=t&&n.sf<=e});if(0!==n.length)return this.eventQueue=this.eventQueue.filter(function(n){return!(n.sf>=t&&n.sf<=e)}),this._mergeEventsBySf(n)},e._mergeEventsBySf=function(t){for(var e,n={},r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var i,s=e.value,a=s.sf;n[a]||(n[a]=_extends({},s,{e:[]})),(i=n[a].e).push.apply(i,s.e)}var o=Object.values(n);if(0===o.length)return null;if(o.length>1){var l=[];return o.forEach(function(t){return l.push.apply(l,t.e)}),_extends({},o[0],{mergeFrameFlag:1,e:l})}return o[0]},e.checkValidData=function(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,r;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==(r=this.audioQueue[0])?void 0:r.sf)){var i=this.audioQueue.findIndex(function(e){return e.sf>=t[0].sf});-1!==i&&(this.audioQueue.length=i)}}},e.destroy=function(){this._bodyQueue.forEach(function(t){t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]},_createClass(t,[{key:"currentPlayState",get:function(){return this._currentPlayState},set:function(t){this._currentPlayState=t}},{key:"currentTtsaState",get:function(){return this._currentTtsaState},set:function(t){this._currentTtsaState=t}},{key:"bodyQueue",get:function(){return Array.from(this._bodyQueue.values())}},{key:"facialQueue",get:function(){return this._facialQueue}},{key:"realFacialQueue",get:function(){return this._realFacialQueue}}])}(),GLDevice=/*#__PURE__*/function(){function t(t){var e=this;this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;var n=function(){var t=e.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");e.gl=t,e._lost_context_sim=e.gl.getExtension("WEBGL_lose_context"),e.shaderStage={vertex:e.gl.VERTEX_SHADER,fragment:e.gl.FRAGMENT_SHADER},e._ElementTypeMap_JS2GL={Uint8Array:e.gl.UNSIGNED_BYTE,Uint8ClampedArray:e.gl.UNSIGNED_BYTE,Int8Array:e.gl.BYTE,Uint16Array:e.gl.UNSIGNED_SHORT,Int16Array:e.gl.SHORT,Uint32Array:e.gl.UNSIGNED_INT,Int32Array:e.gl.INT,Float16Array:e.gl.HALF_FLOAT,Float32Array:e.gl.FLOAT};var n=[[e.gl.UNSIGNED_BYTE,[[e.gl.RED,e.gl.R8],[e.gl.RED_INTEGER,e.gl.R8UI],[e.gl.RG,e.gl.RG8],[e.gl.RG_INTEGER,e.gl.RG8UI],[e.gl.RGB,e.gl.RGB8],[e.gl.RGB_INTEGER,e.gl.RGB8UI],[e.gl.RGBA,e.gl.RGBA8],[e.gl.RGBA_INTEGER,e.gl.RGBA8UI]]],[e.gl.BYTE,[[e.gl.RED,e.gl.R8_SNORM],[e.gl.RED_INTEGER,e.gl.R8I],[e.gl.RG,e.gl.RG8_SNORM],[e.gl.RG_INTEGER,e.gl.RG8I],[e.gl.RGB,e.gl.RGB8_SNORM],[e.gl.RGB_INTEGER,e.gl.RGB8I],[e.gl.RGBA,e.gl.RGBA8_SNORM],[e.gl.RGBA_INTEGER,e.gl.RGBA8I]]],[e.gl.UNSIGNED_SHORT,[[e.gl.RED_INTEGER,e.gl.R16UI],[e.gl.RG_INTEGER,e.gl.RG16UI],[e.gl.RGB_INTEGER,e.gl.RGB16UI],[e.gl.RGBA_INTEGER,e.gl.RGBA16UI],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT16]]],[e.gl.SHORT,[[e.gl.RED_INTEGER,e.gl.R16I],[e.gl.RG_INTEGER,e.gl.RG16I],[e.gl.RGB_INTEGER,e.gl.RGB16I],[e.gl.RGBA_INTEGER,e.gl.RGBA16I]]],[e.gl.UNSIGNED_INT,[[e.gl.RED_INTEGER,e.gl.R32UI],[e.gl.RG_INTEGER,e.gl.RG32UI],[e.gl.RGB_INTEGER,e.gl.RGB32UI],[e.gl.RGBA_INTEGER,e.gl.RGBA32UI],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT24]]],[e.gl.INT,[[e.gl.RED_INTEGER,e.gl.R32I],[e.gl.RG_INTEGER,e.gl.RG32I],[e.gl.RGB_INTEGER,e.gl.RGB32I],[e.gl.RGBA_INTEGER,e.gl.RGBA32I]]],[e.gl.HALF_FLOAT,[[e.gl.RED,e.gl.R16F],[e.gl.RG,e.gl.RG16F],[e.gl.RGB,e.gl.RGB16F],[e.gl.RGBA,e.gl.RGBA16F]]],[e.gl.FLOAT,[[e.gl.RED,e.gl.R32F],[e.gl.RG,e.gl.RG32F],[e.gl.RGB,e.gl.RGB32F],[e.gl.RGBA,e.gl.RGBA32F],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT32F]]],[e.gl.UNSIGNED_SHORT_5_6_5,[[e.gl.RGB,e.gl.RGB565]]],[e.gl.UNSIGNED_SHORT_4_4_4_4,[[e.gl.RGBA,e.gl.RGBA4]]],[e.gl.UNSIGNED_SHORT_5_5_5_1,[[e.gl.RGBA,e.gl.RGB5_A1]]],[e.gl.UNSIGNED_INT_2_10_10_10_REV,[[e.gl.RGBA,e.gl.RGB10_A2]]],[e.gl.UNSIGNED_INT_10F_11F_11F_REV,[[e.gl.RGB,e.gl.R11F_G11F_B10F]]],[e.gl.UNSIGNED_INT_5_9_9_9_REV,[[e.gl.RGB,e.gl.RGB9_E5]]],[e.gl.UNSIGNED_INT_24_8,[[e.gl.DEPTH_STENCIL,e.gl.DEPTH24_STENCIL8]]],[e.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[e.gl.DEPTH_STENCIL,e.gl.DEPTH32F_STENCIL8]]]];e._FormatTypeMap_Ext2Int=new Map;for(var r=0,i=n;r<i.length;r++){for(var s,a=i[r],o=a[0],l=a[1],h=new Map,c=_createForOfIteratorHelperLoose(l);!(s=c()).done;){var d=s.value;h.set(d[0],d[1])}e._FormatTypeMap_Ext2Int.set(o,h)}var u={GL_RED:e.gl.RED,GL_RED_INTEGER:e.gl.RED_INTEGER,GL_RG:e.gl.RG,GL_RG_INTEGER:e.gl.RG_INTEGER,GL_RGB:e.gl.RGB,GL_RGB_INTEGER:e.gl.RGB_INTEGER,GL_RGBA:e.gl.RGBA,GL_RGBA_INTEGER:e.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:e.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:e.gl.DEPTH_STENCIL};e._FormatTypeMap_Ext2Str=new Map;for(var f=0,p=Object.entries(u);f<p.length;f++){var m=p[f];e._FormatTypeMap_Ext2Str.set(m[1],m[0])}};this.frameID=null,this.cbRender=function(){},this._onContextLost=function(t){t.preventDefault(),e.stop()},this._onContextRestored=n,this._onContextCreationError=function(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),n()}var e=t.prototype;return e.compileShaderProgram=function(t){var e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(var n=0,r=Object.entries(t);n<r.length;n++){var i=r[n],s=i[1],a=this.gl.createShader(this.shaderStage[i[0]]);if(!a)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(a,s),this.gl.compileShader(a),!this.gl.getShaderParameter(a,this.gl.COMPILE_STATUS)){var o=this.gl.getShaderInfoLog(a);throw this.gl.deleteShader(a),new Error("WebGL shader compile failed:"+o)}this.gl.attachShader(e,a)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){var l=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+l)}return e},e.getShaderProgramUniformLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getUniformLocation(t,s)}return r},e.getShaderProgramUniformBlockLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getUniformBlockIndex(t,s)}return r},e.getShaderProgramAttribLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getAttribLocation(t,s)}return r},e.getGLArrayElementType=function(t){var e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null},e.getGLTexInternalFormat=function(t,e){var n=this._FormatTypeMap_Ext2Int.get(e);if(n){var r=n.get(t);if(r)return r}return null},e.texImage2D=function(t,e,n,r,i,s){var a,o=this.getGLArrayElementType(s);if(!o)throw new Error("Unsupported data format: "+s[Symbol.toStringTag]);var l=this.getGLTexInternalFormat(i,o);if(!l)throw new Error("No available internal format for "+s[Symbol.toStringTag]+" and "+(null!=(a=this._FormatTypeMap_Ext2Str.get(i))?a:"unknown")+".");this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,r,0,i,o,s)},e.texImage3D=function(t,e,n,r,i,s,a){var o,l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);var 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,r,i,0,s,l,a)},e.run=function(t,e){var n=this;if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;var r=function(t,i){n.running&&(n.syncMediaTime=i.mediaTime,n.cbRender(n),n.frameID=e.requestVideoFrameCallback(r))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(r)}else{var i=function(){n.running&&(n.cbRender(n),n.frameID=requestAnimationFrame(i))};i()}},e.refresh=function(){this.cbRender(this)},e.getSyncMediaTime=function(){return this.syncMediaTime},e.stop=function(){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},e.simulateContextFault=function(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())},e.captureFrame=function(){var 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}},e.destroy=function(){if(!this._isDestroyed&&this.gl){var t=this.gl;try{var 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){var n=this.canvas.getContext("2d");n&&n.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}}},t}(),_performanceText;function length(t){return Math.sqrt(t.reduce(function(t,e){return t+e*e},0))}function normalize(t){var e=length(t);return t.map(function(t){return t/e})}function mvmul(t,e){for(var n=t.length,r=e.length,i=Array(n),s=0;s<n;s++){i[s]=0;for(var a=0;a<r;a++)i[s]+=t[s][a]*e[a]}return i}function mmul(t,e){for(var n=t.length,r=e.length,i=e[0].length,s=Array(n),a=0;a<n;a++){for(var o=Array(i),l=0;l<i;l++){o[l]=0;for(var h=0;h<r;h++)o[l]+=t[a][h]*e[h][l]}s[a]=o}return s}function transpose(t){for(var e=t.length,n=t[0].length,r=Array(n),i=0;i<n;i++){for(var s=Array(e),a=0;a<e;a++)s[a]=t[a][i];r[i]=s}return r}function identity(t){for(var e=Array(t),n=0;n<t;n++){for(var r=Array(t),i=0;i<t;i++)r[i]=n==i?1:0;e[n]=r}return e}function det3(t){var 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])-t[0][0]*t[1][2]*t[2][1]}function inv3(t){var 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){for(var e=[[].concat(t[0]),[].concat(t[1]),[].concat(t[2]),[].concat(t[3])],n=[0,0,0,0],r=[0,0,0,0],i=0,s=0;s<4;s++){for(var a=0,o=s;o<4;o++)for(var l=s;l<4;l++)Math.abs(e[o][l])>a&&(a=Math.abs(e[o][l]),n[s]=o,r[s]=l);if(a<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[s]!=s)for(var h=0;h<4;h++)i=e[s][h],e[s][h]=e[n[s]][h],e[n[s]][h]=i;if(r[s]!=s)for(var c=0;c<4;c++)i=e[c][s],e[c][s]=e[c][r[s]],e[c][r[s]]=i;e[s][s]=1/e[s][s];for(var d=0;d<4;d++)d!=s&&(e[s][d]*=e[s][s]);for(var u=0;u<4;u++)if(u!=s)for(var f=0;f<4;f++)f!=s&&(e[u][f]-=e[u][s]*e[s][f]);for(var p=0;p<4;p++)p!=s&&(e[p][s]*=-e[s][s])}for(var m=3;m>=0;m--){if(r[m]!=m)for(var _=0;_<4;_++)i=e[m][_],e[m][_]=e[r[m]][_],e[r[m]][_]=i;if(n[m]!=m)for(var g=0;g<4;g++)i=e[g][m],e[g][m]=e[g][n[m]],e[g][n[m]]=i}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){var e=t[0],n=t[1],r=t[2],i=t[3];return[[e*e+n*n-r*r-i*i,2*(n*r-i*e),2*(n*i+r*e)],[2*(n*r+i*e),e*e-n*n+r*r-i*i,2*(r*i-n*e)],[2*(n*i-r*e),2*(r*i+n*e),e*e-n*n-r*r+i*i]]}function GivensTransform(t,e,n,r){for(var i=Math.sin(r),s=Math.cos(r),a=t[0].length,o=0;o<a;o++){var l=i*t[e][o]+s*t[n][o];t[e][o]=s*t[e][o]-i*t[n][o],t[n][o]=l}}function Euler_to_mat(t,e){void 0===e&&(e="xyz");var 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){for(var e=t.length,n=t[0].length,r=Array(e*n),i=0;i<e;i++)for(var s=0;s<n;s++)r[i*n+s]=t[i][s];return r}var 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"};_performanceText={},_performanceText[performanceConstant.load_resource]="加载资源",_performanceText[performanceConstant.ttsa_connect]="ttsa连接",_performanceText[performanceConstant.ttsa_ready]="ttsa准备返回first_start_timestamp",_performanceText[performanceConstant.first_avatar_render]="前端处理好第一帧渲染数据",_performanceText[performanceConstant.first_webgl_render]="前端处理好第一帧webgl渲染",_performanceText[performanceConstant.ttsa_body_res]="ttsa返回body",_performanceText[performanceConstant.start_action_res]="触发行为返回",_performanceText[performanceConstant.start_action_render]="触发行为并渲染耗时",_performanceText[performanceConstant.load_video]="视频加载",_performanceText[performanceConstant.decode_video]="视频解码",_performanceText[performanceConstant.voice_response_play]="speak音频响应",_performanceText[performanceConstant.first_decode_video]="第一帧视频解码",_performanceText[performanceConstant.first_render]="第一帧webgl渲染";var PerformanceTracker=/*#__PURE__*/function(){function t(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=function(){},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}var e=t.prototype;return e.getFirstInfo=function(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}},e.markStart=function(t,e){this.marks.set(t,{state:e,time:performance.now()})},e.markEnd=function(t,e){var n=this.marks.get(t);if(n&&(!e||"string"!=typeof e||e===(null==n?void 0:n.state))){var r=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:r}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,r),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=r),t===performanceConstant.first_render&&(this.firstRenderTime=r),r}},e.getAllMetrics=function(){return Object.fromEntries(this.measures.entries())},e.getVideoMetrics=function(){var t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(function(t){return[performanceConstant.decode_video,performanceConstant.load_video].includes(t[0])}))},e.setReportFunc=function(t){this.reportFunc=t},e.reportMetric=function(){var t,e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){var n,r=Object.fromEntries(Object.entries(e).filter(function(t){return![performanceConstant.load_video,performanceConstant.decode_video].includes(t[0])}));for(var i in Object.keys(r).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(r)),r)i!==performanceConstant.decode_video&&i!==performanceConstant.load_video&&this.measures.delete(i)}},e.setOnStateRenderChange=function(t){this.onStateRenderChange=t},t}();window.performanceTracker=new PerformanceTracker;var 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"}}var 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"],GLPipeline=/*#__PURE__*/function(){function t(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=function(){return 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=function(){},this.device=t,this.sendSdkPoint=e,this.reinitialize()}var e=t.prototype;return e.assembleBackgroundPipeline=function(){this._ub_shadow_fx_data=new Float32Array(32);var 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);var r=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r),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);var i={};i.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.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=i,this.device.gl.bindVertexArray(null);var 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},e.assembleMeshPipelines=function(t){if(t.char){for(var e=t.char,n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)},r=0;r<e.mesh.length;r++){for(var i,s=0,a=_createForOfIteratorHelperLoose(e.mesh[r].textureModels);!(i=a()).done;){var o=i.value.data.size[0]+3;o-=o%4,s=Math.max(s,o)}n.max_pca_component_count=Math.max(n.max_pca_component_count,s);var l=e.mesh[r].blendshapes.size[2]+3;l-=l%4,n.max_bs_count=Math.max(n.max_bs_count,l)}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);var h=generateMeshPipelineShader(this.meshStatistics),c=this.device.compileShaderProgram({vertex:h.vertex,fragment:h.fragment}),d=this.device.getShaderProgramUniformLocation(c,uniform_var_list_mesh),u=this.device.getShaderProgramUniformBlockLocation(c,uniform_block_list_mesh);this.meshPipelineInfo={program:c,progUniforms:d,progUniformBlocks:u},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),c=this.device.compileShaderProgram({vertex:h.vertex,fragment:h.fragment_mask}),d=this.device.getShaderProgramUniformLocation(c,uniform_var_list_mesh),u=this.device.getShaderProgramUniformBlockLocation(c,uniform_block_list_mesh),this.maskPipelineInfo={program:c,progUniforms:d,progUniformBlocks:u},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(var f=0;f<e.mesh.length;f++){var p={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(p.VAO),null===this.device.getGLArrayElementType(e.mesh[f].blendshapes.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].blendshapes.data);if(p.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[f].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[f].UVCoord.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].UVCoord.data);if(p.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[f].UVCoord.data),!0,0,0),e.mesh[f].opacity){if(null===this.device.getGLArrayElementType(e.mesh[f].opacity.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].opacity.data);p.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[f].opacity.data),!0,0,0)}if(p.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].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),p.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].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[f].triangles.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].triangles.data);if(p.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,p.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[f].triangles.data,this.device.gl.STATIC_DRAW),p.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,p.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),p.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,p.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[f].blendshapes.size[2]>0){for(var m=[Math.ceil(e.mesh[f].blendshapes.size[2]/4),e.mesh[f].blendshapes.size[0]*e.mesh[f].blendshapes.size[1]],_=Math.ceil(Math.sqrt(m[0]*m[1])),g=4*m[0],v=new Float32Array(_*_*4),y=0;y<m[1];y++){for(var b=0;b<e.mesh[f].blendshapes.size[2];b++)v[y*g+b]=e.mesh[f].blendshapes.data[y*e.mesh[f].blendshapes.size[2]+b];for(var S=e.mesh[f].blendshapes.size[2];S<g;S++)v[y*g+S]=0}if(p.textures.u_image_bs=this.device.gl.createTexture(),!p.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,p.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,_,_,this.device.gl.RGBA,v),p.uniformUInts.u_bs_count=m[0]}else p.uniformUInts.u_bs_count=0;for(var E,w=_createForOfIteratorHelperLoose(e.mesh[f].textureModels);!(E=w()).done;){var x=E.value,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);var A=this.device.getGLArrayElementType(x.data.data),R={texture:T,unsigned:this.device.gl.UNSIGNED_BYTE===A||this.device.gl.UNSIGNED_SHORT===A||this.device.gl.UNSIGNED_INT===A},P=x.data.data;if("Float64Array"===x.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===A&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===A&&!this.compat_features.OES_texture_half_float_linear){for(var B=x.data.size[1]*x.data.size[2]*3,C=new Uint8Array(x.data.size[0]*B),I=new Float32Array(x.data.size[0]),k=0;k<x.data.size[0];k++){for(var D=1e-6,U=0;U<B;U++)D=Math.max(D,Math.abs(x.data.data[k*B+U]));for(var O=1/D,F=0;F<B;F++)C[k*B+F]=Math.round(255*(x.data.data[k*B+F]*O*.5+.5));I[k]=D}P=C,R.unsigned=!0,R.scalingFactor=I}x.scalingFactor&&(R.scalingFactor=x.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,x.data.size[1],x.data.size[2],x.data.size[0],this.device.gl.RGB,P),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),p.texturePCAModels.push(R)}this.meshInfos.push(p)}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);var L=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,L),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);var M=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,M),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);var 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.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,M),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,N),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,L)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;var z=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,z),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,z)}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{for(var G=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3),j=0;j<G.length;j++)G[j]=Math.round(255*t.LUT.data[j]);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,G)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null},e.getProjMat=function(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())},e.initFrame=function(){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)},e.renderBackground=function(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);var e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);var n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){var r=t.fx.shadow,i=this.getBillboardShadowGeometryInfo(r.refPos,r.light,"point"===r.lightType);e+=4;for(var s=0;s<3;s++)for(var a=0;a<3;a++)this._ub_shadow_fx_data[4*s+a]=i.Mat_World2ObjImage[a][s];for(var o=0;o<3;o++)for(var l=0;l<3;l++)this._ub_shadow_fx_data[4*o+l+12]=i.Mat_ShadowImage2World[l][o];for(var h=0;h<3;h++)this._ub_shadow_fx_data[24+h]=r.tint[h];this._ub_shadow_fx_data[27]=r.intensity,this._ub_shadow_fx_data[28]=r.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)},e.renderMesh=function(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);var n,r=t.char,i=new Float32Array(flatten(this.getProjMat(r.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),n=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]);for(var a=r.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(r.skeleton.length),l=0;l<r.skeleton.length;l++){var h=a[l].apply(this.initSkeletonStatus[l].inv());o[l]=h.homogeneous_matrix()}for(var c=0,d=0;d<Math.min(this.meshStatistics.max_bones,r.skeleton.length);d++){for(var u=0;u<4;u++)for(var f=0;f<4;f++)this._ub_rig_info_data[c+4*u+f]=o[d][f][u];c+=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,i),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,n);for(var p=0;p<r.mesh.length;p++)if(r.mesh[p].genMask){var m=this.meshInfos[p];if(r.mesh[p].blendshapes.size[2]>0){c=16*this.meshStatistics.max_bones;for(var _=Math.min(r.mesh[p].blendshapeIndices.length,this.meshStatistics.max_bs_count),g=0;g<_;g++)this._ub_rig_info_data[c+g]=e.data.blendshapeWeights[r.mesh[p].blendshapeIndices[g]];for(var v=_;v<this.meshStatistics.max_bs_count;v++)this._ub_rig_info_data[c+v]=0}var y=0;for(var b in r.mesh[p].opacity&&(y+=1),m.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[b],m.uniformUInts[b]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,y),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,m.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,m.buffers.ub_rig_info),this.device.gl.bindVertexArray(m.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,m.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,m.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,r.mesh[p].triangles.itemSize(),this.device.getGLArrayElementType(r.mesh[p].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,i),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,n);for(var S=!0,E=0;E<r.mesh.length;E++){var w=this.meshInfos[E],x=w.texturePCAModels[e.data.mesh[E].textureModelIndex];if(r.mesh[E].blendshapes.size[0]>0){c=16*this.meshStatistics.max_bones;for(var T=Math.min(r.mesh[E].blendshapeIndices.length,this.meshStatistics.max_bs_count),A=0;A<T;A++)this._ub_rig_info_data[c+A]=e.data.blendshapeWeights[r.mesh[E].blendshapeIndices[A]];for(var R=T;R<this.meshStatistics.max_bs_count;R++)this._ub_rig_info_data[c+R]=0}var P=0;for(var B in r.mesh[E].opacity&&(P+=1),null!==this.LUTTexture&&(P+=2),x.unsigned&&(P+=4),S!=r.mesh[E].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!r.mesh[E].genMask),S=r.mesh[E].genMask),w.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[B],w.uniformUInts[B]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,P),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,w.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,w.buffers.ub_rig_info);var C=Math.min(e.data.mesh[E].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(var I=1;I<C;I++)this._ub_pca_info_data[I]=e.data.mesh[E].texturePCAWeights[I-1];if(x.scalingFactor)for(var k=0;k<C;k++)this._ub_pca_info_data[k]*=x.scalingFactor[k];for(var D=C;D<this.meshStatistics.max_pca_component_count;D++)this._ub_pca_info_data[D]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,w.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,w.buffers.ub_pca_info),this.device.gl.bindVertexArray(w.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,w.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,w.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),x.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,x.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,r.mesh[E].triangles.itemSize(),this.device.getGLArrayElementType(r.mesh[E].triangles.data),0)}S||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)},e.reinitialize=function(){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)},e.setSyncMedia=function(t){var e=this;this.device.run(function(t){return e.render()},t)},e.setCharData=function(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null},e.setFrameDataCallback=function(t){this.frameDataCallback=t},e.setGamma=function(t,e,n){this.currentGamma={r:t,g:e,b:n}},e.setColorBalance=function(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}},e.getBillboardTransform2D=function(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};var n=this.getProjMat(this.charData.char.cameraConfig),r=inv4(n),i=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=i[3][0]/i[3][1],a=[r[0][0]-e[0]*r[3][0],r[1][0]-e[1]*r[3][0],r[2][0]-e[2]*r[3][0]],o=[r[0][1]-t[0]*r[3][1],r[1][1]-t[1]*r[3][1],r[2][1]-t[2]*r[3][1]],l=[r[0][1]-e[0]*r[3][1],r[1][1]-e[1]*r[3][1],r[2][1]-e[2]*r[3][1]],h=s*Math.sqrt([r[0][0]-t[0]*r[3][0],r[1][0]-t[1]*r[3][0],r[2][0]-t[2]*r[3][0]].reduce(function(t,e){return t+e*e},0)/a.reduce(function(t,e){return t+e*e},0)),c=s*Math.sqrt(o.reduce(function(t,e){return t+e*e},0)/l.reduce(function(t,e){return t+e*e},0));return{offsetX:.5*(i[0][1]/i[3][1]-i[0][0]/i[3][0]-(h-1)),offsetY:.5*(1-c-(i[1][1]/i[3][1]-i[1][0]/i[3][0])),scaleX:h,scaleY:c}},e.getBillboardShadowGeometryInfo=function(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};var r=this.getProjMat(this.charData.char.cameraConfig),i=inv4(r),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]);var o=transpose(mmul(inv3(a),s)),l=mvmul(r,[t[0],t[1],t[2],1]),h=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[r[0][0],r[0][2],r[0][1]*t[1]+r[0][3]],[r[1][0],r[1][2],r[1][1]*t[1]+r[1][3]],[r[3][0],r[3][2],r[3][1]*t[1]+r[3][3]]])),Mat_World2ObjImage:inv3([[i[0][0],i[0][1],i[0][2]*h+i[0][3]],[i[1][0],i[1][1],i[1][2]*h+i[1][3]],[i[3][0],i[3][1],i[3][2]*h+i[3][3]]])}},e.render=function(){var t,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()},e.renderFrame=function(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()},e.destroy=function(){var t,e,n,r,i=this;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(function(t){t.VAO&&i.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(function(t){t&&i.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(function(t){t&&i.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(function(t){t.texture&&i.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!=(r=this.maskPipelineInfo)&&r.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)},t}(),containerWidgetMaps=new Map,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;var e=t.getAttribute("data-widget-container-id");if(e)return e;var n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){var e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}var 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:function(t){var e=t.axis_id,n=t.x_location,r=t.y_location,i=t.width,s=t.height,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");var o="position:absolute;";return o+=void 0!==e?"z-index:"+e+";":"z-index:1;",void 0!==n&&void 0!==r&&(o+="top:"+100*r+"%;left:"+100*n+"%;"),void 0!==i&&void 0!==s&&(o+="width:"+100*i+"%;height:"+100*s+"%;"),a.setAttribute("style",o),a},_getWidgetKey:function(t,e){return t+"-"+(null!=e?e:"default")},_replaceWidget:function(t,e,n,r){var i=this._getWidgetKey(t,e),s=getContainerElement(r||this._currentInstance);if(s){var a=getContainerWidgetMap(s);if(a.has(i)){var o=a.get(i);o&&o.parentNode&&o.remove()}a.set(i,n)}},WIDGET_PIC:function(t,e){var n=this._el(t),r=document.createElement("img");return r.crossOrigin="anonymous",r.setAttribute("style","width:100%;height:100%;"),r.src=t.image,n.appendChild(r),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE:function(t,e){var n=t.type,r=t.text,i=t.axis_id,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){var a=getContainerWidgetMap(s),o=this._getWidgetKey("WIDGET_SUBTITLE",i);if(a.has(o)){var l=a.get(o);l&&l.parentNode&&l.remove(),a.delete(o)}}return null}var h=this._el(t);return h.innerHTML=r,h.setAttribute("style",h.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",i,h,e),h},destroy:function(t){var e=getContainerElement(t||this._currentInstance);if(e){var n=getContainerId(e);if(containerWidgetMaps.has(n)){var r=containerWidgetMaps.get(n);r.forEach(function(t,e){(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),r.clear(),containerWidgetMaps.delete(n)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(function(t){t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var n=[0,0,0],r=0;r<3;r++)n[r]=t.dataview.getUint8(t.offset),t.offset+=1;var i=e.split(".").map(function(t){return 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)});for(var e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset),n=0;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;var r=e.slice(0,n);return new TextDecoder("utf-8").decode(r)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var e=0,n=0;;){var r=t.dataview.getUint8(t.offset);t.offset++;var i=e|(127&r)<<n;if(i<e)throw new Error("Integer too large to decode.");if(e=i,!(128&r))break;n+=7}return e}var 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);var Tensor=/*#__PURE__*/function(){function t(t,e){this.size=t,this.data=e}var e=t.prototype;return e.itemSize=function(){for(var t,e=1,n=_createForOfIteratorHelperLoose(this.size);!(t=n()).done;)e*=t.value;return e},e.byteSize=function(){return this.itemSize()*this.data.BYTES_PER_ELEMENT},t.zeros=function(e,n){void 0===n&&(n=Float32Array);for(var r=1,i=0;i<e.length;i++)r*=e[i];for(var s=new n(r),a=0;a<r;a++)s[a]=0;return new t(e,s)},e.part=function(){var e=[].slice.call(arguments);if(e.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");for(var n=[],r=1,i=e.length;i<this.size.length;i++)n.push(this.size[i]),r*=this.size[i];var s=0;e.length>0&&(s+=e[0]);for(var a=1;a<e.length;a++)s*=this.size[a],s+=e[a];return new t(n,this.data.slice(s*=r,s+r))},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var n=e.dataview.getUint8(e.offset);e.offset++;for(var r=new Array(n),i=1,s=0;s<n;s++)r[s]=decodeLongInt(e),i*=r[s];var a=String.fromCodePoint(e.dataview.getUint8(e.offset));e.offset++;var o=TensorDataTypeMap[a];if(void 0===o)throw new Error('Unsupported tensor element type "'+a+'".');var l=i*o.BYTES_PER_ELEMENT,h=new o(e.dataview.buffer.slice(e.offset,e.offset+l));return e.offset+=l,new t(r,h)},t}();function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var e=[null];;){var n=decodeStr(t);if(""==n)break;var r=null;if("text/plain;charset=UTF-8"===n){var i=decodeLongInt(t),s=new Uint8Array(t.dataview.buffer,t.offset,i);t.offset+=i,r=new TextDecoder("utf-8").decode(s)}else if("application/json;charset=UTF-8"==n){var a=decodeLongInt(t),o=new Uint8Array(t.dataview.buffer,t.offset,a);t.offset+=a;var l=new TextDecoder("utf-8");r=JSON.parse(l.decode(o))}else if("application/octet-stream"===n)r=Tensor.deserialize(t);else{var h=decodeLongInt(t),c=t.dataview.buffer.slice(t.offset,t.offset+h);t.offset+=h,r=new Blob([c],{type:n})}e.push(r)}return e}var CameraConfig=/*#__PURE__*/function(){function t(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}var e=t.prototype;return e.getIntrinsicMatrix=function(t){var e=25.4*this.filmAperture[0];return[[this.focalLength/(e/t[0]),0,t[0]/2],[0,this.focalLength/(e*t[1]/t[0]/t[1]),t[1]/2],[0,0,1]]},e.getProjMatrix=function(t,e,n){void 0===e&&(e=.01),void 0===n&&(n=Infinity);var r,i,s=t[0],a=t[1],o=this.getIntrinsicMatrix(t);return Infinity===n?(r=-1,i=-2*e):(r=-(n+e)/(n-e),i=-2*n*e/(n-e)),[[2*o[0][0]/s,0,(s-2*o[0][2])/s,0],[0,2*o[1][1]/a,(a-2*o[1][2])/a,0],[0,0,r,i],[0,0,-1,0]]},e.getExtrinsicMatrix=function(){var t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(function(e){return e*t}),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(function(t){return-t})))},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var n=new t;n.focalLength=e.dataview.getFloat32(e.offset,!0);for(var r=0;r<2;r++)n.filmAperture[r]=e.dataview.getFloat32(e.offset+4*(r+1),!0);for(var i=0;i<3;i++)n.translation[i]=e.dataview.getFloat32(e.offset+4*(i+3),!0);for(var s=0;s<3;s++)n.rotation[s]=e.dataview.getFloat32(e.offset+4*(s+6),!0);return e.offset+=36,n},t}(),RigidTransform=/*#__PURE__*/function(){function t(t,e){void 0===t&&(t=[0,0,0]),void 0===e&&(e=[1,0,0,0]),this.translation=t,this.rotQuaternion=e}var e=t.prototype;return e.apply=function(e){if(e instanceof t){var n=quaternion_mul(this.rotQuaternion,e.rotQuaternion);n=normalize(n);for(var r=mvmul(quaternion_to_mat(this.rotQuaternion),e.translation),i=0;i<3;i++)r[i]+=this.translation[i];return new t(r,n)}for(var s=mvmul(this.matrix(),e),a=0;a<3;a++)s[a]+=this.translation[a];return s},e.inv=function(){var e=quaternion_conj(this.rotQuaternion);return new t(mvmul(quaternion_to_mat(e),this.translation.map(function(t){return-t})),e)},e.matrix=function(){return quaternion_to_mat(this.rotQuaternion)},e.homogeneous_matrix=function(){return make_homogeneous(this.matrix(),this.translation)},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});for(var n=[0,0,0],r=[1,0,0,0],i=0;i<3;i++)n[i]=e.dataview.getFloat32(e.offset+4*i,!0);for(var s=0,a=0;a<3;a++)r[a+1]=e.dataview.getFloat32(e.offset+4*(a+3),!0),s+=r[a+1]*r[a+1];return r[0]=Math.sqrt(Math.max(1-s,0)),e.offset+=24,new t(n,r)},t}(),IBRMeshInfo=function(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){var n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;for(var r=[],i=[],s=!0;;){var a=decodeLongInt(t);if(0===a){if(!s)break}else r.push(a-1);s=!1;for(var o=[],l=!0,h=0;;){var c=decodeLongInt(t);if(l)for(var d=0;d<c;d++)o.push(h+d);if(l=!l,h+=c,0===c&&h>0)break}i.push(o)}var u=i[0].length;this.blendshapeIndices=r;for(var f,p=e.archivedItems[decodeLongInt(t)],m=Tensor.zeros([u,p.size[1]],p.data.constructor),_=Tensor.zeros([u,p.size[1],this.blendshapeIndices.length],p.data.constructor),g=0,v=_createForOfIteratorHelperLoose(i[0]);!(f=v()).done;){for(var y=f.value,b=0;b<p.size[1];b++)m.data[y*p.size[1]+b]=p.data[g*p.size[1]+b];g++}for(var S=this.blendshapeIndices.length,E=1;E<i.length;E++)for(var w,x=_createForOfIteratorHelperLoose(i[E]);!(w=x()).done;){for(var T=w.value,A=0;A<p.size[1];A++)_.data[(T*p.size[1]+A)*S+E-1]=p.data[g*p.size[1]+A];g++}this.vertices=m,this.blendshapes=_,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(u*e.maxJointsPerVertex),this.jointWeight=new Float32Array(u*e.maxJointsPerVertex);for(var R=0;R<u;R++){for(var P=0;P<e.maxJointsPerVertex;P++)this.jointIndex[R*e.maxJointsPerVertex+P]=t.dataview.getUint8(t.offset),t.offset+=1;for(var B=0;B<e.maxJointsPerVertex;B++)this.jointWeight[R*e.maxJointsPerVertex+B]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}var C=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(C);for(var I=0;I<C;I++)this.textureModels[I]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;var k=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var D=new Float32Array(k),U=0;U<k;U++)D[U]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([k],D);var O=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var F=new Uint16Array(3*O),L=0;L<O;L++)for(var M=0;M<3;M++)F[3*L+M]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([O,3],F);for(var N=new Float32Array(2*k),z=0;z<k;z++)for(var G=0;G<2;G++)N[2*z+G]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([k,2],N);var j=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var W=new Float32Array(3*k),H=0;H<3*k;H++)W[H]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;for(var V=new Float32Array((j-1)*k*3),$=0;$<j-1;$++)for(var K=0;K<3*k;K++)V[K*(j-1)+$]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([k,3],W),this.blendshapes=new Tensor([k,3,j-1],V),this.blendshapeIndices=[];for(var Y,X=_createForOfIteratorHelperLoose(e.blendshapeIndices);!(Y=X()).done;)this.blendshapeIndices.push(Y.value);this.jointIndex=new Uint8Array(k*e.maxJointsPerVertex),this.jointWeight=new Float32Array(k*e.maxJointsPerVertex);for(var Z=0;Z<k;Z++){for(var q=0;q<e.maxJointsPerVertex;q++)this.jointIndex[Z*e.maxJointsPerVertex+q]=t.dataview.getUint8(t.offset),t.offset+=1;for(var Q=0;Q<e.maxJointsPerVertex;Q++)this.jointWeight[Z*e.maxJointsPerVertex+Q]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}var J=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(J);for(var tt=0;tt<J;tt++){for(var et=[0,0,0,3],nt=0;nt<3;nt++)et[nt]=t.dataview.getUint16(t.offset,!0),t.offset+=2;for(var rt=new Float32Array(et[0]*et[1]*et[2]*3),it=0;it<rt.length;it++)rt[it]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[tt]={data:new Tensor(et,rt)}}}},IBRMeshFrameInfo=/*#__PURE__*/function(){function t(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}return t.deserialize=function(e,n){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var r=e.dataview.getUint8(e.offset);e.offset+=1;for(var i=new Float32Array(n.textureModels[r].data.size[0]-1),s=0;s<i.length;s++)i[s]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;return new t(r,i)},t}(),IBRAnimationGeneratorCharInfo_NN=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e={}),t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});var n=checkVersion(t,__version__),r=[];if(n[0]>2&&(r=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.");for(var i,s=new Set,a=_createForOfIteratorHelperLoose(e.blendshapeMap);!(i=a()).done;)for(var o,l=_createForOfIteratorHelperLoose(i.value);!(o=l()).done;)s.add(o.value);this.blendshapeCount=s.size}var h=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;var c=t.dataview.getUint8(t.offset);t.offset+=1;for(var d=new Array(c),u=0;u<c;u++)d[u]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=d,this.skeleton=new Array(h);for(var f=0;f<h;f++){var p=t.dataview.getUint8(t.offset);p>=this.skeleton.length&&(p=null),t.offset+=1;var m=RigidTransform.deserialize(t);this.skeleton[f]={parent:p,local_transform:m}}this.jointEvalOrder=new Array(h);for(var _=0;_<h;_++)this.jointEvalOrder[_]=t.dataview.getUint8(t.offset),t.offset+=1;var g={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(g.archivedItems=r);var v=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(v);for(var y=0;y<v;y++)n[0]<=2&&(g.blendshapeIndices=e.blendshapeMap[y]),this.mesh[y]=new IBRMeshInfo(t,g)}var e=t.prototype;return e.evalSkeleton=function(){for(var t,e=Array(this.skeleton.length),n=_createForOfIteratorHelperLoose(this.jointEvalOrder);!(t=n()).done;){var r=t.value;e[r]=null==this.skeleton[r].parent?this.skeleton[r].local_transform:e[this.skeleton[r].parent].apply(this.skeleton[r].local_transform)}return e},e.evalSkeletonFromMovable=function(t){for(var e=Array(this.skeleton.length),n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(var r,i=_createForOfIteratorHelperLoose(this.jointEvalOrder);!(r=i()).done;){var s=r.value;null!=this.skeleton[s].parent&&(e[s]=e[this.skeleton[s].parent].apply(this.skeleton[s].local_transform))}return e},t}(),IBRAnimationFrameData_NN=/*#__PURE__*/function(){function t(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}return t.deserialize=function(e,n,r){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var i=new t,s=n.mesh.length;if(i.mesh=new Array(s),i.blendshapeWeights=new Float32Array(n.blendshapeCount),r[0]>2){for(var a=0;a<s;a++)i.mesh[a]=IBRMeshFrameInfo.deserialize(e,n.mesh[a]);for(var o=0;o<i.blendshapeWeights.length;o++)i.blendshapeWeights[o]=e.dataview.getFloat32(e.offset,!0),e.offset+=4}else for(var l=0;l<s;l++){for(var h=n.mesh[l].blendshapeIndices,c=0;c+1<h.length;c++)i.blendshapeWeights[h[c+1]-1]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;var d=e.dataview.getUint8(e.offset);e.offset+=1;for(var u=new Float32Array(n.mesh[l].textureModels[d].data.size[0]-1),f=0;f<u.length;f++)u[f]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;i.mesh[l]=new IBRMeshFrameInfo(d,u)}i.movableJointTransforms=new Array(n.movableJoints.length);for(var p=0;p<n.movableJoints.length;p++)i.movableJointTransforms[p]=RigidTransform.deserialize(e);return i},t.interp=function(e,n,r,i,s){var a=new t;a.blendshapeWeights=new Float32Array(e.blendshapeWeights.length);for(var o=0;o<a.blendshapeWeights.length;o++)a.blendshapeWeights[o]=i*n.blendshapeWeights[o]+(1-i)*e.blendshapeWeights[o];a.mesh=[];for(var l=0;l<e.mesh.length;l++){for(var h=new IBRMeshFrameInfo(e.mesh[l].textureModelIndex,new Float32Array(e.mesh[l].texturePCAWeights.length)),c=0;c<e.mesh[l].texturePCAWeights.length;c++)h.texturePCAWeights[c]=i*n.mesh[l].texturePCAWeights[c]+(1-i)*e.mesh[l].texturePCAWeights[c];a.mesh.push(h)}a.movableJointTransforms=new Array(r.movableJointTransforms.length);for(var d=0;d<r.movableJointTransforms.length;d++){for(var u,f=!0,p=_createForOfIteratorHelperLoose(s);!(u=p()).done;)if(u.value[0]===d){f=!1;break}f&&(a.movableJointTransforms[d]=r.movableJointTransforms[d])}for(var m,_=_createForOfIteratorHelperLoose(s);!(m=_()).done;){for(var g=m.value,v=g[0],y=g[1],b=e.movableJointTransforms[y].inv().apply(e.movableJointTransforms[v]),S=n.movableJointTransforms[y].inv().apply(n.movableJointTransforms[v]),E=[],w=[],x=0;x<3;x++)E.push(i*S.translation[x]+(1-i)*b.translation[x]);for(var T=0;T<4;T++)w.push(i*S.rotQuaternion[T]+(1-i)*b.rotQuaternion[T]);w=normalize(w);var A=new RigidTransform(E,w);A=r.movableJointTransforms[y].apply(A),a.movableJointTransforms[v]=A}return a},t}();function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});var n=checkVersion(t,__version__),r=t.dataview.getUint32(t.offset,!0);t.offset+=4;for(var i=Array(r),s=0;s<r;s++)i[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return i}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){var t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),r=/Google Inc/.test(e),i=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(r||i)&&s}function getStyleStr(t){return Object.entries(t).map(function(t){var e=t[0],n=t[1],r="number"==typeof n?n.toString():n;return e.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()})+":"+r+";"}).join("")}function updateCanvasXOffset(t,e){var n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+" translateX("+e+"px)";t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){var t=screen.width+"x"+screen.height,e=navigator.userAgent,n=navigator.language,r=Intl.DateTimeFormat().resolvedOptions().timeZone,i=encodeURIComponent(t+"|"+e+"|"+n+"|"+r);return btoa(i)}function getDeviceInfo(){var t=navigator.userAgent,e="Unknown Brand",n="Unknown Model",r="Unknown Version",i="Unknown Browser",s="Unknown Version",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?r="Windows NT "+a[1]:o?r="Android "+o[1]:l?r="iOS "+l[1].replace(/_/g,"."):t.includes("Macintosh")?r="Macintosh":t.includes("Linux")&&(r="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");var h=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),c=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),d=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?(i="Chrome",s=h[1]):c?(i="Safari",s=c[1]):d?(i="Firefox",s=d[1]):u?(i="Edge",s=u[1]):f?(i="Opera",s=f[1]):p&&(i="IE",s=p[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:r,browser:i,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(){var t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}function _settle$2(t,e,n){if(!t.s){if(n instanceof _Pact$2){if(!n.s)return void(n.o=_settle$2.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle$2.bind(null,t,e),_settle$2.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var AvatarRender=/*#__PURE__*/function(){function t(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=function(){},this.onRenderChange=function(){},this.sendVideoInfo=function(){},this.lostHandler=function(){},this.restoreHandler=function(){},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=function(){},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=function(){},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")}var e=t.prototype;return e.resetFaceFrameState=function(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")},e.createPipeline=function(){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()))},e._lostHandler=function(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())},e._restoreHandler=function(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())},e._recoverContext=function(){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);var 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())},e._tryLightRecovery=function(){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}},e._tryMediumRecovery=function(){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}var e,n,r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),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}},e._tryFullRecovery=function(){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}var r=this.canvas,i=r.style.cssText,s=r.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),c=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=h,a.height=c,a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,window.avatarSDKLogger.log("[Recovery] Using reduced resolution: "+h+"x"+c+" (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}},e._onRecoverySuccess=function(){var 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},e._scheduleResolutionRestore=function(){var t=this;this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log("[Recovery] Scheduling resolution restore in "+this.RESOLUTION_RESTORE_DELAY+"ms"),this.resolutionRestoreTimer=setTimeout(function(){t._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)},e._restoreOriginalResolution=function(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");var r=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,i=null!=(e=null==r?void 0:r.width)?e:1080,s=null!=(n=null==r?void 0:r.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=i,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 "+i+"x"+s),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:"Resolution restored to "+i+"x"+s+".",e:{timestamp:Date.now(),resolution:{width:i,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")},e._advanceStage=function(){var t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){var 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},e._scheduleNextAttempt=function(){var t=this,e=this.recoveryBaseDelays[this.recoveryStage],n=this.recoveryMaxAttempts[this.recoveryStage],r=e*Math.pow(2,this.currentStageAttempts),i=Math.min(r,this.recoveryMaxDelay);window.avatarSDKLogger.log("[Recovery] Scheduling "+this.recoveryStage+" attempt "+(this.currentStageAttempts+1)+"/"+n+" in "+i+"ms (base="+e+"ms, exp="+r+"ms)"),this.restoreTimeout=setTimeout(function(){t.isRecovering=!0,t._recoverContext()},i)},e._reportRecoveryFailure=function(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()}})},e.init=function(t){var e,n,r,i,s,a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(r=null==(i=this.options.resourceManager.getConfig())||null==(i=i.resolution)?void 0:i.height)?r: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()},e.style=function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)},e.setCanvasStyle=function(t){var e,n,r,i,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;var h=null!=(e=null!=(n=null==(r=this.walkConfig)?void 0:r.init_point)?n:null==(i=this.options.resourceManager.getConfig())||null==(i=i.walk_config)?void 0:i.init_point)?e:null,c=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},d=c.width,u=void 0===d?1080:d,f=c.height,p=void 0===f?1920:f,m=(null!=(o=null==(l=t.container)?void 0:l.size)?o:[u,p])[1],_=t.avatar||{},g=_.v_align,v=void 0===g?"center":g,y=_.h_align,b=void 0===y?"center":y,S=_.scale,E=void 0===S?1:S,w=_.offset_x,x=void 0===w?0:w,T=_.offset_y,A=void 0===T?0:T;if(null!=h&&(b="left",x=0),"string"==typeof E&&E.includes("vh")){var R=parseFloat(E.replace("vh",""));E=isNaN(R)?1:R/100*m/p}this.scale=Number(E);var P=p*Number(E),B=u*Number(E),C=B/2,I=P/2,k={position:"absolute",zIndex:100,height:P+"px",width:B+"px",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(b){case"left":k.left=null!=h?h-C+"px":"0",k.marginLeft=x+"px";break;case"right":k.right="-"+C+"px",k.marginLeft=x+"px";break;default:k.position="absolute",k.left="50%",k.marginLeft=-C+x+"px"}switch(v){case"top":k.top="0",k.marginTop=A+"px";break;case"bottom":k.bottom="0",k.marginTop=A+"px";break;default:k.position="absolute",k.top="50%",k.marginTop=-I+A+"px"}var D=getStyleStr(k);this.canvas.setAttribute("style",D)},e.setWalkConfig=function(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)},e.setCharacterCanvasAnchor=function(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n,r=(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(r)}else{var i,s=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",s);var a=(null==(i=this.options.resourceManager.getConfig())||null==(i=i.init_events)?void 0:i.find(function(t){return"SetCharacterCanvasAnchor"===t.type}))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1};this.canvas.setAttribute("style",this.canvas.style.cssText+"left: calc("+a.x_location+" * 100%); top: calc("+a.y_location+" * 100%); transform: scale("+a.width+", "+a.height+"); transform-origin: top left;")}},e.computeWeight=function(t){var 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},e.render=function(t){var e,n,r,i,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};var l=this.options.dataCacheQueue._getBodyImageBitmap(t),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),c=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(r=null!=(i=null==l?void 0:l.body_id)?i:null==l?void 0:l.id)?r:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)h=c;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&&c){var d,u,f=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==(d=h)?void 0:d.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,c.FaceFrameData,c.FaceFrameData,f,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)h=c;else if(null!=c&&c.FaceFrameData)if(null===this.lastRealFaceFrameData)h=c;else{var p,m,_=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==(p=h)?void 0:p.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,c.FaceFrameData,c.FaceFrameData,_,(null==(m=this.options.resourceManager.resource_pack)?void 0:m.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 g,v;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(g=this.onStateChange)||g.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==(v=this.onDownloadProgress)||v.call(this,100));var y=!1;if(this.pipeline){var b;try{var S,E,w,x,T,A,R,P=this.options.resourceManager.getIsEnableRobotExpression()?null!=(S=null==(E=h)?void 0:E.FaceFrameData)?S:null:null!=l&&l.hfd&&null!=(w=null==(x=h)?void 0:x.FaceFrameData)?w:null;P&&this.saveAndDownload.appendMultipleToArray("render_faceData",[h]),this.lastFaceFrame=h;var B,C=l.frame;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(B=this.copyCtx)||B.drawImage(l.frame,0,0),C=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:C,data:P,backgroundTexture:null,fx:null!=(T=null==(A=this.options.resourceManager.getConfig())?void 0:A.fx)?T:{},onPostRender:function(){return null}});var I=[0,0,0],k=[].concat(I),D=null!=(R=null==l?void 0:l.offset)?R:0;this.lastBodyOffset=D,k[0]+=D-this.baseWalkOffset;var U=this.pipeline.getBillboardTransform2D([I[0],I[1],I[2]],[k[0],k[1],k[2]]).offsetX*this.canvas.width*this.scale;U!==this.canvasOffsetX&&(this.canvasOffsetX=U,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:U}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(U):updateCanvasXOffset(this.canvas,U)),this.lastFrameIndex=t,y=!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==(b=this.onRenderChange)||b.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:y}}return{canvas:this.canvas,rendered:!1}},e.renderBackground=function(){var t=this.options.resourceManager.getBackgroundImageElement();if(t){var e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage="url("+t.src+")",e.style.backgroundSize="cover",e.style.backgroundPosition="center")}},e._setCurrentBodyFrame=function(t){t&&(this.currentBodyFrame=t)},e._getCurrentBodyFrameInfo=function(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"}},e._getCurrentFrameData=function(t){var e,n,r,i,s,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!=(r=null!=(i=o.body_id)?i:o.id)?r:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}},e.setCanvasVisibility=function(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")},e.getCanvasVisibility=function(){return this.avatarCanvasVisible},e.destroy=function(){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){var t=this.device;this.device=null,requestAnimationFrame(function(){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;var e=document.getElementById("avatar-bg-container");e&&e.parentNode&&e.parentNode.removeChild(e),this.canvas&&this.canvas.parentNode&&this.canvas.remove()},e.setInterrupt=function(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)},e.simulateContextLoss=function(t,e){if(void 0===t&&(t=5e3),void 0===e&&(e=!1),this.device&&this.device.gl){var 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(function(){window.avatarSDKLogger.log("[Test] Auto-restoring context after "+t+"ms..."),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}else window.avatarSDKLogger.warn("[Test] No WebGL device available for testing")},e.getRecoveryStatus=function(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}},e.testStagedRecovery=function(){try{var t=function(){window.avatarSDKLogger.log("[Test] Staged recovery test completed!")},e=this;window.avatarSDKLogger.log("[Test] Starting staged recovery test...");var n=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}],r=_forTo$2(n,function(t){var r=n[t];return window.avatarSDKLogger.log("[Test] Step "+(t+1)+": "+r.desc),Promise.resolve(new Promise(function(t){setTimeout(function(){e.simulateContextLoss(r.delay,r.forceFail),t()},r.delay)})).then(function(){return Promise.resolve(new Promise(function(t){return setTimeout(t,r.delay+2e3)})).then(function(){var n=e.getRecoveryStatus();window.avatarSDKLogger.log("[Test] After step "+(t+1)+":",n)})})});return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){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}var e,n,r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),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}},t}();const _Pact$2=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const t=1&i?e:n;if(t){try{_settle$2(r,1,t(this.v))}catch(t){_settle$2(r,2,t)}return r}return this}return this.o=function(t){try{const i=t.v;1&t.s?_settle$2(r,1,e?e(i):i):n?_settle$2(r,1,n(i)):_settle$2(r,2,i)}catch(t){_settle$2(r,2,t)}},r},t}();function _isSettledPact$2(t){return t instanceof _Pact$2&&1&t.s}function _forTo$2(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact$2(o))return void o.then(a,i||(i=_settle$2.bind(null,r=new _Pact$2,2)));o=o.v}r?_settle$2(r,1,o):r=o}catch(t){_settle$2(r||(r=new _Pact$2),2,t)}}(),r}var BaseTrack=/*#__PURE__*/function(){function t(){}var e=t.prototype;return e.render=function(){},e.stop=function(){},t}(),ImageTrack=/*#__PURE__*/function(t){function e(e,n){var r;return(r=t.call(this)||this).data=e,r.instance=n,r}return _inheritsLoose(e,t),e.prototype.render=function(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null},e}(BaseTrack),SubtitleTrack=/*#__PURE__*/function(t){function e(e,n){var r;return(r=t.call(this)||this).data=e,r.instance=n,r}return _inheritsLoose(e,t),e.prototype.render=function(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)},e}(BaseTrack),TrackRenderer=/*#__PURE__*/function(){function t(t,e){this.TAG="[TrackRenderer]",this.instance=e;var n,r=t.type,i=t.data,s=t.text,a=void 0===s?"":s;"widget_pic"===r&&(this.tracker=new ImageTrack(i,e)),("subtitle_on"===r||"subtitle_off"===r)&&(this.tracker=new SubtitleTrack({type:r,text:a,axis_id:null!=(n=null==i?void 0:i.axis_id)?n:1e3},e))}var e=t.prototype;return e.render=function(){var t;return null==(t=this.tracker)?void 0:t.render()},e.stop=function(){this.tracker.stop()},e.destroy=function(){WidgetDefaultRenderer.destroy(this.instance)},t}(),UIRenderer=/*#__PURE__*/function(){function t(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}var e=t.prototype;return e.render=function(t){var e,n,r,i,s,a,o,l,h,c=this,d=[];if(-1===this.lastFrameIndex){var u=this.options.resourceManager.getConfig();u.init_events&&u.init_events.length>0&&(d=u.init_events.map(function(t){return _extends({},t,{speech_id:0})}))}var f=null;if(f=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,f?f.e=f.e.concat(d):f={e:d}),null!=(e=f)&&e.e){window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(f));var p,m,_=null==(n=f.e)?void 0:n.filter(function(t){return null==(null==t?void 0:t.speech_id)});if(null!=_&&_.length){var g=_.map(function(t){return t.type}).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:"Error: 事件中存在不包含speech_id的事件"+g,e:_})}if(this.enableClientInterrupt&&(f.e=null==(p=f.e)?void 0:p.filter(function(t){return t.speech_id>c.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type})),-1!==this.lastSpeechId&&this.lastSpeechId&&(f.e=null==(m=f.e)?void 0:m.filter(function(t){return(null==t?void 0:t.speech_id)>=c.lastSpeechId})),null!=(r=f.e)&&r.some(function(t){return"speak_start"===t.type})){var v=f.e.find(function(t){return"speak_start"===t.type});this.lastSpeechId=null==v?void 0:v.speech_id,this.onSpeakStateChange("speak_start",v.client_speak_id,(null==v?void 0:v.speech_id)||0)}if((null!=(i=f.e)&&i.some(function(t){return"walk_start"===t.type})||null!=(s=f.e)&&s.some(function(t){return"speak_walk_start"===t.type}))&&this.onWalkStateChange("walk_start"),null!=(a=f.e)&&a.some(function(t){return"voice_start"===t.type})){var y=f.e.find(function(t){return"voice_start"===t.type}),b=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==y?void 0:y.multi_turn_conversation_id}),this.onVoiceStart(b,null==y?void 0:y.client_speak_id)}if((null!=(o=f.e)&&o.some(function(t){return"walk_end"===t.type})||null!=(l=f.e)&&l.some(function(t){return"speak_walk_end"===t.type}))&&this.onWalkStateChange("walk_end"),null!=(h=f.e)&&h.some(function(t){return"voice_end"===t.type})){var S=f.e.find(function(t){return"voice_end"===t.type});this.onVoiceEnd((null==S?void 0:S.client_speak_id)||"",(null==S?void 0:S.speech_id)||0)}["speak_end","speak_error"].forEach(function(t){var e=f.e.find(function(e){return e.type===t});e&&c.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});for(var E=[].concat(f.e),w=0;w<f.e.length;w++){var x=f.e[w];if(!Object.prototype.hasOwnProperty.call(x,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(x);var T=E.indexOf(x);T>-1&&E.splice(T,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[x.type]){WidgetDefaultRenderer.PROXY_WIDGET[x.type](x);var A=E.indexOf(x);A>-1&&E.splice(A,1)}}if(E.length>0)for(var R,P=_createForOfIteratorHelperLoose(E);!(R=P()).done;){var B=new TrackRenderer(R.value,this.options.sdk);this.trackerRenderer.push(B)}return this.trackerRenderer}},e.clearTrackerRenderer=function(){this.trackerRenderer=[]},e.setInterrupt=function(t){this.interruptSpeechId=t},e.destroy=function(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(function(t){return t.destroy()})},t}(),FPSTracker=/*#__PURE__*/function(){function t(t){void 0===t&&(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}var e=t.prototype;return e.tick=function(t){void 0===t&&(t=!0);var e=performance.now();if(this.lastFrameTime>0){var 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},e.getStats=function(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};var t=this.frameTimestamps.reduce(function(t,e){return t+e},0)/this.frameTimestamps.length,e=Math.min.apply(Math,this.frameTimestamps),n=Math.max.apply(Math,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}},e.getCurrentFPS=function(){return this.currentFPS},e.getAverageFPS=function(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)},e.reset=function(){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},e.getDroppedFrames=function(){return this.droppedFrames},t}(),Composition=/*#__PURE__*/function(){function t(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)}var e=t.prototype;return e.compose=function(t){if(!this.audioOnlyMode){var e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);var n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(var r,i=_createForOfIteratorHelperLoose(this.restRenderers);!(r=i()).done;){var s=r.value,a=s.render(t);if(s.clearTrackerRenderer(),a)for(var o,l=_createForOfIteratorHelperLoose(a);!(o=l()).done;){var h=o.value,c=null==h?void 0:h.render();c&&this.container.appendChild(c)}}},e.getFPSStats=function(){return this.fpsTracker.getStats()},e.stop=function(){this.audioRenderer.stop(-1)},e.destroy=function(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(function(t){return t.destroy()})},t}(),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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/\'/g, "'")\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);for(var e=atob(t),n=new Uint8Array(e.length),r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function twoByteToInt16(t,e){var n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){var e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];for(var n=e.length/2,r=new ArrayBuffer(4*n),i=new Float32Array(r),s=0;s<n;s++){var a=2*s,o=twoByteToInt16(e[a],e[a+1]);i[s]=o/32767}return Array.from(i)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];var e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);var n=new Float32Array(e);return Array.from(n)}function _catch$8(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var ParallelDecoder=/*#__PURE__*/function(){function t(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=function(){},this.onDone=function(){},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}var e=t.prototype;return e.getRandomTaskId=function(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)},e.decode=function(t,e){var n=this;if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=function(t,r,i){n.currentDecodedFrameIndex=t.startFrameIndex+i,n._handlePendingAbort(t,i),e(t,r,i)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)},e.clearOldQueue=function(t){this.queue=this.queue.filter(function(e){return e.sf>=t})},e.updateQueue=function(t){if(this.abortAfterFrame=null,0!==this.queue.length){var e,n=this.queue[0].sf,r=t[0].sf;if(r>=this.queue[this.queue.length-1].ef)(e=this.queue).push.apply(e,t);else if(r<n){if(null!==this.currentDecodedFrameIndex&&r>this.currentDecodedFrameIndex+1){this.abortAfterFrame=r-1;var i=this.queue.filter(function(t){return t.ef<r});return void(this.queue=i.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(r===n)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{var s,a=this.queue.findIndex(function(t){return t.sf>=r});-1!==a&&(this.queue.length=a),this.abortAfterFrame=r-1,(s=this.queue).push.apply(s,t)}}else{var o;(o=this.queue).push.apply(o,t)}},e._isIOS=function(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)},e.getQueue=function(){return this.queue.map(function(t){return _extends({},t,{x_offset:[]})})},e.timeoutPromise=function(t,e){return new Promise(function(e,n){setTimeout(function(){n()},t)})},e.loadVideoWithTimeout=function(t){var e=this;return Promise.resolve(_catch$8(function(){return Promise.resolve(Promise.race([e.resourceManager.loadVideo(t),e.timeoutPromise(e.MAX_LOAD_VIDEO_TIMEOUT_MS,"视频 "+t+" 加载超时("+e.MAX_LOAD_VIDEO_TIMEOUT_MS+"ms)")]))},function(){return null}))},e._tryStartNext=function(){try{var t,e,n=this;return e=(null==(t=n.queue)?void 0:t.some(function(t){return null!==n.currentDecodedFrameIndex&&t.sf<n.currentDecodedFrameIndex}))?n._isIOS()?n.maxVideoCount:n.maxVideoCount+1:n._isIOS()?1:n.maxVideoCount,n.dataCacheQueue.getBodyVideoNameListLength()>=e?Promise.resolve():Promise.resolve(function(){if(n.currentParallel<n.maxParallel&&n.queue.length>0){var t,e,r=n.queue.shift();return n.saveAndDownload.appendMultipleToArray("videoData",[_extends({},r,{x_offset:parseUint8ToFloat32(r.x_offset)||[]})]),n._cleanupOldWorkers(null!=(t=null!=(e=r.body_id)?e:r.id)?t:0),n.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,r),r.n?Promise.resolve(n.loadVideoWithTimeout(r.n)).then(function(t){if(!t)return n.currentParallel--,void n._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,r),window.performanceTracker.markStart(performanceConstant.decode_video,r),window.performanceTracker.markStart(performanceConstant.first_decode_video,r),n._startWorker({name:r.n,id:r.id,frameState:r.s,start:r.asf,end:r.aef,hfd:r.hfd,data:t,startFrameIndex:r.sf,endFrameIndex:r.ef,body_id:r.body_id,x_offset:parseUint8ToFloat32(r.x_offset)||[]})}):(n.currentParallel--,n._tryStartNext(),void n.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:"body数据无Name: "+JSON.stringify(r)}))}}())}catch(t){return Promise.reject(t)}},e._startWorker=function(t){var e,n,r,i=this,s=this.currentTaskId;try{r=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}var a=(null!=(e=null!=(n=t.body_id)?n:t.id)?e:0)+"_"+t.name,o=t.data,l=new ArrayBuffer(o.byteLength);new Uint8Array(l).set(new Uint8Array(o)),r.addEventListener("error",function(t){s===i.currentTaskId&&i.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});var h=function(e){if(s===i.currentTaskId)if("frame"===e.data.type)if(i.firstDecodeFrame&&(i.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;i.cacheVideo(),i.onFrame(t,e.data.frame,e.data.index);var o=null!=(n=i.bodyFrameCountMap.get(t.name))?n:0;i.bodyFrameCountMap.set(t.name,o+1),i.abortAfterFrame&&e.data.index+t.startFrameIndex>=i.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",i.abortAfterFrame,t),i.abortOne(a),i.abortAfterFrame=null,i._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var l;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(l=i.bodyFrameCountMap.get(t.name))?l:0)<t.end-t.start-1&&i.bodyFrameCountMap.delete(t.name);var c=i.tasks.get(a);c&&(c.status="done",c.worker.postMessage({type:"abort"})),i.currentParallel--,i.onDone&&i.onDone(t,a),r.removeEventListener("message",h),r.terminate(),i.tasks.delete(a),0===i.currentParallel&&0===i.queue.length&&(i._locked=!1),i._tryStartNext()}else if("error"===e.data.type){var d,u=null!=(d=e.data.error)?d:"",f=u.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;i.reportMessage({code:f,message:u||"视频解码错误",e:{fileName:t.name,error:u}});var p=i.tasks.get(a);p&&(p.status="error",p.worker.postMessage({type:"abort"})),i.currentParallel--,i.onDone&&i.onDone(t,a),r.removeEventListener("message",h),r.terminate(),i.tasks.delete(a),0===i.currentParallel&&0===i.queue.length&&(i._locked=!1)}};r.addEventListener("message",h),this.tasks.set(a,{worker:r,status:"decoding",onMessage:h,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),r.postMessage({type:"decode",file:{data:l},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:s},[l])},e.cacheVideo=function(){for(var t,e=_createForOfIteratorHelperLoose(this.queue.slice(0,this.cacheVideoCount));!(t=e()).done;)this.resourceManager.preloadVideo(t.value.n)},e.abort=function(){this.tasks.forEach(function(t){var e=t.worker,n=t.onMessage;"decoding"===t.status&&(e.postMessage({type:"abort"}),n&&e.removeEventListener("message",n),e.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null},e.abortOne=function(t){var 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))},e.destroy=function(){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},e._handlePendingAbort=function(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)},e._cleanupOldWorkers=function(t){for(var e,n=_createForOfIteratorHelperLoose(this.tasks);!(e=n()).done;){var r=e.value,i=r[0],s=r[1],a=i.split("_"),o=parseInt(a[0],10);!isNaN(o)&&o<t&&(s.worker.postMessage({type:"abort"}),s.onMessage&&s.worker.removeEventListener("message",s.onMessage),s.worker.terminate(),this.tasks.delete(i))}},e.syncDecode=function(t){var e=this.queue.filter(function(e){return e.ef>t});0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())},e._reload=function(){this._offlineLastFrame=0,this.queue=[]},e._offLineMode=function(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()},e._offlineRun=function(){var t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0},e._putOfflineBodyData=function(t){var 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},t}(),FrameAnimationController=/*#__PURE__*/function(){function t(t){var e=void 0===t?{}:t,n=e.defaultSpeed,r=void 0===n?1:n,i=e.frameRate,s=void 0===i?24:i,a=e.frameCallback;this.startTime=null,this.currentFrame=1,this.speed=r,this.frameCallback=a||null,this.frameRate=s,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}var e=t.prototype;return e.play=function(){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)))},e.pause=function(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)},e.reset=function(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null},e.setSpeed=function(t){this.speed=t},e.gotoFrame=function(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()},e.nextFrame=function(){this.currentFrame++,this._updateFrame()},e.prevFrame=function(){this.gotoFrame(this.currentFrame-1)},e.destroy=function(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1},e._animate=function(t){var 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){var n=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;n!==this.currentFrame&&(this.currentFrame=n,this._updateFrame());var r=Date.now()-this.startTimeFromDate,i=Math.floor(Math.floor(r/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=i}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}},e._updateFrame=function(){var 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))},e.getCurrentFrame=function(){if(null!==this.startTime){var t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame},e.updateStartTime=function(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)},_createClass(t,[{key:"playing",get:function(){return this.isPlaying}}])}(),captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t){void 0===t&&(t=navigator);var e=getAudioSession(t);if(!e)return!1;var n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e){void 0===e&&(e=navigator);var n=getAudioSession(e);if(!n)return function(){};var r=playbackSessionRestoredListeners.get(n);return r||(r=new Set,playbackSessionRestoredListeners.set(n,r)),r.add(t),function(){var e,i;null==(e=r)||e.delete(t),0===(null==(i=r)?void 0:i.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}}function _catch$7(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var 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),PCMAudioPlayer=/*#__PURE__*/function(){function t(){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}var e=t.prototype;return e.init=function(){try{var t=this;if(t.isInitialized)return Promise.resolve();configureWebAudioPlaybackSession();var e=window.AudioContext||window.webkitAudioContext;if(!e||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");t.audioCtx=new e({sampleRate:t.SAMPLE_RATE});var n=window.avatarSDKLogger||console;return Promise.resolve(_catch$7(function(){return Promise.resolve(t.audioCtx.audioWorklet.addModule(t.WORKLET_SCRIPT_URL)).then(function(){n.log("[PCMAudioPlayer] Worklet脚本加载完成: "+t.WORKLET_SCRIPT_URL),t.audioWorkletNode=new AudioWorkletNode(t.audioCtx,"pcm-audio-processor"),t.audioWorkletNode.connect(t.audioCtx.destination),n.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),t.audioWorkletNode.port.onmessage=function(e){var r,i;switch(e.data.type){case"cacheStatus":n.log("[PCMAudioPlayer] Worklet缓存状态: "+e.data.size+"字节");break;case"error":n.error("[PCMAudioPlayer] Worklet错误:",e.data.detail);break;case"destroyConfirmed":n.log("[PCMAudioPlayer] Worklet已确认销毁"),null==t.destroyResolve||t.destroyResolve();break;case"syncVolume":void 0!==(null==(r=t.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("volume"))?void 0:r.value)&&(t.audioWorkletNode.parameters.get("volume").value=e.data.volume);break;case"syncSpeed":void 0!==(null==(i=t.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("speed"))?void 0:i.value)&&(t.audioWorkletNode.parameters.get("speed").value=e.data.speed);break;default:n.log("[PCMAudioPlayer] Worklet消息:",e.data)}},t.isInitialized=!0,t.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(function(){t.refreshPlaybackRoute()}),n.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")})},function(t){throw n.error("[PCMAudioPlayer] 初始化失败:",t),t}))}catch(t){return Promise.reject(t)}},e.refreshPlaybackRoute=function(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;var 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(function(e){t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}},e.receivePCMStream=function(t){var 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数据")},e.start=function(){try{var t=function(){e.audioWorkletNode.port.postMessage({type:"start"}),e.isPlaying=!0,n.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")},e=this;if(!e.isInitialized||!e.audioCtx||!e.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");var n=window.avatarSDKLogger||console,r=function(){if("running"!==e.audioCtx.state)return Promise.resolve(e.audioCtx.resume()).then(function(){n.log("[PCMAudioPlayer] AudioContext已恢复运行")})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.pause=function(){if(this.isInitialized&&this.audioWorkletNode){var t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}},e.stop=function(){if(this.isInitialized&&this.audioWorkletNode){var t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}},e.destroy=function(){try{var t=this,e=window.avatarSDKLogger||console;return null==t.unsubscribePlaybackSessionRestored||t.unsubscribePlaybackSessionRestored(),t.unsubscribePlaybackSessionRestored=null,t.detachCapture(),t.isInitialized&&t.audioCtx&&t.audioWorkletNode?Promise.resolve(new Promise(function(n){var r;t.destroyResolve=n,null==(r=t.audioWorkletNode)||r.port.postMessage({type:"destroy"});var i=setTimeout(function(){e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==t.destroyResolve||t.destroyResolve()},300);t.audioWorkletNode&&(t.audioWorkletNode.port.onmessage=function(e){"destroyConfirmed"===e.data.type&&(clearTimeout(i),null==t.destroyResolve||t.destroyResolve())})})).then(function(){function n(){t.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),t.isInitialized=!1,t.isPlaying=!1,t.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")}t.audioWorkletNode.disconnect(),t.audioWorkletNode.port.close(),t.audioWorkletNode=null;var r=function(){if("closed"!==t.audioCtx.state)return Promise.resolve(t.audioCtx.close()).then(function(){})}();return r&&r.then?r.then(n):n()}):(e.log("[PCMAudioPlayer] 播放器未初始化或已销毁"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.attachCapture=function(t){try{var e=this;if(!e.isInitialized||!e.audioCtx||!e.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");return e.captureWorklet?Promise.resolve():(e.captureCallback=t,Promise.resolve(_catch$7(function(){return Promise.resolve(e.audioCtx.audioWorklet.addModule(captureWorkletUrl)).then(function(){var t;e.captureWorklet=new AudioWorkletNode(e.audioCtx,"pcm-capture-processor"),e.audioWorkletNode.connect(e.captureWorklet),e.captureWorklet.port.onmessage=function(t){e.captureCallback&&t.data.pcmData&&e.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(t=window.avatarSDKLogger)||t.log("[PCMAudioPlayer] 捕获节点已挂载")})},function(t){var e;throw null==(e=window.avatarSDKLogger)||e.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t})))}catch(t){return Promise.reject(t)}},e.detachCapture=function(){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},e.resetCaptureBuffer=function(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})},e.getStatus=function(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}},e.setVolume=function(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})},e.setSpeed=function(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})},e.resume=function(){try{var t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(function(){window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(function(t){window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}return Promise.resolve()}catch(t){return Promise.reject(t)}},t}();function _catch$6(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var MediaSourceAudioPlayer=/*#__PURE__*/function(){function t(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()}t.getInstance=function(e){return t.instance||(t.instance=new t(e)),t.instance};var e=t.prototype;return e.createAudioElement=function(t){if(!this.audioElement){var e=document.getElementById("xmov-avatar-audio");if(e)this.audioElement=e;else{var 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}}},e.createNewMediaSource=function(){var t=this;return new Promise(function(e,n){try{if(!t.audioElement)return;t.mediaSource=new MediaSource,t.currentObjectURL=URL.createObjectURL(t.mediaSource),t.audioElement.src=t.currentObjectURL,t.mediaSource.addEventListener("sourceopen",function(){try{if(!t.mediaSource)return;t.sourceBuffer=t.mediaSource.addSourceBuffer(t.MIME_TYPE),t.sourceBuffer.mode="sequence",t.sourceBuffer.addEventListener("updateend",function(){t.isUpdating=!1,t.processQueue()}),t.isInitialized=!0,e()}catch(t){n(t)}}),t.mediaSource.addEventListener("sourceclose",function(){t.isInitialized=!1})}catch(t){n(t)}})},e.destroyCurrentMediaSource=function(t){try{var e=this;try{e.audioElement&&(e.audioElement.pause(),e.audioElement.removeAttribute("src"),e.audioElement.load())}catch(t){}try{e.currentObjectURL&&(URL.revokeObjectURL(e.currentObjectURL),e.currentObjectURL=null)}catch(t){}return e.mediaSource=null,e.sourceBuffer=null,e.isInitialized=!1,e.isPlaying=!1,e.queue=[],e.isUpdating=!1,Promise.resolve(e.createNewMediaSource()).then(function(){t()})}catch(t){return Promise.reject(t)}},e.stop=function(t){this.destroyCurrentMediaSource(t)},e.addAudioSegment=function(t){try{var e=this;return e.isDestroyed||(e.queue.push({data:t}),e.processQueue()),Promise.resolve()}catch(t){return Promise.reject(t)}},e.processQueue=function(){if(!this.isDestroyed&&this.sourceBuffer&&this.mediaSource&&!this.isUpdating&&0!==this.queue.length&&!this.sourceBuffer.updating&&"open"===this.mediaSource.readyState){this.isUpdating=!0;var t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}},e.start=function(){try{var t=this;if(t.isDestroyed||!t.audioElement||t.isPlaying)return Promise.resolve();var e=_catch$6(function(){return t.audioElement.currentTime=0,t.isPlaying=!0,Promise.resolve(t.audioElement.play()).then(function(){window.avatarSDKLogger.log("mseAudioPlayer开始播放",t.getStats(),Date.now())})},function(){});return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.getStats=function(){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"}},e.setSpeed=function(t){this.setPlaybackRate(t)},e.getBufferedRanges=function(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){for(var e=[],n=0;n<this.sourceBuffer.buffered.length;n++){var r=this.sourceBuffer.buffered.start(n).toFixed(2),i=this.sourceBuffer.buffered.end(n).toFixed(2);e.push("["+r+"-"+i+"]")}return e.join(", ")}}catch(t){return"-"}return"-"},e.setVolume=function(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)},e.setPlaybackRate=function(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)},e.destroy=function(){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,t.instance=null},t}();function _catch$5(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var AudioRender=/*#__PURE__*/function(){function t(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)}var e=t.prototype;return e.updateAudioData=function(t){if(this.resourceManager.config.raw_audio&&t[0].sid!==this.oldSpeechId){-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);for(var e,n=0,r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var i;n+=(null==(i=e.value.ad)?void 0:i.length)||0}for(var s,a,o,l=new Uint8Array(n),h=0,c=_createForOfIteratorHelperLoose(t);!(s=c()).done;){var d=s.value;d.ad&&(l.set(new Uint8Array(d.ad),h),h+=d.ad.length)}-1===this.speech_id?(this.speech_id=t[0].sid,null==(a=this.audio)||a.receivePCMStream(l)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(l)):null==(o=this.audio)||o.receivePCMStream(l)}},e._updateAudio=function(t){if(this.mseAudioPlayer&&0!==t.length){var 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(var r,i=_createForOfIteratorHelperLoose(t);!(r=i()).done;){var s=r.value;this.mseCacheAudioData.push({data:s.ad,frameIndex:s.sf,speechId:s.sid})}}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(var a,o=_createForOfIteratorHelperLoose(t);!(a=o()).done;){var l=a.value;if(l.ad){var h=l.ad instanceof ArrayBuffer?l.ad:l.ad.buffer.slice(l.ad.byteOffset,l.ad.byteOffset+l.ad.byteLength);this.mseAudioPlayer.addAudioSegment(h)}}}}},e.render=function(t){try{var e,n=this;if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",n.firstFrameIndex),-1===n.lastFrameIndex&&(n.lastFrameIndex=t),n.options.sdk.getStatus()===AvatarStatus.offline)return Promise.resolve();if(t>=n.firstFrameIndex&&-1!=n.firstFrameIndex&&!n.isPlaying&&n.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),n.isPlaying=!0,null==(e=n.audio)||e.start(),Promise.resolve();var r=function(){if(!n.resourceManager.config.raw_audio&&n.mseAudioPlayer){var e=function(){if(-1!==n.firstFrameIndex&&t>=n.firstFrameIndex&&!n.mseAudioPlayer.isPlaying&&!n.isPlaying){var e=n.mseAudioPlayer.getStats(),r=e.queueLength>0||"-"!==e.bufferedRanges,i=function(){if(r){var i=_catch$5(function(){return window.avatarSDKLogger.log("开始播放",t),n.isPlaying=!0,Promise.resolve(n.mseAudioPlayer.start()).then(function(){window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")})},function(r){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:r,frameIndex:t,firstFrameIndex:n.firstFrameIndex,queueLength:e.queueLength})});if(i&&i.then)return i.then(function(){})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]","等待更多 WebM 音频数据 (frameIndex: "+t+", queueLength: "+e.queueLength+")")}();if(i&&i.then)return i.then(function(){})}}();if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.resume=function(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())},e.pause=function(){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},e.stop=function(t){var e,n,r;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==(r=this.mseAudioPlayer)||r.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(var i,s=_createForOfIteratorHelperLoose(this.cacheAudioData);!(i=s()).done;){var a;null==(a=this.audio)||a.receivePCMStream(i.value)}this.cacheAudioData=[]}},e.addNewAudioSegment=function(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(var t,e=_createForOfIteratorHelperLoose(this.mseCacheAudioData);!(t=e()).done;){var n,r=t.value;r.data&&(null==(n=this.mseAudioPlayer)||n.addAudioSegment(r.data))}this.mseCacheAudioData=[]}},e.setVolume=function(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)},e.setSpeed=function(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)},e.getAudioPlayer=function(){return this.audio},e.destroy=function(){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},t}(),SaveAndDownload=/*#__PURE__*/function(){function t(t,e){void 0===t&&(t="avatarData.json"),void 0===e&&(e=!1),this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}var e=t.prototype;return e.initDownloadButton=function(){var t=this;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",function(){t.download()}),document.body.appendChild(this.downloadButton))},e.writeFields=function(t){this.enabled&&Object.assign(this.data,t)},e.appendMultipleToArray=function(t,e){var n;this.enabled&&(this.data[t]||(this.data[t]=[]),(n=this.data[t]).push.apply(n,e))},e.download=function(){if(this.enabled){var t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}},e.generateJSONContent=function(){return JSON.stringify(this.data,null,2)},e.downloadFile=function(t,e,n){if(this.enabled){var r=new Blob([t],{type:n}),i=URL.createObjectURL(r);this.downloadButton.href=i,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=i}},t}(),RenderScheduler=/*#__PURE__*/function(){function t(t){var e=this;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:function(t){e.onDownloadProgress(t)},onStateChange:function(e){t.onStateChange(e)},onRenderChange:function(n){t.onRenderChange(n,e.renderState),e.renderState=n},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:function(e){t.onWalkStateChange(e)},onVoiceStart:function(e,n){t.onVoiceStateChange("start",e,n)},onVoiceEnd:function(n,r){e.stopAudio(r),t.onVoiceStateChange("end",void 0,n)},onSpeakStateChange:function(n,r,i){"speak_start"===n?(e.currentSpeechId=i,e.avatarRenderer.setInterrupt(!1)):"speak_end"===n&&(e.dataCacheQueue.clearSubtitleOn(i),i>=e.currentSpeechId&&e.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(n,r)},sendSdkPoint:function(e,n,r){t.sendSdkPoint(e,n,r)}}),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:function(t){e.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:function(n,r){if(!e.hasSendTimeJson&&r&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",r),e.sendMessage("client_error",r),e.hasSendTimeJson=!0),t.renderFrameCallback(n+=e.offsetFrame),e.isStartPlay&&(e.composition.compose(n),e.decoder._tryStartNext(),t.onFrameDataUpdate)){var i=e.avatarRenderer._getCurrentFrameData(n);t.onFrameDataUpdate({frameIndex:n,body:i.body,face:i.face})}}})}var e=t.prototype;return e.init=function(){if(!this.audioOnlyMode){var 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})}},e.handleData=function(t,e){var n,r,i;try{var s=this;if(s.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return Promise.resolve();var a=s.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:s.decoder.clearOldQueue(a);var o=a,l=[].concat(e).filter(function(t){return t.ef>o});window.avatarSDKLogger.log(l,"mp4List"),l.length>0&&(s.renderState!==RenderState.paused&&a&&a>e[0].sf&&a>10&&s.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:"Error: 身体数据过期 cur:"+a+"-sf:"+e[0].sf,e:e}),s.decoder.decode(l,function(t,e,n){var r,i;t.start<=n&&t.end>=n&&(s.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&&s.decoder.abortOne((null!=(r=null!=(i=t.body_id)?i:t.id)?r:0)+"_"+t.name))}));break;case EFrameDataType.FACE:s.dataCacheQueue.clearOldFaceData(a);var h=s.handleFaceData(e);h.length>0&&s.saveAndDownload.appendMultipleToArray("faceData",h),s.dataCacheQueue.checkValidData(h,t);for(var c=[],d=[],u=0;u<h.length;u++){var f;null!=(f=h[u])&&f.face_frame_type?d.push(h[u]):c.push(h[u])}d.length&&s.dataCacheQueue._updateFacial(d),c.length&&s.dataCacheQueue._updateRealFacial(c);break;case EFrameDataType.AUDIO:if(s.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),s.renderState!==RenderState.paused&&a>e[0].sf){var p=a?a-e[0].sf:0;s.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:"Error: 音频数据过期 cur:"+a+"-sf:"+e[0].sf,e:{currentFrame:a,sf:e[0].sf,ef:p,timestamp:Date.now()}}),s.sendSdkPoint("audio_data_expired",{currentFrame:a,sf:e[0].sf,ef:p,timestamp:Date.now()})}var m=e[0],_=m.sf,g=m.ef-_;if(g<=0)return Promise.resolve();var v=(a||0)-_;if(v>g)return Promise.resolve();var y=1;if(v>0&&(y=g/Math.max(g-v,.1)),s._speedResetTimer&&clearTimeout(s._speedResetTimer),y>4)return Promise.resolve();s.audioRenderer.setSpeed(y),s._speedResetTimer=setTimeout(function(){s.audioRenderer.setSpeed(1),s._speedResetTimer=null},g*(1e3/24)/y),s.dataCacheQueue.checkValidData(e,t);var b,S=e.map(function(t){return s.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)})});if(S[0].sid<=s.lastSpeechId)return Promise.resolve();s.resourceManager.config.raw_audio?(null==(b=window.avatarSDKLogger)||b.log(s.TAG,"processedAudioData[0].sid",S[0].sid,s.currentSpeechId,s.renderState),s.audioRenderer.updateAudioData(S)):s.audioRenderer._updateAudio(S);break;case EFrameDataType.EVENT:s.dataCacheQueue.clearOldEvent(a);var E=e;s.setEventData({sf:E[0].sf,ef:E[0].ef,event:E[0].e});for(var w,x=!1,T=null,A=null,R=_createForOfIteratorHelperLoose(E);!(w=R()).done;){var P,B=w.value,C=null!=(P=B.e)?P:[];if(C.some(function(t){return"speak_start"===t.type})&&(x=!0),B.sf<a&&(T||(T=C.find(function(t){return"speak_start"===t.type})||null),A||(A=C.find(function(t){return"voice_start"===t.type})||null),T&&A))break}if(x&&s.audioRenderer.isPlaying){var I;s.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});var k,D,U=E.flatMap(function(t){var e;return null!=(e=t.e)?e:[]}).find(function(t){return"speak_start"===t.type}),O=null!=(I=null==U?void 0:U.speech_id)?I:0,F=s.audioRenderer.speech_id;-1!==F&&F<O&&(s.interrupt("new_speak_start",F),-1!==s.audioRenderer.speech_id&&s.audioRenderer.pause()),U&&(s.currentSpeechId=null!=(k=U.speech_id)?k:0,s.avatarRenderer.setInterrupt(!1),s.uiRenderer.lastSpeechId=null!=(D=U.speech_id)?D:0)}if(T){var L=T.speech_id,M=T.client_speak_id;s.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),s.currentSpeechId=null!=L?L:0,s.avatarRenderer.setInterrupt(!1),s.uiRenderer.lastSpeechId=null!=L?L:0,s.config.onSpeakStateChange("speak_start",null!=M?M:0)}if(A){var N,z;s.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});var G=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");s.config.onVoiceStateChange("start",G,null!=(N=null==(z=A)?void 0:z.client_speak_id)?N:"")}for(var j,W=E.filter(function(t){return-1===t.sf&&-1===t.ef}),H=_createForOfIteratorHelperLoose(W);!(j=H()).done;)for(var V=j.value,$=0;$<V.e.length;$++){var K=V.e[$];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(K);else if(WidgetDefaultRenderer.PROXY_WIDGET){var Y,X;null==(Y=WidgetDefaultRenderer.PROXY_WIDGET)||null==(X=Y[K.type])||X.call(Y,K)}}var Z=E.filter(function(t){return-1!==t.sf});s.dataCacheQueue._updateUiEvent(Z);break;case EFrameDataType.SYNC_FRAME:var q=e;if(null!=(n=s.sdk.getOptions().config)&&n.replay||(null==q?void 0:q.source)!==FRAME_SOURCE_SOURCE)return Promise.resolve();var Q=Date.now()/1e3,J=null!=(r=q.client_time)?r:0,tt=((null!=(i=q.server_client_frame)?i:0)+(Q-J)/2*24).toFixed(0);s.offsetFrame+=Number(tt)-Number(null!=a?a:0);break;default:s.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}return Promise.resolve()}catch(t){return Promise.reject(t)}},e.setOffsetFrame=function(t){this.offsetFrame+=t},e.setVolume=function(t){this.audioRenderer.setVolume(t)},e.runStartFrameIndex=function(){var t;null==(t=this.frameAnimationController)||t.play()},e.stateChangeHandle=function(t){this.dataCacheQueue.currentPlayState=t},e.stopAudio=function(t){this.audioRenderer.stop(t)},e.render=function(){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)},e.stop=function(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()},e.pauseRender=function(){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))},e.resumeRender=function(){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==="))},e.switchInvisibleMode=function(){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+",无法切换隐身模式")}},e.getRenderState=function(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,"getRenderState: "+this.renderState),this.renderState},e.destroy=function(){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()},e.handleFaceData=function(t){try{var e,n=this.resourceManager.resource_pack,r=this.resourceManager.getConfig().framedata_proto_version,i=[].concat(null!=(e=n.blendshape_map)?e:[]);return t.map(function(t){var e=[],n=t.body_id,s=t.sf,a=t.ef,o=t.s,l=t.id,h=t.js,c=t.bsw,d=t.ms,u=t.face_frame_type,f=t.asf,p=t.aef,m=t.n,_=t.cs,g=[];if((null==i?void 0:i.length)>0){for(var v=0;v<i.length;v++){var y=i[v];if((null==y?void 0:y.length)>0)for(var b=0;b<y.length;b++)e[v]||(e[v]=[]),e[v][b]=c[y[b]]}g=Array.from({length:d.length},r?function(t,n){var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=d[n])?void 0:i.index)?r:0,texturePCAWeights:null!=(s=null==(a=d[n])?void 0:a.weights)?s:[]}}:function(t,n){var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=d[n])?void 0:i[0])?r:0,texturePCAWeights:null!=(s=null==(a=d[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:d.length},r?function(t,e){var n,r,i,s;return{blendshapeWeights:0===e?c:[],textureModelIndex:null!=(n=null==(r=d[e])?void 0:r.index)?n:0,texturePCAWeights:null!=(i=null==(s=d[e])?void 0:s.weights)?i:[]}}:function(t,e){var n,r,i,s;return{blendshapeWeights:0===e?c:[],textureModelIndex:null!=(n=null==(r=d[e])?void 0:r[0])?n:0,texturePCAWeights:null!=(i=null==(s=d[e])?void 0:s[1])?i:[]}});return{body_id:n,frameIndex:s,sf:s,ef:a,asf:f,aef:p,n:m,cs:_,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:h.map(r?function(t){return formatMJT(t.translate,t.rotate)}:function(t){return formatMJT(t[0],t[1])}),blendshapeWeights:c}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}},e.forceSyncDecoder=function(){var t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)},e._reload=function(){this.decoder._reload()},e._getResumeInfo=function(){var t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)},e.sendVoiceEnd=function(){var t,e,n,r=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:r,ef:r+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}]}])},e.markReconnectRecover=function(){this.audioRenderer.resume(),this.decoder._reload()},e._offlineMode=function(){var t,e;this.dataCacheQueue._clearEvent();var 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();var r=this.getCurrentFrameIndex();r&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),r),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1},e._offlineRun=function(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()},e.ttsaStateChangeHandle=function(t){this.dataCacheQueue.currentTtsaState=t},e.resume=function(){this.audioRenderer.resume()},e.pauseForBackground=function(){this.audioRenderer.pause()},e.setAvatarCanvasVisible=function(t){this.avatarRenderer.setCanvasVisibility(t)},e.setCharacterCanvasLayout=function(t){this.avatarRenderer.setCharacterCanvasAnchor(t)},e.setWalkConfig=function(t){this.avatarRenderer.setWalkConfig(t)},e.interrupt=function(t,e){var n,r=Date.now(),i=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:i,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(i),this.dataCacheQueue.clearSubtitleOn(i);var 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!=i?i:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(i),this.uiRenderer.setInterrupt(i),Date.now()-r},e.seekToFrame=function(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)},e.getCurrentFrameIndex=function(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame},e.getSpeechId=function(){return this.audioRenderer.speech_id},e.getAudioRenderer=function(){return this.audioRenderer},e.simulateContextLoss=function(t,e){void 0===t&&(t=5e3),void 0===e&&(e=!1),this.avatarRenderer.simulateContextLoss(t,e)},e.getRecoveryStatus=function(){return this.avatarRenderer.getRecoveryStatus()},e.testStagedRecovery=function(){try{return Promise.resolve(this.avatarRenderer.testStagedRecovery())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){return this.avatarRenderer.restartWebGL()},t}();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,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,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,r=e.max_code,i=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,c,d,u,f,p,m=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++)c=t.heap[h],u=n[2*n[2*c+1]+1]+1,u>l&&(u=l,m++),n[2*c+1]=u,c>r||(t.bl_count[u]++,f=0,c>=o&&(f=a[c-o]),p=n[2*c],t.opt_len+=p*(u+f),s&&(t.static_len+=p*(i[2*c+1]+f)));if(0!==m){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]--,m-=2}while(m>0);for(u=l;0!==u;u--)for(c=t.bl_count[u];0!==c;)d=t.heap[--h],d>r||(n[2*d+1]!==u&&(t.opt_len+=(u-n[2*d+1])*n[2*d],n[2*d+1]=u),c--)}},gen_codes=(t,e,n)=>{const r=new Array(MAX_BITS$1+1);let i,s,a=0;for(i=1;i<=MAX_BITS$1;i++)a=a+n[i-1]<<1,r[i]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(r[e]++,e))}},tr_static_init=()=>{let t,e,n,r,i;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,t=0;t<1<<extra_lbits[r];t++)_length_code[n++]=r;for(_length_code[n-1]=r,i=0,r=0;r<16;r++)for(base_dist[r]=i,t=0;t<1<<extra_dbits[r];t++)_dist_code[i++]=r;for(i>>=7;r<D_CODES$1;r++)for(base_dist[r]=i<<7,t=0;t<1<<extra_dbits[r]-7;t++)_dist_code[256+i++]=r;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,r)=>{const i=2*e,s=2*n;return t[i]<t[s]||t[i]===t[s]&&r[e]<=r[n]},pqdownheap=(t,e,n)=>{const r=t.heap[n];let i=n<<1;for(;i<=t.heap_len&&(i<t.heap_len&&smaller(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!smaller(e,r,t.heap[i],t.depth));)t.heap[n]=t.heap[i],n=i,i<<=1;t.heap[n]=r},compress_block=(t,e,n)=>{let r,i,s,a,o=0;if(0!==t.sym_next)do{r=255&t.pending_buf[t.sym_buf+o++],r+=(255&t.pending_buf[t.sym_buf+o++])<<8,i=t.pending_buf[t.sym_buf+o++],0===r?send_code(t,i,e):(s=_length_code[i],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(i-=base_length[s],send_bits(t,i,a)),r--,s=d_code(r),send_code(t,s,n),a=extra_dbits[s],0!==a&&(r-=base_dist[s],send_bits(t,r,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,r=e.stat_desc.static_tree,i=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--,i&&(t.static_len-=r[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 r,i,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=a,a=e[2*(r+1)+1],++o<l&&i===a||(o<h?t.bl_tree[2*i]+=o:0!==i?(i!==s&&t.bl_tree[2*i]++,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=i,0===a?(l=138,h=3):i===a?(l=6,h=3):(l=7,h=4))},send_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),r=0;r<=n;r++)if(i=a,a=e[2*(r+1)+1],!(++o<l&&i===a)){if(o<h)do{send_code(t,i,t.bl_tree)}while(0!==--o);else 0!==i?(i!==s&&(send_code(t,i,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=i,0===a?(l=138,h=3):i===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,r)=>{let i;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,r-4,4),i=0;i<r;i++)send_bits(t,t.bl_tree[2*bl_order[i]+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,r)=>{send_bits(t,(STORED_BLOCK<<1)+(r?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,r)=>{let i,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),i=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=i&&(i=s)):i=s=n+5,n+4<=i&&-1!==e?_tr_stored_block$1(t,e,n,r):t.strategy===Z_FIXED$1||s===i?(send_bits(t,(STATIC_TREES<<1)+(r?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(r?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),r&&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,r)=>{let i=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{i=i+e[r++]|0,s=s+i|0}while(--a);i%=65521,s%=65521}return i|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,r)=>{const i=crcTable,s=r+n;t^=-1;for(let n=r;n<s;n++)t=t>>>8^i[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_init,_tr_stored_block:_tr_stored_block,_tr_flush_block:_tr_flush_block,_tr_tally:_tr_tally,_tr_align:_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH: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_FILTERED,Z_HUFFMAN_ONLY:Z_HUFFMAN_ONLY,Z_RLE:Z_RLE,Z_FIXED:Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN: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,r,i=t.w_size;e=t.hash_size,r=e;do{n=t.head[--r],t.head[r]=n>=i?n-i:0}while(--e);e=i,r=e;do{n=t.prev[--r],t.prev[r]=n>=i?n-i: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,r)=>{let i=t.avail_in;return i>r&&(i=r),0===i?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,i,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,i,n)),t.next_in+=i,t.total_in+=i,i)},longest_match=(t,e)=>{let n,r,i=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,c=t.w_mask,d=t.prev,u=t.strstart+MAX_MATCH;let f=h[s+a-1],p=h[s+a];t.prev_length>=t.good_match&&(i>>=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(r=MAX_MATCH-(u-s),s=u-MAX_MATCH,r>a){if(t.match_start=e,a=r,r>=o)break;f=h[s+a-1],p=h[s+a]}}}while((e=d[e&c])>l&&0!==--i);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,r,i;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-r),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),r+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=HASH(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[i+MIN_MATCH-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,r,i,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,i=t.bi_valid+42>>3,t.strm.avail_out<i)break;if(i=t.strm.avail_out-i,r=t.strstart-t.block_start,n>r+t.strm.avail_in&&(n=r+t.strm.avail_in),n>i&&(n=i),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==r+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===r+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),r&&(r>n&&(r=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+r),t.strm.next_out),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r,t.block_start+=r,n-=r),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:(i=t.window_size-t.strstart,t.strm.avail_in>i&&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++,i+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),i>t.strm.avail_in&&(i=t.strm.avail_in),i&&(read_buf(t.strm,t.window,t.strstart,i),t.strstart+=i,t.insert+=i>t.w_size-t.insert?t.w_size-t.insert:i),t.high_water<t.strstart&&(t.high_water=t.strstart),i=t.bi_valid+42>>3,i=t.pending_buf_size-i>65535?65535:t.pending_buf_size-i,s=i>t.w_size?t.w_size:i,r=t.strstart-t.block_start,(r>=s||(r||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&r<=i)&&(n=r>i?i:r,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===r?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,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),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(r=_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 r=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(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,r,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),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){i=t.strstart+t.lookahead-MIN_MATCH,r=_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<=i&&(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++,r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(r=_tr_tally(t,0,t.window[t.strstart-1]),r&&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&&(r=_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,r,i,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&&(i=t.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){s=t.strstart+MAX_MATCH;do{}while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&i<s);t.match_length=MAX_MATCH-(s-i),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,r,i){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=r,this.func=i}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,r,i,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||e<0||e>9||s<0||s>Z_FIXED||8===r&&1!==a)return err(t,Z_STREAM_ERROR$2);8===r&&(r=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=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+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<<i+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 r=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(r)&&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,r=-1;if(r=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=r<<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,r=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+r>n.pending_buf_size;){let i=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+i),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+=i,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,r-=i}let i=new Uint8Array(n.gzhead.extra);n.pending_buf.set(i.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending+=r,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,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=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>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=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>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r))}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 r=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(r!==BS_FINISH_STARTED&&r!==BS_FINISH_DONE||(n.status=FINISH_STATE),r===BS_NEED_MORE||r===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(r===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 r=t.state,i=r.wrap;if(2===i||1===i&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(1===i&&(t.adler=adler32_1(t.adler,e,n,0)),r.wrap=0,n>=r.w_size){0===i&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let t=new Uint8Array(r.w_size);t.set(e.subarray(n-r.w_size,n),0),e=t,n=r.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(r);r.lookahead>=MIN_MATCH;){let t=r.strstart,e=r.lookahead-(MIN_MATCH-1);do{r.ins_h=HASH(r,r.ins_h,r.window[t+MIN_MATCH-1]),r.prev[t&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=t,t++}while(--e);r.strstart=t,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,r.wrap=i,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: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,r=t.length;n<r;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,r=0,i=t.length;e<i;e++){let i=t[e];n.set(i,r),r+=i.length}return n},common={assign:assign,flattenChunks: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,r,i,s,a=t.length,o=0;for(i=0;i<a;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),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 r=0;r<e;r++)n+=String.fromCharCode(t[r]);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 r,i;const s=new Array(2*n);for(i=0,r=0;r<n;){let e=t[r++];if(e<128){s[i++]=e;continue}let a=_utf8len[e];if(a>4)s[i++]=65533,r+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&r<n;)e=e<<6|63&t[r++],a--;a>1?s[i++]=65533:e<65536?s[i++]=e:(e-=65536,s[i++]=55296|e>>10&1023,s[i++]=56320|1023&e)}}return buf2binstring(s,i)},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:string2buf,buf2string:buf2string,utf8border: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_SYNC_FLUSH,Z_FULL_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_COMPRESSION,Z_DEFAULT_STRATEGY: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,r=this.options.chunkSize;let i,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(r),n.next_out=0,n.avail_out=r),(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(i=deflate_1$2.deflate(n,s),i===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=deflate_1$2.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===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,r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x,T;const A=t.state;n=t.next_in,x=t.input,r=n+(t.avail_in-5),i=t.next_out,T=t.output,s=i-(e-t.avail_out),a=i+(t.avail_out-257),o=A.dmax,l=A.wsize,h=A.whave,c=A.wnext,d=A.window,u=A.hold,f=A.bits,p=A.lencode,m=A.distcode,_=(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),v=p[u&_];e:for(;;){if(y=v>>>24,u>>>=y,f-=y,y=v>>>16&255,0===y)T[i++]=65535&v;else{if(!(16&y)){if(64&y){if(32&y){A.mode=TYPE$1;break t}t.msg="invalid literal/length code",A.mode=BAD$1;break t}v=p[(65535&v)+(u&(1<<y)-1)];continue e}for(b=65535&v,y&=15,y&&(f<y&&(u+=x[n++]<<f,f+=8),b+=u&(1<<y)-1,u>>>=y,f-=y),f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),v=m[u&g];;){if(y=v>>>24,u>>>=y,f-=y,y=v>>>16&255,16&y){if(S=65535&v,y&=15,f<y&&(u+=x[n++]<<f,f+=8,f<y&&(u+=x[n++]<<f,f+=8)),S+=u&(1<<y)-1,S>o){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(u>>>=y,f-=y,y=i-s,S>y){if(y=S-y,y>h&&A.sane){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(E=0,w=d,0===c){if(E+=l-y,y<b){b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}}else if(c<y){if(E+=l+c-y,y-=c,y<b){b-=y;do{T[i++]=d[E++]}while(--y);if(E=0,c<b){y=c,b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}}}else if(E+=c-y,y<b){b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}for(;b>2;)T[i++]=w[E++],T[i++]=w[E++],T[i++]=w[E++],b-=3;b&&(T[i++]=w[E++],b>1&&(T[i++]=w[E++]))}else{E=i-S;do{T[i++]=T[E++],T[i++]=T[E++],T[i++]=T[E++],b-=3}while(b>2);b&&(T[i++]=T[E++],b>1&&(T[i++]=T[E++]))}break}if(64&y){t.msg="invalid distance code",A.mode=BAD$1;break t}v=m[(65535&v)+(u&(1<<y)-1)]}}break}}while(n<r&&i<a);b=f>>3,n-=b,f-=b<<3,u&=(1<<f)-1,t.next_in=n,t.next_out=i,t.avail_in=n<r?r-n+5:5-(n-r),t.avail_out=i<a?a-i+257:257-(i-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,r,i,s,a,o)=>{const l=o.bits;let h,c,d,u,f,p,m=0,_=0,g=0,v=0,y=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 P,B,C,I=null;for(m=0;m<=MAXBITS;m++)A[m]=0;for(_=0;_<r;_++)A[e[n+_]]++;for(y=l,v=MAXBITS;v>=1&&0===A[v];v--);if(y>v&&(y=v),0===v)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(g=1;g<v&&0===A[g];g++);for(y<g&&(y=g),E=1,m=1;m<=MAXBITS;m++)if(E<<=1,E-=A[m],E<0)return-1;if(E>0&&(t===CODES$1||1!==v))return-1;for(R[1]=0,m=1;m<MAXBITS;m++)R[m+1]=R[m]+A[m];for(_=0;_<r;_++)0!==e[n+_]&&(a[R[e[n+_]]++]=_);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,_=0,m=g,f=s,b=y,S=0,d=-1,w=1<<y,u=w-1,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;for(;;){P=m-S,a[_]+1<p?(B=0,C=a[_]):a[_]>=p?(B=I[a[_]-p],C=T[a[_]-p]):(B=96,C=0),h=1<<m-S,c=1<<b,g=c;do{c-=h,i[f+(x>>S)+c]=P<<24|B<<16|C}while(0!==c);for(h=1<<m-1;x&h;)h>>=1;if(0!==h?(x&=h-1,x+=h):x=0,_++,0===--A[m]){if(m===v)break;m=e[n+a[_]]}if(m>y&&(x&u)!==d){for(0===S&&(S=y),f+=g,b=m-S,E=1<<b;b+S<v&&(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;d=x&u,i[d]=y<<24|b<<16|f-s}}return 0!==x&&(i[f+x]=m-S<<24|64<<16),o.bits=y,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK:Z_BLOCK,Z_TREES: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_BUF_ERROR,Z_DEFLATED: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 r=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!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.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 r=inflateReset2(t,e);return r!==Z_OK$1&&(t.state=null),r},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,r)=>{let i;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)),r>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>r&&(i=r),s.window.set(e.subarray(n-r,n-r+i),s.wnext),(r-=i)?(s.window.set(e.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0},inflate$2=(t,e)=>{let n,r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x=0;const T=new Uint8Array(4);let A,R;const P=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,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,h=n.hold,c=n.bits,d=o,u=l,w=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=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,c-=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,c=0;break;case FLAGS:for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=TIME;case TIME:for(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=OS;case OS:for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=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(r.subarray(s,s+f),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,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=r[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,r,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=r[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,r,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(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(4&n.wrap&&h!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}h=0,c=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(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}t.adler=n.check=zswap32(h),h=0,c=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=c,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&c,c-=7&c,n.mode=CHECK;break}for(;c<3;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}switch(n.last=1&h,h>>>=1,c-=1,3&h){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){h>>>=2,c-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}h>>>=2,c-=2;break;case STORED:for(h>>>=7&c,c-=7&c;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&h,h=0,c=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;i.set(r.subarray(s,s+f),a),o-=f,s+=f,l-=f,a+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;c<14;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(n.nlen=257+(31&h),h>>>=5,c-=5,n.ndist=1+(31&h),h>>>=5,c-=5,n.ncode=4+(15&h),h>>>=4,c-=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(;c<3;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.lens[P[n.have++]]=7&h,h>>>=3,c-=3}for(;n.have<19;)n.lens[P[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],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(v<16)h>>>=_,c-=_,n.lens[n.have++]=v;else{if(16===v){for(R=_+2;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(h>>>=_,c-=_,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,c-=2}else if(17===v){for(R=_+3;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=_,c-=_,E=0,f=3+(7&h),h>>>=3,c-=3}else{for(R=_+7;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=_,c-=_,E=0,f=11+(127&h),h>>>=7,c-=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=c,inffast(t,u),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,h=n.hold,c=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;x=n.lencode[h&(1<<n.lenbits)-1],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(g&&!(240&g)){for(y=_,b=g,S=v;x=n.lencode[S+((h&(1<<y+b)-1)>>y)],_=x>>>24,g=x>>>16&255,v=65535&x,!(y+_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=y,c-=y,n.back+=y}if(h>>>=_,c-=_,n.back+=_,n.length=v,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;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.length+=h&(1<<n.extra)-1,h>>>=n.extra,c-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;x=n.distcode[h&(1<<n.distbits)-1],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(!(240&g)){for(y=_,b=g,S=v;x=n.distcode[S+((h&(1<<y+b)-1)>>y)],_=x>>>24,g=x>>>16&255,v=65535&x,!(y+_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=y,c-=y,n.back+=y}if(h>>>=_,c-=_,n.back+=_,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=v,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(R=n.extra;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.offset+=h&(1<<n.extra)-1,h>>>=n.extra,c-=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),m=n.window}else m=i,p=a-n.offset,f=n.length;f>l&&(f=l),l-=f,n.length-=f;do{i[a++]=m[p++]}while(--f);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;i[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;c<32;){if(0===o)break t;o--,h|=r[s++]<<c,c+=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,i,u,a-u):adler32_1(n.check,i,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,c=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(4&n.wrap&&h!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}h=0,c=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=c,(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),d-=t.avail_in,u-=t.avail_out,t.total_in+=d,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,t.next_out-u):adler32_1(n.check,i,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===d&&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 r,i,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(r=t.state,0!==r.wrap&&r.mode!==DICT?Z_STREAM_ERROR$1:r.mode===DICT&&(i=1,i=adler32_1(i,e,n,0),i!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.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: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_NO_FLUSH,Z_FINISH:Z_FINISH,Z_OK:Z_OK,Z_STREAM_END:Z_STREAM_END,Z_NEED_DICT:Z_NEED_DICT,Z_STREAM_ERROR:Z_STREAM_ERROR,Z_DATA_ERROR:Z_DATA_ERROR,Z_MEM_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,r=this.options.chunkSize,i=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(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&i&&(s=inflate_1$2.inflateSetDictionary(n,i),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,i=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=r-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(i)}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:constants};const{Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip}=deflate_1$1,{Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip: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};function _catch$4(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var request=function(t,e){try{var n,r,i,s,a,o,l;void 0===e&&(e={}),s=(n=e).data;var h={method:i=void 0===(r=n.method)?"GET":r,headers:_extends({"Content-Type":"application/json"},void 0===(a=n.headers)?{}:a)};return"GET"===i&&s&&(o=new URLSearchParams(s).toString(),t+=(t.includes("?")?"&":"?")+o),"GET"!==i&&s&&(h.body=JSON.stringify(s)),Promise.resolve(_catch$4(function(){return Promise.resolve(fetch(t,h)).then(function(t){if(!(l=t).ok)throw{status:l.status,statusText:l.statusText,message:"HTTP error! status: "+l.status};return l})},function(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}))}catch(t){return Promise.reject(t)}};function XMLRequest(t){return new Promise(function(e,n){var r,i=new XMLHttpRequest;i.open("GET",t.url),i.responseType="arraybuffer",i.timeout=null!=(r=t.timeout)?r:6e4,i.onload=function(){4===i.readyState&&200===i.status?e([!1,i.response]):n([!0,"HTTP "+i.status+" "+i.statusText])},i.onerror=function(){n([!0,"network error"])},i.ontimeout=function(){n([!0,"timeout after "+i.timeout+"ms"])},i.onabort=function(){n([!0,"aborted"])},i.onprogress=function(e){if(e.lengthComputable){var n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},i.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 r(t,e,r,i,s,a){return n((o=n(n(e,t),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function i(t,e,n,i,s,a,o){return r(e&n|~e&i,t,e,s,a,o)}function s(t,e,n,i,s,a,o){return r(e&i|n&~i,t,e,s,a,o)}function a(t,e,n,i,s,a,o){return r(e^n^i,t,e,s,a,o)}function o(t,e,n,i,s,a,o){return r(n^(e|~i),t,e,s,a,o)}function l(t,e){var r,l,h,c,d;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,f=-271733879,p=-1732584194,m=271733878;for(r=0;r<t.length;r+=16)l=u,h=f,c=p,d=m,u=i(u,f,p,m,t[r],7,-680876936),m=i(m,u,f,p,t[r+1],12,-389564586),p=i(p,m,u,f,t[r+2],17,606105819),f=i(f,p,m,u,t[r+3],22,-1044525330),u=i(u,f,p,m,t[r+4],7,-176418897),m=i(m,u,f,p,t[r+5],12,1200080426),p=i(p,m,u,f,t[r+6],17,-1473231341),f=i(f,p,m,u,t[r+7],22,-45705983),u=i(u,f,p,m,t[r+8],7,1770035416),m=i(m,u,f,p,t[r+9],12,-1958414417),p=i(p,m,u,f,t[r+10],17,-42063),f=i(f,p,m,u,t[r+11],22,-1990404162),u=i(u,f,p,m,t[r+12],7,1804603682),m=i(m,u,f,p,t[r+13],12,-40341101),p=i(p,m,u,f,t[r+14],17,-1502002290),u=s(u,f=i(f,p,m,u,t[r+15],22,1236535329),p,m,t[r+1],5,-165796510),m=s(m,u,f,p,t[r+6],9,-1069501632),p=s(p,m,u,f,t[r+11],14,643717713),f=s(f,p,m,u,t[r],20,-373897302),u=s(u,f,p,m,t[r+5],5,-701558691),m=s(m,u,f,p,t[r+10],9,38016083),p=s(p,m,u,f,t[r+15],14,-660478335),f=s(f,p,m,u,t[r+4],20,-405537848),u=s(u,f,p,m,t[r+9],5,568446438),m=s(m,u,f,p,t[r+14],9,-1019803690),p=s(p,m,u,f,t[r+3],14,-187363961),f=s(f,p,m,u,t[r+8],20,1163531501),u=s(u,f,p,m,t[r+13],5,-1444681467),m=s(m,u,f,p,t[r+2],9,-51403784),p=s(p,m,u,f,t[r+7],14,1735328473),u=a(u,f=s(f,p,m,u,t[r+12],20,-1926607734),p,m,t[r+5],4,-378558),m=a(m,u,f,p,t[r+8],11,-2022574463),p=a(p,m,u,f,t[r+11],16,1839030562),f=a(f,p,m,u,t[r+14],23,-35309556),u=a(u,f,p,m,t[r+1],4,-1530992060),m=a(m,u,f,p,t[r+4],11,1272893353),p=a(p,m,u,f,t[r+7],16,-155497632),f=a(f,p,m,u,t[r+10],23,-1094730640),u=a(u,f,p,m,t[r+13],4,681279174),m=a(m,u,f,p,t[r],11,-358537222),p=a(p,m,u,f,t[r+3],16,-722521979),f=a(f,p,m,u,t[r+6],23,76029189),u=a(u,f,p,m,t[r+9],4,-640364487),m=a(m,u,f,p,t[r+12],11,-421815835),p=a(p,m,u,f,t[r+15],16,530742520),u=o(u,f=a(f,p,m,u,t[r+2],23,-995338651),p,m,t[r],6,-198630844),m=o(m,u,f,p,t[r+7],10,1126891415),p=o(p,m,u,f,t[r+14],15,-1416354905),f=o(f,p,m,u,t[r+5],21,-57434055),u=o(u,f,p,m,t[r+12],6,1700485571),m=o(m,u,f,p,t[r+3],10,-1894986606),p=o(p,m,u,f,t[r+10],15,-1051523),f=o(f,p,m,u,t[r+1],21,-2054922799),u=o(u,f,p,m,t[r+8],6,1873313359),m=o(m,u,f,p,t[r+15],10,-30611744),p=o(p,m,u,f,t[r+6],15,-1560198380),f=o(f,p,m,u,t[r+13],21,1309151649),u=o(u,f,p,m,t[r+4],6,-145523070),m=o(m,u,f,p,t[r+11],10,-1120210379),p=o(p,m,u,f,t[r+2],15,718787259),f=o(f,p,m,u,t[r+9],21,-343485551),u=n(u,l),f=n(f,h),p=n(p,c),m=n(m,d);return[u,f,p,m]}function h(t){var e,n="",r=32*t.length;for(e=0;e<r;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function c(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var r=8*t.length;for(e=0;e<r;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function d(t){var e,n,r="0123456789abcdef",i="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),i+=r.charAt(e>>>4&15)+r.charAt(15&e);return i}function u(t){return unescape(encodeURIComponent(t))}function f(t){return function(t){return h(l(c(t),8*t.length))}(u(t))}function p(t,e){return function(t,e){var n,r,i=c(t),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=l(i,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^i[n],a[n]=1549556828^i[n];return r=l(s.concat(c(e)),512+8*e.length),h(l(a.concat(r),640))}(u(t),u(e))}function m(t,e,n){return e?n?p(e,t):d(p(e,t)):n?f(t):d(f(t))}t.exports?t.exports=m:e.md5=m}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,function(t){return"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0")})}function compareUnicodeCodePoints(t,e){for(var n=Array.from(t,function(t){return t.codePointAt(0)}),r=Array.from(e,function(t){return t.codePointAt(0)}),i=Math.min(n.length,r.length),s=0;s<i;s+=1)if(n[s]!==r[s])return n[s]-r[s];return n.length-r.length}function parseUrlWithoutBase(t){try{var e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){var n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,r,i){var s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(r).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"!=typeof e)return e;for(var n,r={},i=_createForOfIteratorHelperLoose(Object.keys(e).sort(compareUnicodeCodePoints));!(n=i()).done;){var s=n.value;r[s]=t(e[s])}return r}(i),h=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),c=encodeWithMd5(""+o.toLowerCase()+n.toLowerCase()+h+e+a);return s["X-APP-ID"]=t,s["X-TOKEN"]=c,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}var CacheManager=/*#__PURE__*/function(){function t(t){this.cacheServer=t}return t.prototype.getVideo=function(t){return this.cacheServer+"/get_video?url="+encodeURIComponent(t)},t}();function _catch$3(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var ResourceManager=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.getAppInfo=function(){return{appId:this.options.appId}},e.getBackgroundImage=function(){var t=this;return new Promise(function(e,n){try{var r,i,s=new Image;if(s.crossOrigin="anonymous",s.src=(null==(r=t.config)?void 0:r.background_img)||"",null==(i=t.config)||!i.background_img)return;s.onload=function(){t.bg=s,e()},s.onerror=function(n){t.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:s}}),t.bg=null,e()}}catch(t){}})},e.getIsEnableRobotExpression=function(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression},e.getBackgroundImageElement=function(){return this.bg},e.getConfig=function(){return this.config},e.load=function(t){try{var e=this;return e.destroyed=!1,null==t||t(e.progress),e.startSessionTimer&&(clearInterval(e.startSessionTimer),e.startSessionTimer=null),e.startSessionTimer=setInterval(function(){if(e.destroyed||e.progress>=14)return clearInterval(e.startSessionTimer),void(e.startSessionTimer=null);e.progress+=1,null==t||t(e.progress)},100),Promise.resolve(e.startSession()).then(function(n){var r;function i(i){var a,o;if(r)return i;if(!n)return clearInterval(e.startSessionTimer),e.startSessionTimer=null,null;clearInterval(e.startSessionTimer),e.startSessionTimer=null,e.progress=15,null==t||t(e.progress),e.resource_pack=s.resource_pack,e.config=s.config,e.offlineIdle=(null==(a=s.resource_pack)?void 0:a.offline_idle)||[];var l=function(){if(e.resource_pack){var n=function(){var t,n;if(e.getBackgroundImage(),(null==(t=e.mouthShapeLib)||!t.char_info)&&null!=s&&null!=(n=s.resource_pack)&&n.face_ani_char_data&&!e.audioOnlyMode)return o=1,null},r=function(){if(!e.audioOnlyMode)return Promise.resolve(e.loadMouthShapeLib(t)).then(function(){})}();return r&&r.then?r.then(n):n()}}();return l&&l.then?l.then(function(t){return o?t:s}):o?l:s}var s=n;null!=s&&s.session_id&&(e.session_id=s.session_id);var a=function(){if(e.destroyed)return window.avatarSDKLogger.warn(e.TAG,"sdk destroyed during load, aborting after startSession"),Promise.resolve(e.stopSession("destroy_during_init")).then(function(){return r=1,null})}();return a&&a.then?a.then(i):i(a)})}catch(t){return Promise.reject(t)}},e.startSession=function(){var t=this;return Promise.resolve(_catch$3(function(){return Promise.resolve(t._startSession()).then(function(e){return null!=e&&e.verify_res&&(null==t.options.onStartSessionWarning||t.options.onStartSessionWarning(e.verify_res)),e})},function(){return null}))},e._startSession=function(){var t,e=this;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;var n=""+this.options.gatewayServer,r=_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})}),i=headersNeedSign(this.options.appId,this.options.appSecret,"POST",n,r);return request(n,{method:"POST",data:i.data,headers:_extends({},i.headers,this.options.headers)}).then(function(t){return t.json()}).then(function(t){var n;return null!=t&&null!=(n=t.data)&&n.resource_pack?null==t?void 0:t.data:(e.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(function(t){return e.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null})},e.stopSession=function(t){try{var e=this;return Promise.resolve(_catch$3(function(){var n=""+e.options.gatewayServer;if(e.session_id){var r=headersNeedSign(e.options.appId,e.options.appSecret,"DELETE",n,{session_id:e.session_id,stop_reason:t});return Promise.resolve(request(n,{method:"DELETE",data:r.data,headers:_extends({},r.headers,e.options.headers)})).then(function(t){return Promise.resolve(t.json())})}},function(t){e.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}))}catch(t){return Promise.reject(t)}},e.loadMouthShapeLib=function(t){try{var e=this;return Promise.resolve(_catch$3(function(){function n(){var n;function c(i){if(n)return i;var o=performance.now()-a;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:o,downlink:s>0&&o>0?8*s/(o/1e3)/1e6:0,networkStatus:navigator.onLine}),e.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(r,{blendshapeMap:e.resource_pack.blendshape_map||[]})},e.progress+=65,null==t||t(e.progress)}var d=function(){if(!r){var t=_catch$3(function(){var t=e.resource_pack.face_ani_char_data;return a=performance.now(),o=a,l=0,Promise.resolve(XMLRequest({url:t,onProgress:h()})).then(function(t){r=t[1]})},function(t){e.first_load&&(e.first_load=!1,e.stopSession("char_bin_load_error")),null==e.sdk.onMessage||e.sdk.onMessage({code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:i,binError:t}}),n=1});if(t&&t.then)return t.then(function(){})}}();return d&&d.then?d.then(c):c(d)}if(!e.resource_pack.face_ani_char_data)return e.progress+=60,void(null==t||t(e.progress));var r=null,i=null,s=0,a=0,o=0,l=0,h=function(){return function(n,r){if(r){var i=performance.now(),s=i-o,a=r.loaded-l;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:s,downlink:s>0&&a>0?8*a/(s/1e3)/1e6:0,networkStatus:navigator.onLine}),l=r.loaded,o=i,null==t||t(e.progress+.65*n)}}},c=_catch$3(function(){var t=e.resource_pack.face_ani_char_data+".gz";return a=performance.now(),o=a,l=0,Promise.resolve(XMLRequest({url:t,onProgress:h()})).then(function(t){var e=pako.ungzip(new Uint8Array(t[1])),n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e),r=n})},function(t){i=t,r=null});return c&&c.then?c.then(n):n()},function(t){e.first_load&&(e.first_load=!1,e.stopSession("char_bin_load_error")),null==e.sdk.onMessage||e.sdk.onMessage({code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}))}catch(t){return Promise.reject(t)}},e.getMouthShapeLib=function(){return this.mouthShapeLib},e.getVideoUrl=function(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}),"";var e,n=""+this.resource_pack.body_data_dir+t+".mp4";return this.cacheServer?null==(e=this.cacheServer)?void 0:e.getVideo(n):n},e.preloadVideo=function(t){try{return this.videoCache.has(t)?Promise.resolve():Promise.resolve(this.loadVideo(t))}catch(t){return Promise.reject(t)}},e.loadVideo=function(t){try{var e,n=function(n){if(e)return n;r.isProcessingVideo=!0;var i=r.downloadVideo(t);return r.downloadingVideos.set(t,i),_finallyRethrows$1(function(){return Promise.resolve(i)},function(e,n){if(r.downloadingVideos.delete(t),r.isProcessingVideo=!1,e)throw n;return n})},r=this,i=r.videoCache.get(t)||r.offlineCache.get(t);if(i){if(i.data)return r.updateCacheAccess(t),Promise.resolve(i.data);window.avatarSDKLogger.warn(r.TAG,"发现无效缓存条目: "+t+",正在删除"),r.videoCache.delete(t)}var s=function(){if(r.downloadingVideos.has(t))return _catch$3(function(){return Promise.resolve(r.downloadingVideos.get(t)).then(function(t){return e=1,t})},function(e){throw r.downloadingVideos.delete(t),window.avatarSDKLogger.warn(r.TAG,t+" 视频下载失败,从下载列表移除"),e})}();return Promise.resolve(s&&s.then?s.then(n):n(s))}catch(t){return Promise.reject(t)}},e.downloadVideo=function(t){try{var e=this,n=e.getVideoUrl(t);return n?Promise.resolve(_catch$3(function(){return Promise.resolve(e._fetchVideo(n)).then(function(r){var i=r.response,s=r.arrayBuffer;return i.ok?(e.addToCache(t,s),s):(e.first_load&&(e.first_load=!1,e.stopSession("load_video_error")),void e.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:"Error: "+t+" 视频下载失败",e:{name:t,url:n,res:i}}))})},function(r){e.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:"Error: "+t+" 视频下载失败",e:{name:t,url:n,error:r}})})):Promise.resolve()}catch(t){return Promise.reject(t)}},e._fetchVideo=function(t){try{var e=this;if(e.networkInfos.length>=4){var n=e.networkInfos.reduce(function(t,e){return t+e.rtt},0)/e.networkInfos.length,r=e.networkInfos.reduce(function(t,e){return t+e.downlink},0)/e.networkInfos.length;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:n,downlink:r,networkStatus:navigator.onLine}),e.networkInfos.length=0}var i=performance.now();return Promise.resolve(fetch(t)).then(function(t){var n=parseFloat(t.headers.get("Content-Length")||"0"),r=performance.now();return Promise.resolve(t.arrayBuffer()).then(function(s){var a=r-i,o={rtt:a,downlink:8*n/(a/1e3*1e6),networkStatus:navigator.onLine};return e.networkInfos.push(o),{response:t,arrayBuffer:s}})})}catch(t){return Promise.reject(t)}},e.addToCache=function(t,e){for(var n,r=Date.now(),i=0,s=_createForOfIteratorHelperLoose(this.videoCache.values());!(n=s()).done;)i+=n.value.data.byteLength;if(i+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),i=0;for(var a,o=_createForOfIteratorHelperLoose(this.videoCache.values());!(a=o()).done;)i+=a.value.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)for(var l,h=.5*this.maxCacheSize,c=_createForOfIteratorHelperLoose(Array.from(this.videoCache.entries()).sort(function(t,e){return t[1].lastAccessTime-e[1].lastAccessTime}));!(l=c()).done;){var d=l.value,u=d[0],f=d[1];if(i<=h)break;this.videoCache.delete(u),i-=f.data.byteLength}}this.videoCache.set(t,{data:e,lastAccessTime:r,accessCount:1})},e.startCacheCleanup=function(){var t=this;this.cacheCleanupInterval=setInterval(function(){t.cleanupCache()},3e5)},e.cleanupCache=function(){if(!this.isProcessingVideo){for(var t,e=Date.now(),n=Array.from(this.videoCache.entries()).sort(function(t,e){return t[1].lastAccessTime-e[1].lastAccessTime}),r=0,i=[],s=_createForOfIteratorHelperLoose(this.videoCache.entries());!(t=s()).done;)r+=t.value[1].data.byteLength;for(var a,o=_createForOfIteratorHelperLoose(n);!(a=o()).done;){var l=a.value,h=l[1];e-h.lastAccessTime>6e5&&(i.push(l[0]),r-=h.data.byteLength)}if(r>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(var c,d=_createForOfIteratorHelperLoose(n);!(c=d()).done;){var u=c.value,f=u[0],p=u[1];if(!i.includes(f)&&(i.push(f),r-=p.data.byteLength,this.videoCache.size-i.length<=2||r<=.8*this.maxCacheSize&&this.videoCache.size-i.length<=.8*this.maxCacheEntries))break}for(var m=0,_=i;m<_.length;m++)this.videoCache.delete(_[m])}},e.updateCacheAccess=function(t){var e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)},e.clearAllCache=function(){this.videoCache.clear()},e._getOfflineIdle=function(){return this.offlineIdle},e._getSessionId=function(){return this.session_id||""},e._reload=function(){try{var t=this;return Promise.resolve(t.startSession()).then(function(e){var n;function r(e){var r;return n?e:(t.resource_pack=i.resource_pack,t.config=i.config,t.offlineIdle=(null==(r=i.resource_pack)?void 0:r.offline_idle)||[],t.resource_pack&&t.getBackgroundImage(),i)}if(!e)return null;var i=e;t.session_id=null==i?void 0:i.session_id;var s=function(){if(t.destroyed)return Promise.resolve(t.stopSession("destroy_during_reload")).then(function(){return n=1,null})}();return s&&s.then?s.then(r):r(s)})}catch(t){return Promise.reject(t)}},e._setOfflineCache=function(){try{var t=this;if(!t.offlineIdle||0===t.offlineIdle.length)return Promise.resolve();t.offlineCache.clear();var e=t.offlineIdle.map(function(t){return t.n});return Promise.resolve(_forOf$1(e,function(e){var n=_catch$3(function(){return Promise.resolve(t._runOfflineCache(e)).then(function(){})},function(){});if(n&&n.then)return n.then(function(){})}))}catch(t){return Promise.reject(t)}},e._runOfflineCache=function(t){try{var e=this,n=e.getVideoUrl(t);return n?Promise.resolve(e._fetchVideo(n).then(function(n){e.offlineCache.set(t,{data:n.arrayBuffer})})):Promise.resolve()}catch(t){return Promise.reject(t)}},e.destroy=function(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0},t}();function _finallyRethrows$1(t,e){try{var n=t()}catch(t){return e(!0,t)}return n&&n.then?n.then(e.bind(null,!1),e.bind(null,!0)):e(!1,n)}var _iteratorSymbol$1="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function _settle$1(t,e,n){if(!t.s){if(n instanceof _Pact$1){if(!n.s)return void(n.o=_settle$1.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle$1.bind(null,t,e),_settle$1.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var _Pact$1=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){var r=new t,i=this.s;if(i){var s=1&i?e:n;if(s){try{_settle$1(r,1,s(this.v))}catch(t){_settle$1(r,2,t)}return r}return this}return this.o=function(t){try{var i=t.v;1&t.s?_settle$1(r,1,e?e(i):i):n?_settle$1(r,1,n(i)):_settle$1(r,2,i)}catch(t){_settle$1(r,2,t)}},r},t}();function _isSettledPact$1(t){return t instanceof _Pact$1&&1&t.s}function _forTo$1(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact$1(o))return void o.then(a,i||(i=_settle$1.bind(null,r=new _Pact$1,2)));o=o.v}r?_settle$1(r,1,o):r=o}catch(t){_settle$1(r||(r=new _Pact$1),2,t)}}(),r}function _forOf$1(t,e,n){if("function"==typeof t[_iteratorSymbol$1]){var r,i,s,a=function(t){try{for(;!((r=o.next()).done||n&&n());)if((t=e(r.value))&&t.then){if(!_isSettledPact$1(t))return void t.then(a,s||(s=_settle$1.bind(null,i=new _Pact$1,2)));t=t.v}i?_settle$1(i,1,t):i=t}catch(t){_settle$1(i||(i=new _Pact$1),2,t)}},o=t[_iteratorSymbol$1]();if(a(),o.return){var l=function(t){try{r.done||o.return()}catch(t){}return t};if(i&&i.then)return i.then(l,function(t){throw l(t)});l()}return i}if(!("length"in t))throw new TypeError("Object is not iterable");for(var h=[],c=0;c<t.length;c++)h.push(t[c]);return _forTo$1(h,function(t){return e(h[t])},n)}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},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 r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},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 P}),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 _}),n.d(e,"encodeDateToTimeSpec",function(){return v}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return b}),n.d(e,"encodeTimestampExtension",function(){return y}),n.d(e,"decodeTimestampExtension",function(){return S});var r=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return a},i=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,r=0;r<e;){var i=t.charCodeAt(r++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&r<e){var s=t.charCodeAt(r);56320==(64512&s)&&(++r,i=((1023&i)<<10)+(1023&s)+65536)}n+=4294901760&i?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 c(t,e,n){for(var r=e,s=r+n,a=[],o="";r<s;){var l=t[r++];if(128&l)if(192==(224&l)){var h=63&t[r++];a.push((31&l)<<6|h)}else if(224==(240&l)){h=63&t[r++];var c=63&t[r++];a.push((31&l)<<12|h<<6|c)}else if(240==(248&l)){var d=(7&l)<<18|(h=63&t[r++])<<12|(c=63&t[r++])<<6|63&t[r++];d>65535&&(a.push((d-=65536)>>>10&1023|55296),d=56320|1023&d),a.push(d)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,i(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,i(a))),o}var d=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 r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function m(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var _=-1;function g(t){var e,n=t.sec,r=t.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var i=new Uint8Array(4);return(e=new DataView(i.buffer)).setUint32(0,n),i}var s=n/4294967296,a=4294967295&n;return i=new Uint8Array(8),(e=new DataView(i.buffer)).setUint32(0,r<<2|3&s),e.setUint32(4,a),i}return i=new Uint8Array(12),(e=new DataView(i.buffer)).setUint32(0,r),p(e,4,n),i}function v(t){var e=t.getTime(),n=Math.floor(e/1e3),r=1e6*(e-1e3*n),i=Math.floor(r/1e9);return{sec:n+i,nsec:r-1e9*i}}function y(t){return t instanceof Date?g(v(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:m(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:_,encode:y,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,r=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{var i=1+e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(r=this.builtInEncoders[n])&&null!=(i=r(t,e)))return new f(-1-n,i);for(n=0;n<this.encoders.length;n++){var r,i;if(null!=(r=this.encoders[n])&&null!=(i=r(t,e)))return new f(n,i)}return t instanceof f?t:null},t.prototype.decode=function(t,e,n){var r=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return r?r(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],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A=function(){function t(t,e,n,r,i,s,a){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=100),void 0===r&&(r=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,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),r=new DataView(e);n.set(this.bytes),this.view=r,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 r=t.length,i=n,s=0;s<r;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<r){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[i++]=a>>18&7|240,e[i++]=a>>12&63|128,e[i++]=a>>6&63|128):(e[i++]=a>>12&15|224,e[i++]=a>>6&63|128)}else e[i++]=a>>6&31|192;e[i++]=63&a|128}else e[i++]=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,r,i=t.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: "+i);this.writeU8(221),this.writeU32(i)}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&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,r,i=0;try{for(var s=T(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&i++}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},t.prototype.encodeMap=function(t,e){var n,r,i=Object.keys(t);this.sortKeys&&i.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,i):i.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(i),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&&(r=a.return)&&r.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 r=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,r)}(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 P(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 B(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var C=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 r=this.caches[n-1],i=r.length;t:for(var s=0;s<i;s++){for(var a=r[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],r={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},t.prototype.decode=function(t,e,n){var r=this.get(t,e,n);if(null!=r)return r;var i=c(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,i),i},t}(),I=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},k=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={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise(function(r,i){!function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)}(r,i,(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 C,N=function(){function t(t,e,n,r,i,s,a,o){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=4294967295),void 0===r&&(r=4294967295),void 0===i&&(i=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=r,this.maxArrayLength=i,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),r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),this.setBuffer(r)}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,r,i;return function(t,e,n,r){return new(n||(n=Promise))(function(e,i){function s(t){try{o(r.next(t))}catch(t){i(t)}}function a(t){try{o(r.throw(t))}catch(t){i(t)}}function o(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(s,a)}o((r=r.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,h,c,d,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=k(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(),r={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),n&&!n.done&&(i=e.return)?[4,i.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw c=(h=this).headByte,d=h.pos,u=h.totalPos,new RangeError("Insufficient data in parcing "+B(c)+" at "+u+" ("+d+" 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 r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof D?Promise.resolve(n.value.v).then(l,h):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function c(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,r,i,s,a,o,l,h,c;return I(this,function(d){switch(d.label){case 0:n=e,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),i=k(t),d.label=2;case 2:return[4,D(i.next())];case 3:if((s=d.sent()).done)return[3,12];if(a=s.value,e&&0===r)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,D(this.decodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=d.sent())instanceof F))throw o;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=d.sent(),h={error:l},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(c=i.return)?[4,D(c.call(i))]:[3,16];case 15:d.sent(),d.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!=(r=t-128)){this.pushMapState(r),this.complete();continue t}e={}}else if(t<160){if(0!=(r=t-144)){this.pushArrayState(r),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!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(221===t){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(222===t){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue t}e={}}else if(223===t){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue t}e={}}else if(196===t){var r=this.lookU8();e=this.decodeBinary(r,1)}else if(197===t)r=this.lookU16(),e=this.decodeBinary(r,2);else if(198===t)r=this.lookU32(),e=this.decodeBinary(r,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)r=this.lookU8(),e=this.decodeExtension(r,1);else if(200===t)r=this.lookU16(),e=this.decodeExtension(r,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+B(t));r=this.lookU32(),e=this.decodeExtension(r,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;i.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}i.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: "+B(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 r,i=this.pos+e;return r=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,i,t):s&&t>u?function(t,e,n){var r=t.subarray(e,e+n);return d.decode(r)}(this.bytes,i,t):c(this.bytes,i,t),this.pos+=e+t,r},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,r=this.bytes.subarray(n,n+t);return this.pos+=e+t,r},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),r=this.decodeBinary(t,e+1);return this.extensionCodec.decode(r,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=m(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 j=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=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)},H=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof W?Promise.resolve(n.value.v).then(l,h):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function c(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function V(t){return null!=t[Symbol.asyncIterator]?t:function(t){return H(this,arguments,function(){var e,n,r;return j(this,function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,W(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,W(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(r),[4,W(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var $=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function a(t){try{l(r.next(t))}catch(t){s(t)}}function o(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((r=r.apply(t,e||[])).next())})},K=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=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),$(this,void 0,void 0,function(){var n;return K(this,function(r){return n=V(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=V(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=V(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,r)=>withNativeBlob$1&&e instanceof Blob?n?r(e):encodeBlobAsBase64(e,r):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?r(e):encodeBlobAsBase64(new Blob([e]),r):r(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,r,i,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),c=new Uint8Array(h);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],r=lookup$1[t.charCodeAt(e+1)],i=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],c[l++]=n<<2|r>>4,c[l++]=(15&r)<<4|i>>2,c[l++]=(3&i)<<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,r=new Array(n);let i=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{r[s]=t,++i===n&&e(r.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),r=[];for(let t=0;t<n.length;t++){const i=decodePacket(n[t],e);if(r.push(i),"error"===i.type)break}return r};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),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 r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let r=0,i=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===r){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(totalLength(n)<2)break;const t=concatChunks(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){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}i=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(totalLength(n)<i)break;const t=concatChunks(n,i);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),r=0}if(0===i||i>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,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.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],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].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 r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,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,r=n.length;t<r;t++){let r=n[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[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],r=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}r&&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(),r=createPacketEncoderStream();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();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("["),r=t.indexOf("]");-1!=n&&-1!=r&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=i[a]||"";return-1!=n&&-1!=r&&(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,r){e&&(n[e]=r)}),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,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),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 r=()=>{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 i(){n||(n=!0,h(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",r),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 r=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),r=parse(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}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 r=0;r<t.length;r++)n[r]=_deconstructPacket(t[r],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=_deconstructPacket(t[r],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),r=e.buffers;return r.unshift(n),r}}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 r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(r,e)}else n.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=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(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}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:protocol,get PacketType(){return PacketType},Encoder:Encoder,Decoder: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,r,i;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===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._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 r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=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"))},r),s=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(t,e)=>t?r(t):n(e);i.withError=!0,e.push(i),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,...r)=>{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,...r)),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(...r){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:r}))}}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 r=e.parser||parser;this.encoder=new r.Encoder,this.decoder=new r.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 r=on(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",i);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(r),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"),r=n.source,i=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[i]&&n.path in cache[i].nsps?s=new Manager(r,e):(cache[i]||(cache[i]=new Manager(r,e)),s=cache[i]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;function _finallyRethrows(t,e){try{var n=t()}catch(t){return e(!0,t)}return n&&n.then?n.then(e.bind(null,!1),e.bind(null,!0)):e(!1,n)}Object.assign(lookup,{Manager:Manager,Socket: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),r=0,i=2,s=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,a){n[r]=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];i.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 r=Array(64),i=Array(123),s=0;s<64;)i[r[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 i,s=null,a=[],o=0,l=0;e<n;){var h=t[e++];switch(l){case 0:a[o++]=r[h>>2],i=(3&h)<<4,l=1;break;case 1:a[o++]=r[i|h>>4],i=(15&h)<<2,l=2;break;case 2:a[o++]=r[i|h>>6],a[o++]=r[63&h],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=r[i],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 r,s=n,o=0,l=0;l<t.length;){var h=t.charCodeAt(l++);if(61==h&&1<o)break;if((h=i[h])===rt)throw Error(a);switch(o){case 0:r=h,o=1;break;case 1:e[n++]=r<<2|(48&h)>>4,r=h,o=2;break;case 2:e[n++]=(15&r)<<4|(60&h)>>2,r=h,o=3;break;case 3:e[n++]=(3&r)<<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 r=[];function i(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 c=Array(arguments.length-1),d=0;d<c.length;)c[d]=arguments[++d];if(d=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=c[d++];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"%"}),d!==c.length)throw Error("parameter count mismatch");return r.push(e),i}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+r.join("\n ")+"\n}"}return i.toString=s,i}).verbose=!1},{}],4:[function(t,e,n){function r(){this.i={}}(e.exports=r).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},r.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},r.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var r=t(1),i=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&i&&i.readFile?i.readFile(t,function(r,i){return r&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):r?n(r):n(null,e.binary?i:i.toString("utf8"))}):s.xhr(t,e,n):r(s,this,t,e)}s.xhr=function(t,e,n){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(4!==r.readyState)return rt;if(0!==r.status&&200!==r.status)return n(Error("status "+r.status));if(e.binary){if(!(t=r.response))for(var t=[],i=0;i<r.responseText.length;++i)t.push(255&r.responseText.charCodeAt(i));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,r.responseText)},e.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",t),r.send()}},{1:1,7:7}],6:[function(t,e,n){function r(t){function e(t,e,n,r){var i=e<0?1:0;t(0===(e=i?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(i<<31|2139095040)>>>0:e<11754943508222875e-54?(i<<31|Math.round(e/1401298464324817e-60))>>>0:(i<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,r)}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 r(t,e,n){d[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){d[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],d[0]}function c(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],d[0]}var d,u,f,p,m;function _(t,e,n,r,i,s){var a,o=r<0?1:0;0===(r=o?-r:r)?(t(0,i,s+e),t(0<1/r?0:2147483648,i,s+n)):isNaN(r)?(t(0,i,s+e),t(2146959360,i,s+n)):17976931348623157e292<r?(t(0,i,s+e),t((o<<31|2146435072)>>>0,i,s+n)):r<22250738585072014e-324?(t((a=r/5e-324)>>>0,i,s+e),t((o<<31|a/4294967296)>>>0,i,s+n)):(t(4503599627370496*(a=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,i,s+e),t((o<<31|r+1023<<20|1048576*a&1048575)>>>0,i,s+n))}function g(t,e,n,r,i){return e=t(r,i+e),r=2*((t=t(r,i+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(i=t>>>20&2047)?n?NaN:1/0*r:0==i?5e-324*r*n:r*Math.pow(2,i-1075)*(n+4503599627370496)}function v(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 y(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?(d=new Float32Array([-0]),u=new Uint8Array(d.buffer),t.writeFloatLE=(m=128===u[3])?r:l,t.writeFloatBE=m?l:r,t.readFloatLE=m?h:c,t.readFloatBE=m?c:h):(t.writeFloatLE=e.bind(null,i),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=(m=128===p[7])?v:y,t.writeDoubleBE=m?y:v,t.readDoubleLE=m?b:S,t.readDoubleBE=m?S:b):(t.writeDoubleLE=_.bind(null,i,0,4),t.writeDoubleBE=_.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function i(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=r(r)},{}],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 r=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},i=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=r(t);t="",n&&(t=e.shift()+"/");for(var i=0;i<e.length;)".."===e[i]?0<i&&".."!==e[i-1]?e.splice(--i,2):n?e.splice(i,1):++i:"."===e[i]?e.splice(i,1):++i;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=i(e)),!r(e)&&(t=(t=n?t:i(t)).replace(/(?:\/|^)[^/]+$/,"")).length?i(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var r=n||8192,i=r>>>1,s=null,a=r;return function(n){return n<1||i<n?t(n):(r<a+n&&(s=t(r),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,r=0;r<t.length;++r)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(r+1))?(++r,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,s=[],a=0;e<n;)(r=t[e++])<128?s[a++]=r:191<r&&r<224?s[a++]=(31&r)<<6|63&t[e++]:239<r&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(r>>10),s[a++]=56320+(1023&r)):s[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,s)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var r,i,s=n,a=0;a<t.length;++a)(r=t.charCodeAt(a))<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(++a,e[n++]=(r=65536+((1023&r)<<10)+(1023&i))>>18|240,e[n++]=r>>12&63|128):e[n++]=r>>12|224,e[n++]=r>>6&63|128),e[n++]=63&r|128);return n-s}},{}],11:[function(t,e,n){e.exports=i;var r=/\/|\./;function i(t,e){r.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),i[t]=e}i("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),i("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),i("timestamp",{Timestamp:e}),i("empty",{Empty:{fields:{}}}),i("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}}}}),i("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}}}}),i("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),i.get=function(t){return i[t]||null}},{}],12:[function(t,e,n){var r=t(15),i=t(37);function s(t,e,n,i){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(d%s){",i);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}',i,i,i),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",i,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',i)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,n,i);else{var h=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",i,i);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",i,i,h)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":t("m%s=String(d%s)",i,i);break;case"bool":t("m%s=Boolean(d%s)",i,i)}}return t}function a(t,e,n,i){if(e.resolvedType)e.resolvedType instanceof r?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,n,i,i,n,i,i):t("d%s=types[%i].toObject(m%s,o)",i,n,i);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("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",i,i,i,i,s?"true":"",i);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",i,i,i,i,i);break;default:t("d%s=m%s",i,i)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=i.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=i.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 r||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof r||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(i.compareFieldsById);if(!e.length)return i.codegen()("return {}");for(var n=i.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=[]",i.safeProp(s[h].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),h=0;h<o.length;++h)n("d%s={}",i.safeProp(o[h].name));n("}")}if(l.length){for(n("if(o.defaults){"),h=0;h<l.length;++h){var c,d=i.safeProp((f=l[h]).name);f.resolvedType instanceof r?n("d%s=o.enums===String?%j:%j",d,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",d)("}else")("d%s=o.longs===String?%j:%i",d,f.typeDefault.toString(),f.typeDefault.toNumber()):f.bytes?(c="["+Array.prototype.slice.call(f.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",d,String.fromCharCode.apply(String,f.typeDefault))("else{")("d%s=%s",d,c)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",d,d)("}")):n("d%s=%j",d,f.typeDefault)}n("}")}var u=!1;for(h=0;h<e.length;++h){var f,p=t.e.indexOf(f=e[h]);d=i.safeProp(f.name),f.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",d,d)("d%s={}",d)("for(var j=0;j<ks2.length;++j){"),a(n,f,p,d+"[ks2[j]]")("}")):f.repeated?(n("if(m%s&&m%s.length){",d,d)("d%s=[]",d)("for(var j=0;j<m%s.length;++j){",d),a(n,f,p,d+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",d,f.name),a(n,f,p,d),f.partOf&&n("if(o.oneofs)")("d%s=%j",i.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 r?"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"),i.defaults[a.keyType]!==rt?e("k=%j",i.defaults[a.keyType]):e("k=null"),i.defaults[o]!==rt?e("value=%j",i.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:"),i.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(i.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),i.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"),i.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)):i.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 r=t(15),i=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(),c=t.e.indexOf(h),d=h.resolvedType instanceof r?"int32":h.type,u=i.basic[d];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|i.mapKey[h.keyType],h.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",c,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,d,e),n("}")("}")):h.repeated?(n("if(%s!=null&&%s.length){",e,e),h.packed&&i.packed[d]!==rt?n("w.uint32(%i).fork()",(h.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",d,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,h,c,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(h.id<<3|u)>>>0,d,e)),n("}")):(h.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,h.name),u===rt?a(n,h,c,e):n("w.uint32(%i).%s(%s)",(h.id<<3|u)>>>0,d,e))}return n("return w")};var r=t(15),i=t(36),s=t(37);function a(t,e,n,r){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,i,s,a){if(r.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=i,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){var e=this;return r.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(function(t){var n=Object.assign({},e.h);e.o[t]=Object.assign(n,e.valuesOptions&&e.valuesOptions[t]&&e.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,r){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 r&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=r||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 i.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=h;var r,i=t(24),s=(((h.prototype=Object.create(i.prototype)).constructor=h).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function h(t,e,n,r,s,h,c){if(o.isObject(r)?(c=s,h=r,r=s=rt):o.isObject(s)&&(c=h,h=s,s=rt),i.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(r!==rt&&!l.test(r=r.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=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===r,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=c}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 r&&"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 i.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 r?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 r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.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 r&&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 i.prototype.u.call(this,this.f||t)},h.d=function(t,e,n,r){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(i,s){o.decorateType(i.constructor).add(new h(s,t,e,n,{default:r}))}},h.p=function(t){r=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var r=e.exports=t(18);r.build="light",r.load=function(t,e,n){return(e="function"==typeof e?(n=e,new r.Root):e||new r.Root).load(t,n)},r.loadSync=function(t,e){return(e=e||new r.Root).loadSync(t)},r.encoder=t(14),r.decoder=t(13),r.verifier=t(40),r.converter=t(12),r.ReflectionObject=t(24),r.Namespace=t(23),r.Root=t(29),r.Enum=t(15),r.Type=t(35),r.Field=t(16),r.OneOf=t(25),r.MapField=t(20),r.Service=t(33),r.Method=t(22),r.Message=t(21),r.wrappers=t(41),r.types=t(36),r.util=t(37),r.ReflectionObject.p(r.Root),r.Namespace.p(r.Type,r.Service,r.Enum),r.Root.p(r.Type),r.Field.p(r.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 r=n;function i(){r.util.p(),r.Writer.p(r.BufferWriter),r.Reader.p(r.BufferReader)}r.build="minimal",r.Writer=t(42),r.BufferWriter=t(43),r.Reader=t(27),r.BufferReader=t(28),r.util=t(39),r.rpc=t(31),r.roots=t(30),r.configure=i,i()},{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 r=t(16),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,i,a,o){if(r.call(this,t,e,i,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(i.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return r.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(r,i){s.decorateType(r.constructor).add(new a(i,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=i;var r=t(39);function i(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}i.create=function(t){return this.$type.create(t)},i.encode=function(t,e){return this.$type.encode(t,e)},i.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},i.decode=function(t){return this.$type.decode(t)},i.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},i.verify=function(t){return this.$type.verify(t)},i.fromObject=function(t){return this.$type.fromObject(t)},i.toObject=function(t,e){return this.$type.toObject(t,e)},i.prototype.toJSON=function(){return this.$type.toObject(this,r.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var r=t(24),i=(((s.prototype=Object.create(r.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,h,c){if(i.isObject(a)?(l=a,a=o=rt):i.isObject(o)&&(l=o,o=rt),e!==rt&&!i.isString(e))throw TypeError("type must be a string");if(!i.isString(n))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");r.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=c}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 i.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),r.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=d;var r,i,s,a=t(24),o=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Namespace",t(16)),l=t(37),h=t(25);function c(t,e){if(!t||!t.length)return rt;for(var n={},r=0;r<t.length;++r)n[t[r].name]=t[r].toJSON(e);return n}function d(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}d.fromJSON=function(t,e){return new d(t,e.options).addJSON(e.nested)},d.arrayToJSON=c,d.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},d.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(d.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),d.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",c(this.nestedArray,t)])},d.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?r:e.values!==rt?s:e.methods!==rt?i:e.id!==rt?o:d).fromJSON(n[a],e));return this},d.prototype.get=function(t){return this.nested&&this.nested[t]||null},d.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},d.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof r||t instanceof h||t instanceof s||t instanceof i||t instanceof d))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof d&&t instanceof d)||e instanceof r||e instanceof i)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 r||this instanceof i||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)},d.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)},d.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 r=t.shift();if(n.nested&&n.nested[r]){if(!((n=n.nested[r])instanceof d))throw Error("path conflicts with non-namespace objects")}else n.add(n=new d(r))}return e&&n.addJSON(e),n},d.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 d?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},d.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(function(e){e.g(t)})),this},d.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 r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var i=this.root.j&&this.root.j["."+r];if(i&&(!e||~e.indexOf(i.constructor)))return i;if((i=this.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;if(!n)for(var s=this;s.parent;){if((i=s.parent.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;s=s.parent}return null},d.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof d&&(t=t.slice(1),r=n.k(t,t.join(".")));else for(var i=0;i<this.nestedArray.length;++i)this.v[i]instanceof d&&(n=this.v[i].k(t,e))&&(r=n);return this.b[e]=r},d.prototype.lookupType=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such type: "+t)},d.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},d.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[r,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},d.prototype.lookupService=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},d.p=function(t,e,n){r=t,i=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=h).className="ReflectionObject";var r,i=t(25),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 r,i,a=this.parsedOptions;return n?(r=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(i=r[t],n,e):((r={})[t]=s.setProperty({},n,e),a.push(r)):((i={})[t]=e,a.push(i)),this},h.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),r=0;r<n.length;++r)this.setOption(n[r],t[n[r]],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 r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,i){if(Array.isArray(e)||(n=e,e=rt),r.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=i}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 i)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 i))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){r.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);r.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 r=t(34),i=t(29),s=t(35),a=t(16),o=t(20),l=t(25),h=t(15),c=t(33),d=t(22),u=t(24),f=t(36),p=t(37),m=/^[1-9][0-9]*$/,_=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,v=/^-?0[x][0-9a-fA-F]+$/,y=/^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 i||(n=e,e=new i);var T,A,R,P,B,C,I=(n=n||x.defaults).preferTrailingComment||!1,k=r(t,n.alternateCommentMode||!1),D=k.next,U=k.push,O=k.peek,F=k.skip,L=k.cmnt,M=!0,N="proto2",z=e,G=[],j={},W=n.keepCase?function(t){return t}:p.camelCase;function H(t,e,n){var r=x.filename;return n||(x.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(r?r+", ":"")+"line "+k.line+")")}function V(){var t,e=[];do{if('"'!==(t=D())&&"'"!==t)throw H(t)}while(e.push(D()),F(t),'"'===(t=O())||"'"===t);return e.join("")}function $(t){var e=D();switch(e){case"'":case'"':return U(e),V();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,r=1;switch("-"==(n[0]||"")&&(r=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(m.test(n))return r*parseInt(n,10);if(g.test(n))return r*parseInt(n,16);if(y.test(n))return r*parseInt(n,8);if(S.test(n))return r*parseFloat(n);throw H(n,"number",!0)}catch(n){if(t&&w.test(e))return e;throw H(e,"value")}}function K(t,e){var n;do{if(!e||'"'!==(r=O())&&"'"!==r)try{t.push([n=Y(D()),F("to",!0)?Y(D()):n])}catch(n){if(!(e&&w.test(r)&&2023<=N))throw n;t.push(r)}else{var r=V();if(t.push(r),2023<=N)throw H(r,"id")}}while(F(",",!0));var i={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};Z(i,function(t){if("option"!==t)throw H(t);tt(i,t),F(";")},function(){nt(i)})}function Y(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(_.test(t))return parseInt(t,10);if(v.test(t))return parseInt(t,16);if(b.test(t))return parseInt(t,8)}throw H(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,r,i=t;if(E.test(r=D()))return Z(n=new c(r),function(t){if(!X(n,t)){if("rpc"!==t)throw H(t);var e=n,r=L(),i=t;if(!E.test(t=D()))throw H(t,"name");var s,a,o,l=t;if(F("("),F("stream",!0)&&(a=!0),!w.test(t=D()))throw H(t);if(s=t,F(")"),F("returns"),F("("),F("stream",!0)&&(o=!0),!w.test(t=D()))throw H(t);F(")");var h=new d(l,i,s,t,a,o);h.comment=r,Z(h,function(t){if("option"!==t)throw H(t);tt(h,t),F(";")}),e.add(h)}}),i.add(n),i===z&&G.push(n),1;throw H(r,"service name");case"extend":var s,a=t;if(i=e,w.test(i=D()))return s=i,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 H(t);U(t),Q(a,"optional",s)}}),1;throw H(i,"reference")}}function Z(t,e,n){var r,i=k.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=x.filename),F("{",!0)){for(;"}"!==(r=D());)e(r);F(";",!0)}else n&&n(),F(";"),t&&("string"!=typeof t.comment||I)&&(t.comment=L(i)||t.comment)}function q(t,e){if(!E.test(e=D()))throw H(e,"type name");var n=new s(e);Z(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,r=(F("<"),D());if(f.mapKey[r]===rt)throw H(r,"type");F(",");var i=D();if(!w.test(i))throw H(i,"type");F(">");var s=D();if(!E.test(s))throw H(s,"name");F("=");var a=new o(W(s),Y(D()),r,i);Z(a,function(t){if("option"!==t)throw H(t);tt(a,t),F(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==N)throw H(t);case"repeated":Q(n,t);break;case"optional":if("proto3"===N)Q(n,"proto3_optional");else{if("proto2"!==N)throw H(t);Q(n,"optional")}break;case"oneof":if(s=n,r=t,!E.test(r=D()))throw H(r,"name");var h=new l(W(r));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 H(t);U(t),Q(n,"optional")}}),t.add(n),t===z&&G.push(n)}function Q(t,e,n){var r=D();if("group"===r){var i=t,o=e;if(2023<=N)throw H("group");var h,c,d=D();if(E.test(d))return d===(c=p.lcFirst(d))&&(d=p.ucFirst(d)),F("="),u=Y(D()),(h=new s(d)).group=!0,(c=new a(c,u,d,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 H(t)}}),void i.add(h).add(c);throw H(d,"name")}for(;r.endsWith(".")||O().startsWith(".");)r+=D();if(!w.test(r))throw H(r,"type");var u=D();if(!E.test(u))throw H(u,"name");u=W(u),F("=");var f=new a(u,Y(D()),r,e,n);Z(f,function(t){if("option"!==t)throw H(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 H(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,r=t;if(!E.test(r))throw H(r,"name");F("=");var i=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 H(t);tt(s,t),F(";")},function(){nt(s)}),void e.add(r,i,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&&(r=D(),F(")"),e="("+r+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var r=e.split("."),i=r[0]+".";e=r[1];continue}i=e}else a=a?a+e:e;e=D()}var s=function t(e,n){if(F("{",!0)){for(var r={};!F("}",!0);){if(!E.test(P=D()))throw H(P,"name");if(null===P)throw H(P,"end of input");var i,s,a=P;if(F(":",!0),"{"===O())i=t(e,n+"."+P);else if("["===O()){if(i=[],F("[",!0)){for(;s=$(!0),i.push(s),F(",",!0););F("]"),void 0!==s&&et(e,n+"."+P,s)}}else i=$(!0),et(e,n+"."+P,i);var o=r[a];o&&(i=[].concat(o).concat(i)),r[a]=i,F(",",!0),F(";",!0)}return r}var l=$(!0);return et(e,n,l),l}(t,s=a?i.concat(a):i),a=a&&"."===a[0]?a.slice(1):a;i=i&&"."===i[i.length-1]?i.slice(0,-1):i,t.setParsedOption&&t.setParsedOption(i,s,a)}function et(t,e,n){z===t&&/^features\./.test(e)?j[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(F("[",!0)){for(;tt(t,"option"),F(",",!0););F("]")}}for(;null!==(P=D());)switch(P){case"package":if(!M)throw H(P);if(T!==rt)throw H("package");if(T=D(),!w.test(T))throw H(T,"name");z=z.define(T),F(";");break;case"import":if(!M)throw H(P);switch(C=void 0,O()){case"weak":C=R=R||[],D();break;case"public":D();default:C=A=A||[]}B=V(),F(";"),C.push(B);break;case"syntax":if(!M)throw H(P);if(F("="),(N=V())<2023)throw H(N,"syntax");F(";");break;case"edition":if(!M)throw H(P);if(F("="),N=V(),!["2023"].includes(N))throw H(N,"edition");F(";");break;case"option":tt(z,P),F(";",!0);break;default:if(X(z,P)){M=!1;continue}throw H(P)}return G.forEach(function(t){t.f=N,Object.keys(j).forEach(function(e){t.getOption(e)===rt&&t.setOption(e,j[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 r,i=t(39),s=i.LongBits,a=i.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 i.Buffer?function(t){return(l.create=function(t){return i.Buffer.isBuffer(t)?new r(t):d(t)})(t)}:d}var c,d="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._=i.Array.prototype.subarray||i.Array.prototype.slice,l.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;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=i.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=i.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=i.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){r=t,l.create=h(),r.p();var e=i.Long?"toLong":"toNumber";i.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 r=t(27),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.p=function(){i.Buffer&&(s.prototype._=i.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=d;var r,i,s,a=t(23),o=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Root",t(16)),l=t(15),h=t(25),c=t(37);function d(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}d.fromJSON=function(t,e){return e=e||new d,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},d.prototype.resolvePath=c.path.resolve,d.prototype.fetch=c.fetch,d.prototype.load=function t(e,n,r){"function"==typeof n&&(r=n,n=rt);var a=this;if(!r)return c.asPromise(t,a,e,n);var o=r===u;function l(t,e){if(r){if(o)throw t;e&&e.resolveAll();var n=r;r=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 d(t,e){try{if(c.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),c.isString(e)){i.filename=t;var r,s=i(e,a,n),d=0;if(s.imports)for(;d<s.imports.length;++d)(r=h(s.imports[d])||a.resolvePath(t,s.imports[d]))&&f(r);if(s.weakImports)for(d=0;d<s.weakImports.length;++d)(r=h(s.weakImports[d])||a.resolvePath(t,s.weakImports[d]))&&f(r,!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?d(t,s[t]):(++p,setTimeout(function(){--p,d(t,s[t])}));else if(o){var n;try{n=c.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}d(t,n)}else++p,a.fetch(t,function(n,i){--p,r&&(n?e?p||l(null,a):l(n):d(t,i))})}var p=0;c.isString(e)&&(e=[e]);for(var m,_=0;_<e.length;++_)(m=a.resolvePath("",e[_]))&&f(m);return o?a.resolveAll():p||l(null,a),a},d.prototype.loadSync=function(t,e){if(c.isNode)return this.load(t,e,u);throw Error("not supported")},d.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,r=e.parent.lookup(e.extend);if(r)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),r.get(n.name)||((n.declaringField=e).extensionField=n,r.add(n)),1}d.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 r)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 r||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},d.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]},d.p=function(t,e,n){r=t,i=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=i;var r=t(39);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function t(e,n,i,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return r.asPromise(t,o,e,n,i,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 i))try{n=i[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}},i.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 r=t(23),i=(((o.prototype=Object.create(r.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){r.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 r=Object.keys(e.methods),s=0;s<r.length;++s)n.add(i.fromJSON(r[s],e.methods[r[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=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",r.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]||r.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){r.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&&(r.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(function(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 i?l((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof i){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 r.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var r,i=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((r=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");i[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:r,q:r.resolvedRequestType.ctor,s:r.resolvedResponseType.ctor})}return i}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=f;var r=/[\s{}=;:[\],'"()<>]/g,i=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,h=/\s/,c=/\\(.?)/g,d={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(c,function(t,e){switch(e){case"\\":case"":return e;default:return d[e]||""}})}function f(t,e){t=t.toString();var n=0,c=t.length,d=1,f=0,p={},m=[],_=null;function g(t){return Error("illegal "+t+" (line "+d+")")}function v(e){return t[0|e]||""}function y(n,r,i){var s,h={type:t[0|n++]||"",lineEmpty:!1,leading:i},c=n-(i=e?2:3);do{if(--c<0||"\n"==(s=t[0|c]||"")){h.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,r).split(l),m=0;m<u.length;++m)u[m]=u[m].replace(e?o:a,"").trim();h.text=u.join("\n").trim(),p[d]=h,f=d}function b(e){var n=S(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function S(t){for(var e=t;e<c&&"\n"!==v(e);)e++;return e}function E(){if(0<m.length)return m.shift();if(_){var a="'"===_?s:i,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,w(_),_=null,u(o[1]);throw g("string")}var l,f,p,E,x,T=0===n;do{if(n===c)return null;for(l=!1;h.test(p=v(n));)if("\n"===p&&(T=!0,++d),++n===c)return null;if("/"===v(n)){if(++n===c)throw g("comment");if("/"===v(n))if(e){if(x=!1,b((E=n)-1))for(x=!0;(n=S(n))!==c&&(n++,T&&b(n)););else n=Math.min(c,S(n)+1);x&&(y(E,n,T),T=!0),d++}else{for(x="/"===v(E=n+1);"\n"!==v(++n);)if(n===c)return null;++n,x&&(y(E,n-1,T),T=!0),++d}else{if("*"!==(p=v(n)))return"/";E=n+1,x=e||"*"===v(E);do{if("\n"===p&&++d,++n===c)throw g("comment")}while(f=p,p=v(n),"*"!==f||"/"!==p);++n,x&&(y(E,n-2,T),T=!0)}l=!0}}while(l);var A=n;if(r.lastIndex=0,!r.test(v(A++)))for(;A<c&&!r.test(v(A));)++A;return'"'!=(a=t.substring(n,n=A))&&"'"!=a||(_=a),a}function w(t){m.push(t)}function x(){if(!m.length){var t=E();if(null===t)return null;w(t)}return m[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,r=null;return t===rt?(n=p[d-1],delete p[d-1],n&&(e||"*"===n.type||n.lineEmpty)&&(r=n.leading?n.text:null)):(f<t&&x(),n=p[t],delete p[t],!n||n.lineEmpty||!e&&"/"!==n.type||(r=n.leading?null:n.text)),r}},"line",{get:function(){return d}})}f.unescape=u},{}],35:[function(t,e,n){e.exports=v;var r=t(23),i=(((v.prototype=Object.create(r.prototype)).constructor=v).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),h=t(21),c=t(27),d=t(42),u=t(37),f=t(14),p=t(13),m=t(40),_=t(12),g=t(41);function v(t,e){r.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 y(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(v.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]],r=n.id;if(this.S[r])throw Error("duplicate id "+r+" in "+this);this.S[r]=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=v.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 r={};for(n=0;n<this.oneofsArray.length;++n)r[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,r)}}}),v.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),r=0;r<t.fieldsArray.length;++r)(e=t.e[r]).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]]")},v.fromJSON=function(t,e){for(var n=new v(t,e.options),h=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),c=0;c<h.length;++c)n.add((void 0!==e.fields[h[c]].keyType?o:a).fromJSON(h[c],e.fields[h[c]]));if(e.oneofs)for(h=Object.keys(e.oneofs),c=0;c<h.length;++c)n.add(s.fromJSON(h[c],e.oneofs[h[c]]));if(e.nested)for(h=Object.keys(e.nested),c=0;c<h.length;++c){var d=e.nested[h[c]];n.add((d.id!==rt?a:d.fields!==rt?v:d.values!==rt?i:d.methods!==rt?l:r).fromJSON(h[c],d))}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},v.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",r.arrayToJSON(this.oneofsArray,t),"fields",r.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])},v.prototype.resolveAll=function(){if(this.y){r.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},v.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(function(e){e.u(t)}),this.fieldsArray.forEach(function(e){e.u(t)})),this},v.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},v.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),y(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),y(this)):r.prototype.add.call(this,t)},v.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),y(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),y(this);throw Error(t+" is not a member of "+this)}return r.prototype.remove.call(this,t)},v.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},v.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)},v.prototype.create=function(t){return new this.ctor(t)},v.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var r;return this.encode=f(this)({Writer:d,types:e,util:u}),this.decode=p(this)({Reader:c,types:e,util:u}),this.verify=m(this)({types:e,util:u}),this.fromObject=_.fromObject(this)({types:e,util:u}),this.toObject=_.toObject(this)({types:e,util:u}),(t=g[t])&&((r=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(r),r.toObject=this.toObject,this.toObject=t.toObject.bind(r)),this},v.prototype.encode=function(t,e){return this.setup().encode(t,e)},v.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},v.prototype.decode=function(t,e){return this.setup().decode(t,e)},v.prototype.decodeDelimited=function(t){return t instanceof c||(t=c.create(t)),this.decode(t,t.uint32())},v.prototype.verify=function(t){return this.setup().verify(t)},v.prototype.fromObject=function(t){return this.setup().fromObject(t)},v.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},v.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 r=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(t,e){var n=0,i={};for(e|=0;n<t.length;)i[r[n+e]]=t[n++];return i}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var r,i,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),r=0;r<e.length;)n[r]=t[e[r++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var r=t[n++],i=t[n++];i!==rt&&(e[r]=i)}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),c=(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(r=r||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(i=i||t(15))("Enum"+c++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,r){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,i){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,i);else{if((n=e[s])&&r)return e;n&&(i=[].concat(n).concat(i)),e[s]=i}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=i;var r=t(39);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=i.zero=new i(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.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 i(n,t))},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):s},i.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},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);i.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new i((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)},i.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)},i.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},i.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},i.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 r=n;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)t[r[i]]!==rt&&n||(t[r[i]]=e[r[i]]);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&&i(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}r.asPromise=t(1),r.base64=t(2),r.EventEmitter=t(4),r.float=t(6),r.inquire=t(7),r.utf8=t(10),r.pool=t(9),r.LongBits=t(38),r.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),r.global=r.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.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)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r.L=null,r.V=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r.V(t):new r.Array(t):r.Buffer?r.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){return t=r.LongBits.fromHash(t),r.Long?r.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},r.merge=i,r.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},r.newError=s,r.ProtocolError=s("ProtocolError"),r.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]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r.p=function(){var t=r.Buffer;t?(r.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r.V=t.allocUnsafe||function(e){return new t(e)}):r.L=r.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=i.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var r=0;r<t.fieldsArray.length;++r){var o,l=t.e[r].resolve(),h="m"+i.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,r,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,r,h+"[i]")("}")):(l.partOf&&(o=i.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,r,h)),l.optional&&e("}")}return e("return null")};var r=t(15),i=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,i){if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(%s){",i)("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,i)("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))",i)("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)))",i,i,i,i)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var r=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,i,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 r?(n=t.$type.toObject(t,e),i="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+i,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=d;var r,i=t(39),s=i.LongBits,a=i.base64,o=i.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function h(){}function c(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function d(){this.len=0,this.head=new l(h,0,0),this.tail=this.head,this.states=null}function u(){return i.Buffer?function(){return(d.create=function(){return new r})()}:function(){return new d}}function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=rt,this.val=e}function m(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 _(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}d.create=u(),d.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.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},d.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},d.prototype.int32=function(t){return t<0?this.M(m,10,s.fromNumber(t)):this.uint32(t)},d.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(t){return t=s.from(t),this.M(m,t.length(),t)},d.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(m,t.length(),t)},d.prototype.bool=function(t){return this.M(f,1,t?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(t){return this.M(_,4,t>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(t){return t=s.from(t),this.M(_,4,t.lo).M(_,4,t.hi)},d.prototype.float=function(t){return this.M(i.float.writeFloatLE,4,t)},d.prototype.double=function(t){return this.M(i.float.writeDoubleLE,8,t)};var g=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};d.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(i.isString(t)&&(e=d.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(f,1,0)},d.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(f,1,0)},d.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new l(h,0,0),this.len=0,this},d.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},d.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},d.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},d.p=function(t){r=t,d.create=u(),r.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var r=t(42),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=i.V,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.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 r=0;r<t.length;)e[n++]=t[r++]}},s.prototype.bytes=function(t){var e=(t=i.isString(t)?i.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=i.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 r=void 0===e?t.len:t.pos+e,i=new $root.MeshData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.index=t.int32();break;case 2:if(i.weights&&i.weights.length||(i.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.weights.push(t.float());else i.weights.push(t.float());break;default:t.skipType(7&s)}}return i},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 r=0;r<t.weights.length;++r)n.weights[r]=e.json&&!isFinite(t.weights[r])?String(t.weights[r]):t.weights[r]}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 r=void 0===e?t.len:t.pos+e,i=new $root.JointData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(i.translate&&i.translate.length||(i.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.translate.push(t.float());else i.translate.push(t.float());break;case 2:i.rotate=t.bytes();break;default:t.skipType(7&s)}}return i},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 r=0;r<t.translate.length;++r)n.translate[r]=e.json&&!isFinite(t.translate[r])?String(t.translate[r]):t.translate[r]}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 r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.id=t.int32();break;case 2:i.s=t.string();break;case 3:i.sf=t.int32();break;case 4:i.ef=t.int32();break;case 5:i.bsw=t.bytes();break;case 11:i.cs=t.bytes();break;case 12:i.js&&i.js.length||(i.js=[]),i.js.push($root.JointData.decode(t,t.uint32()));break;case 13:i.ms&&i.ms.length||(i.ms=[]),i.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:i.bodyId=t.int32();break;case 15:i.faceFrameType=t.int32();break;case 16:i.asf=t.int32();break;case 17:i.aef=t.int32();break;case 18:i.n=t.string();break;default:t.skipType(7&s)}}return i},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 r=0;r<t.js.length;++r)n.js[r]=$root.JointData.toObject(t.js[r],e)}if(t.ms&&t.ms.length)for(n.ms=[],r=0;r<t.ms.length;++r)n.ms[r]=$root.MeshData.toObject(t.ms[r],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 r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameDataList;t.pos<r;){var s=t.uint32();if(s===n)break;s>>>3==1?(i.data&&i.data.length||(i.data=[]),i.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return i},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 r=0;r<t.data.length;++r)n.data[r]=$root.FaceFrameData.toObject(t.data[r],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}();var 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:"音频数据过期"},Ttsa=/*#__PURE__*/function(){function t(t){var e=this,n=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=function(){n.wsConnectTimer&&(clearTimeout(n.wsConnectTimer),n.wsConnectTimer=0)},this.initWsTimeoutTimer=function(){n.clearOldWsTimeoutTimer(),n.wsConnectTimer=window.setTimeout(function(){try{var t=_finallyRethrows(function(){function t(){n.reStartSDK()}n.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"});var e=function(){if(n.session_id)return Promise.resolve(n.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT")).then(function(){n.ws.disconnect()})}();return e&&e.then?e.then(t):t()},function(t,e){if(n.clearOldWsTimeoutTimer(),t)throw e;return e});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},1e3*(n.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;var r=lookup(t.url,{query:{token:this.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});r.on("connect",function(){n.clearReconnectTimer(),n.initWsTimeoutTimer(),n.startHeartbeat(),n.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);var t={room:n.room,client_type:"web",invisible_mode:n.sdk.getPendingInvisibleMode()};n.send("enter_room",t),n.sdk.getStatus()===AvatarStatus.offline&&n.sdk.getIsInitialized()&&n.reloadSuccess()}),r.on("first_start_timestamp",function(e){window.avatarSDKLogger.log(n.TAG,"first_start_timestamp",e),n.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(n.TAG,"ready"),n.reloadSuccess(),t.onReady()}),r.on("state_change",function(t){n.ttsaStateChangeHandle(t)}),r.on("tts_audio",function(e){try{var r=msgpack_min.decode(e);n.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:r[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(n.TAG,"下发音频数据tts_audio",r),t.handleMessage(EFrameDataType.AUDIO,r)}catch(t){n.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),r.on("face_data",function(n){try{try{if(e.framedata_proto_version){var r,i=new Uint8Array(n),s=pako.inflate(i);r=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,function(){}).toJSON()||{data:[]}).data.map(function(t){var e=(t.js||[]).map(function(t){return{translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]}}),n=(t.ms||[]).map(function(t){return{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,r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",r)}else{var a=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",a),"speak"!==a[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,a)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}return Promise.resolve()}catch(n){return Promise.reject(n)}}),r.on("body_data",function(e){try{var r=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,r[0].s);var i=r.map(function(t){return _extends({},t,{x_offset:[]})});window.avatarSDKLogger.log(n.TAG,"body_data",JSON.stringify(i),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,r)}catch(t){n.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),r.on("event_data",function(e){try{var r=msgpack_min.decode(e);window.avatarSDKLogger.log(n.TAG,"event_data",JSON.stringify(r)),t.handleMessage(EFrameDataType.EVENT,r)}catch(t){n.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),r.on("sync_frame",function(e){t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),r.on("aa_frame",function(e){window.avatarSDKLogger.log(n.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),r.on("error_message",function(t){n.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),r.on("disconnect",function(e){n.clearOldWsTimeoutTimer(),n.stopHeartbeat(),"io client disconnect"!==e&&(n.enterOfflineFlag?window.avatarSDKLogger.warn(n.TAG,"已在离线处理中,忽略重复的disconnect事件"):(n.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:"client Warning: socket disconnect, "+e}),window.avatarSDKLogger.warn(n.TAG,t.url+" 已断开","disconnect原因",e),n.enterOfflineFlag=!0,n.sdk.getStatus()===AvatarStatus.offline?n.sdk.onStatusChange(AvatarStatus.offline):n.enterOfflineMode(),-1===n.socketReconnectTimer&&n.reconnect_timeout>0&&(n.socketReconnectTimer=window.setTimeout(function(){try{r.disconnect()}catch(t){window.avatarSDKLogger.warn(n.TAG,"disconnect error",t)}n.socketReconnectTimer=-1},1e3*n.reconnect_timeout)),-1===n.reconnectTimer&&(n.reconnectTimer=window.setTimeout(function(){try{try{r.disconnect()}catch(t){window.avatarSDKLogger.warn(n.TAG,"disconnect error",t)}return Promise.resolve(n.sdk.stopSessionFromSocket("WS_TIMEOUT")).then(function(){n.reStartSDK()})}catch(t){return Promise.reject(t)}},1e3*n.reconnect_client_timeout))))}),r.on("client_quit",function(t){window.avatarSDKLogger.warn(n.TAG,"client_quit","断开原因",t),r.disconnect(),n.session_speak_req_id=0,Object.keys(t).length&&n.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)?(n.sdk.destroyClient(),n.sdk.onStatusChange(AvatarStatus.close)):(n.sdk.getStatus()===AvatarStatus.offline?n.sdk.onStatusChange(AvatarStatus.offline):n.enterOfflineMode(),n.reStartSDK())}),r.on("connect_error",function(t){n.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),r.onAny(function(t,e){n.ws.connected&&n.initWsTimeoutTimer()}),this.ws=r}var e=t.prototype;return e.clearReconnectTimer=function(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()},e.clearSocketReconnectTimer=function(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)},e.startHeartbeat=function(){var t=this;this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(function(){t.send("client_heartbeat",{timestamp:Date.now(),frame:t.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)},e.stopHeartbeat=function(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)},e.start=function(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")},e.idle=function(){this.stateChange("idle")},e.listen=function(){this.stateChange("listen")},e.think=function(){this.stateChange("think")},e.interactiveidle=function(){this.stateChange("interactive_idle")},e.enterInvisibleMode=function(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})},e.exitInvisibleMode=function(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})},e.firstStartTimestamp=function(t){var e=Date.now()/1e3,n={server_time:t,client_time:e},r=this._getResumeInfo();this._isResume&&r&&r.client_frame>0?n.resume_from_offline_idle=r:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)},e.syncTimestamp=function(){var t=this;this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(function(){var e=Date.now();if(e-t.lastSyncTime>=t.SYNC_INTERVAL){var n=t.getCurrentFrameIndex();t.sendSyncTimestamp(n),t.lastSyncTime=e}},this.syncTimestampNum)},e.sendSyncTimestamp=function(t){var e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})},e.sendText=function(t,e,n,r){var i;if(void 0===r&&(r={client_speak_id:""}),this.ws.connected){var s=this.getUniqueSpeakId();null!=(i=r)&&i.client_speak_id||(r.client_speak_id=s);var a={ssml:t,is_start:e,is_end:n,extra:r,multi_turn_conversation_id:s,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.0.0-beta.16"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},r,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:s,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",a),s}},e.sendSdkPoint=function(t,e,n){void 0===e&&(e={}),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.0.0-beta.16"}))},e.stateChange=function(t,e){var 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)},e.sendPerfLog=function(t){},e.changeLayout=function(t){this.send("change_layout",t)},e.changeWalkConfig=function(t){this.send("walk_config",t)},e.send=function(t,e){this.ws.connected&&this.ws.emit(t,e)},e.sendDeviceInfo=function(t){this.send("stat_report",t)},e.getStatus=function(){return this.ws.connected},e._setResumeInfoCallback=function(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e},e._getResumeInfo=function(){if(this.getResumeInfo){var t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null},e.updateUniqueSpeakId=function(){this._uniqueSpeakId+=1},e.getUniqueSpeakId=function(){return this._uniqueSpeakId+"-"+this.session_id},e.close=function(){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)},e.connect=function(){this.ws.connect()},e.seekToFrame=function(t){this.ws.emit("seek_to_frame",{frame:t})},t}();function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{var 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}}var DebugOverlay=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.setAudioInfo=function(t){this.audioInfo=t},e.setEventData=function(t){this.eventInfo=t},e.addError=function(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()},e.show=function(){var t=this;this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(function(){return t.updateTextOnly()},200)),this.updateTextOnly()},e.hide=function(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)},e.destroy=function(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null},e.setVideoInfo=function(t){this.videoInfo=t},e.updateTextOnly=function(){var t,e;if(this.container){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());var 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))}},e.setText=function(t,e){var n=this.domRefs[t];n&&(n.innerHTML=e)},e.copySessionId=function(){var t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(function(){}).catch(function(t){console.warn("复制失败",t)})},e.createOverlay=function(){var t,e=this;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";var n=function(t,n,r){void 0===r&&(r="");var i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML='<span style="color:#888;font-size:11px;">'+n+":</span>";var s=document.createElement("span");return s.style.color="#fff",s.style.fontSize="11px",s.style.marginLeft="4px",s.textContent=r,i.append(s),e.domRefs[t]=s,i},r=document.createElement("h3");r.textContent="🔍 调试信息",r.style.margin="0 0 12px 0",r.style.color="#00ff88",r.style.fontSize="14px";var i=document.createElement("div");i.append(r,n("look_name","角色look_name"),n("video_name","当前视频"),function(){var t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";var n=document.createElement("span");n.style.color="#888",n.style.fontSize="11px",n.textContent="会话 ID:";var r=document.createElement("span");r.style.color="#fff",r.style.fontSize="11px",r.style.wordBreak="break-all",r.style.flex="1",e.domRefs.session_id=r;var 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=function(){return e.copySessionId()},t.append(n,r,i),t}(),n("frame_idx","当前帧"),n("audio_info","下发音频"),n("event_info","下发事件"),n("fps","FPS"));var s=document.createElement("div");s.style.marginBottom="8px",s.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';var a=document.createElement("div");a.style.fontSize="11px",a.style.background="rgba(0,0,0,0.2)",a.style.padding="4px",a.style.borderRadius="4px",a.style.color="#fff",this.domRefs.perf=a,i.append(s,a);var o=document.createElement("div");o.style.borderTop="1px solid #444",o.style.paddingTop="8px",o.style.marginBottom="8px";var l=document.createElement("h4");l.style.margin="0 0 6px 0",l.style.fontSize="12px",l.style.color="#888";var h=document.createElement("span");this.domRefs.error_count=h,l.append("✅ 错误日志 ",h),o.append(l);var c=function(t){var n=document.createElement("pre");return n.style.margin="0 0 4px 0",n.style.padding="6px",n.style.background="rgba(255,255,255,0.05)",n.style.borderRadius="4px",n.style.fontSize="10px",n.style.lineHeight="1.3",n.style.color="#888",n.style.maxHeight="120px",n.style.overflowY="auto",n.style.whiteSpace="pre-wrap",e.domRefs[t]=n,n},d=c("error_log"),u=c("ttsa_error_log");o.append(d,u),i.append(o),i.append(n("mem","内存占用"),n("session_start","会话开始时间"),n("session_duration","会话时长"),n("network","网络信息")),this.container.append(i),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)},e.formatErrors=function(t){var e=this.errors;return 0===(e=e.filter(t?function(t){return t.code===EErrorCode.TTSA_ERROR}:function(t){return t.code!==EErrorCode.TTSA_ERROR})).length?"暂无错误":e.map(function(t){return"["+new Date(t.timestamp).toLocaleTimeString()+"] "+t.code+": "+t.message}).join("\n")},e.updatePerfMetrics=function(){if(window.performanceTracker)for(var t=window.performanceTracker.getVideoMetrics(),e=0,n=Object.entries(t);e<n.length;e++){var r,i=n[e],s=i[0],a=i[1],o=null!=(r=null==a?void 0:a.time)?r:0;this.perfMetrics[s]||(this.perfMetrics[s]={times:[],avg:0,last:0,count:0});var l=this.perfMetrics[s];l.times.push(o),l.last=o,l.count++,l.avg=l.times.reduce(function(t,e){return t+e},0)/l.times.length}},e.formatPerfMetrics=function(){var t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(function(t){var e=t[1];return t[0]+": 最近:"+e.last.toFixed(2)+"ms 平均:"+e.avg.toFixed(2)+"ms 次数:"+e.count}).join("<br>"):"暂无数据"},e.formatMemory=function(){var 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"},e.trackFPS=function(){var t=this,e=function(n){t.frameCount++,n-t.lastFpsUpdate>=1e3&&(t.fps=t.frameCount,t.frameCount=0,t.lastFpsUpdate=n),requestAnimationFrame(e)};requestAnimationFrame(e)},e.updateMemory=function(){var t;if(null!=(t=window.performance)&&t.memory){var e=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}}},e.trackMemory=function(){var t,e=this;null!=(t=window.performance)&&t.memory&&setInterval(function(){return e.updateMemory()},1e3)},e.getNetworkInfo=function(){var t=navigator.connection;return t?"类型:"+t.effectiveType+" 下行:"+t.downlink+"Mbps 延迟:"+t.rtt+"ms":"N/A"},e.applyStyles=function(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"},e.enableDrag=function(t){var e=!1,n=0,r=0,i=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",function(a){e=!0,n=a.clientX,r=a.clientY,i=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",function(a){e&&(t.style.left=i+a.clientX-n+"px",t.style.top=s+a.clientY-r+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",function(){e=!1,document.body.style.userSelect=""})},t}(),NetworkMonitor=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e._initEventListeners=function(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)},e._handleOnline=function(){window.clearTimeout(this.retryTimer),t.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")},e._handleOffline=function(){t.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()},e._attempt=function(){var t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(function(){},t)},e.setState=function(e){t.ONLINE=e},e.destroy=function(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1},t}();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;var isLoggingEnabled=!1;function executeLog(t){isLoggingEnabled&&"function"==typeof t&&t.apply(void 0,[].slice.call(arguments,1))}var sdkLog={log:function(){return executeLog.apply(void 0,[console.log].concat([].slice.call(arguments)))},info:function(){return executeLog.apply(void 0,[console.info].concat([].slice.call(arguments)))},warn:function(){return executeLog.apply(void 0,[console.warn].concat([].slice.call(arguments)))},error:function(){return executeLog.apply(void 0,[console.error].concat([].slice.call(arguments)))}};function setLoggingEnabled(t){isLoggingEnabled=t,t?console.log("[AVATAR SDK] version:","2.0.0-beta.16","日志已启用"):console.log("[AVATAR SDK] version:","2.0.0-beta.16","日志已禁用")}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){for(var n=t.char,r=n.evalSkeleton(),i=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length),a=0;a<n.skeleton.length;a++){var o=i[a].apply(r[a].inv());s[a]=o.homogeneous_matrix()}for(var l=[],h=0;h<n.mesh.length;h++){for(var c=[],d=0;d<n.mesh[h].blendshapes.size[0];d++){for(var u=[],f=n.mesh[h].vertices,p=n.mesh[h].blendshapes,m=e.blendshapeWeights,_=0;_<3;_++)u.push(f.data[d*f.size[1]+_]);for(var g=0;g<n.mesh[h].blendshapeIndices.length;g++)for(var v=0;v<3;v++)u[v]+=m[n.mesh[h].blendshapeIndices[g]]*Number(p.data[(d*p.size[1]+v)*p.size[2]+g]);u.push(1);for(var y=[0,0,0,0],b=n.mesh[h].jointIndex,S=n.mesh[h].jointWeight,E=0;E<n.maxJointsPerVertex;E++){var w=b[d*n.maxJointsPerVertex+E];if(w<n.skeleton.length)for(var x=mvmul(s[w],u),T=0;T<4;T++)y[T]+=S[d*n.maxJointsPerVertex+E]*x[T]}for(var A=0;A<3;A++)y[A]/=y[3];c.push([y[0],y[1],y[2]])}l.push(c)}return l}function getPCATextures(t,e){for(var n=t.char,r=[],i=0;i<n.mesh.length;i++){var s=n.mesh[i].textureModels[e.mesh[i].textureModelIndex],a=[],o=new Uint8ClampedArray(s.data.size[1]*s.data.size[2]*4),l=1;s.scalingFactor&&(l*=Number(s.scalingFactor.data[0]));for(var h=0;h<s.data.size[1];h++){for(var c=[],d=0;d<s.data.size[2];d++){for(var u=[],f=0;f<3;f++)u.push(l*sampleUniformPCATensor(s.data.data,3*(h*s.data.size[2]+d)+f));c.push(u)}a.push(c)}for(var p=1;p<s.data.size[0];p++){var m=e.mesh[i].texturePCAWeights[p-1];s.scalingFactor&&(m*=Number(s.scalingFactor.data[p]));for(var _=0;_<s.data.size[1];_++)for(var g=0;g<s.data.size[2];g++)for(var v=0;v<3;v++)a[_][g][v]+=m*sampleUniformPCATensor(s.data.data,3*((p*s.data.size[1]+_)*s.data.size[2]+g)+v)}for(var y=0;y<s.data.size[1];y++)for(var b=0;b<s.data.size[2];b++){for(var S=0;S<3;S++)o[4*(y*s.data.size[2]+b)+S]=Math.round(255*a[s.data.size[1]-1-y][b][2-S]);o[4*(y*s.data.size[2]+b)+3]=255}r.push(new ImageData(o,s.data.size[1],s.data.size[2]))}return r}function exportAsWavefrontObj(t){for(var e,n="",r="",i=1,s=0,a=_createForOfIteratorHelperLoose(t);!(e=a()).done;){for(var o,l=e.value,h=_createForOfIteratorHelperLoose(l.vertices);!(o=h()).done;){var c=o.value;n+="v "+c[0]+" "+c[1]+" "+c[2]+"\n"}for(var d,u=_createForOfIteratorHelperLoose(l.uv);!(d=u()).done;){var f=d.value;n+="vt "+f[0]+" "+f[1]+"}\n"}r+="g Obj"+s+"\n";for(var p,m=_createForOfIteratorHelperLoose(l.polygons);!(p=m()).done;)r+="f "+p.value.map(function(t){return(t+i).toString()}).map(function(t){return t+"/"+t}).join(" ")+"\n";i+=l.vertices.length,s+=1}return n+r}function getWavefrontObjFromVertices(t,e){function n(t,e){for(var n=[],r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,r));return n}function r(t,e){for(var n=[],r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(Number(t[r]));return n}for(var i=t.char,s=[],a=0;a<i.mesh.length;a++)s.push({vertices:e[a],uv:n(i.mesh[a].UVCoord.data,2),polygons:r(i.mesh[a].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});var StreamingClient=/*#__PURE__*/function(){function t(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}var e=t.prototype;return e.connect=function(){var t=this;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=function(){t.connected=!0,t.retryCount=0,console.log("[StreamingClient] 已连接"),t.send({type:"join",role:"client"})},this.ws.onmessage=function(e){var n;try{n=JSON.parse(e.data)}catch(t){return}t.handleMessage(n)},this.ws.onclose=function(){t.connected=!1,t.destroyed||(null==t.options.onDisconnect||t.options.onDisconnect(),t.scheduleRetry())},this.ws.onerror=function(){null==t.options.onError||t.options.onError("WebSocket 连接错误")}}},e.handleMessage=function(t){var e,n,r,i,s,a,o,l,h,c;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(r=(i=this.options).onOffer)||r.call(i,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=(c=this.options).onError)||h.call(c,t.message||"未知错误")}},e.send=function(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))},e.sendApiCall=function(t,e){void 0===e&&(e=[]),this.send({type:"api_call",method:t,params:e})},e.scheduleRetry=function(){var t=this;if(!this.destroyed){var e,n;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(e=(n=this.options).onError)||e.call(n,"连接重试次数已达上限"));var r=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(function(){t.connect()},r)}},e.isConnected=function(){return this.connected},e.destroy=function(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1},t}(),VideoPlayer=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.createVideoElement=function(){var 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)},e.createCanvasElement=function(){var 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);var 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)},e.handleOffer=function(t){try{var e=this;return e.destroyPeer(),e.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"}]}),e.pc.onicecandidate=function(t){t.candidate&&e.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},e.pc.ontrack=function(t){console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),e.stream||(e.stream=new MediaStream,e.video&&(e.video.srcObject=e.stream)),e.stream.addTrack(t.track),"audio"===t.track.kind&&e.video&&(e.video.muted=!1,e.video.play().catch(function(){})),"video"===t.track.kind&&e.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),e.startAlphaRendering())},e.pc.onconnectionstatechange=function(){e.pc&&(console.log("[VideoPlayer] WebRTC 状态:",e.pc.connectionState),"connected"===e.pc.connectionState?null==e.options.onConnected||e.options.onConnected():"disconnected"!==e.pc.connectionState&&"failed"!==e.pc.connectionState||null==e.options.onDisconnected||e.options.onDisconnected())},Promise.resolve(e.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}))).then(function(){return Promise.resolve(e.pc.createAnswer()).then(function(t){return Promise.resolve(e.pc.setLocalDescription(t)).then(function(){e.options.streamingClient.send({type:"answer",sdp:t.sdp})})})})}catch(t){return Promise.reject(t)}},e.startAlphaRendering=function(){var t=this;if(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx){var e=this.video,n=this.canvas,r=this.canvasCtx,i=this.tempCanvas,s=this.tempCtx,a=0,o=0,l=0,h=null;h=setInterval(function(){t.destroyed?h&&clearInterval(h):console.log("[VideoPlayer] Alpha 渲染调试: frames="+l+", videoReadyState="+e.readyState+", videoSize="+e.videoWidth+"x"+e.videoHeight+", currentTime="+e.currentTime.toFixed(2)+"s, paused="+e.paused)},2e3);var c=function(){if(t.destroyed)h&&clearInterval(h);else{if(e.readyState>=2&&e.videoWidth>0){var d=e.videoWidth,u=e.videoHeight,f=d/2,p=u;d===a&&u===o||(n.width=f,n.height=p,i.width=d,i.height=p,a=d,o=u,console.log("[VideoPlayer] Alpha Mask: 检测到双流 "+d+"x"+u+" → 原始 "+f+"x"+p)),s.clearRect(0,0,2*f,p),s.drawImage(e,0,0),r.clearRect(0,0,f,p),r.drawImage(i,0,0,f,p,0,0,f,p);try{var m=r.getImageData(0,0,f,p),_=s.getImageData(f,0,f,p),g=m.data,v=_.data;if(0===l){for(var y=0,b=0,S=Math.min(1e3,g.length/4),E=0;E<4*S;E+=4)(g[E]>0||g[E+1]>0||g[E+2]>0)&&y++,v[E]>0&&b++;console.log("[VideoPlayer] 首帧像素检查: RGB非零="+y+"/"+S+", Alpha非零="+b+"/"+S),0===y&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(var w=0;w<g.length;w+=4)g[w+3]=v[w];r.putImageData(m,0,0),l++}catch(t){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",t),r.drawImage(e,0,0,f,p,0,0,f,p),l++}}t.animFrameId=requestAnimationFrame(c)}};this.animFrameId=requestAnimationFrame(c)}},e.addIceCandidate=function(t){try{var e=this,n=function(){if(e.pc)return Promise.resolve(e.pc.addIceCandidate(t).catch(function(t){console.warn("[VideoPlayer] addIceCandidate 失败:",t)})).then(function(){})}();return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.getVideoElement=function(){return this.video},e.getCanvasElement=function(){return this.canvas},e.isConnected=function(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)},e.destroyPeer=function(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)},e.destroy=function(){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},t}(),EventDispatcher=/*#__PURE__*/function(){function t(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}var e=t.prototype;return e.dispatch=function(t,e,n){var r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x,T,A,R,P;switch(t){case"state_change":null==(r=(i=this.callbacks).onStateChange)||r.call(i,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=(c=this.callbacks).onStatusChange)||h.call(c,e.status);break;case"render_change":null==(d=(u=this.callbacks).onRenderChange)||d.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)||m.call(_,e);break;case"message":case"error":null==(g=(v=this.callbacks).onMessage)||g.call(v,e);break;case"network_info":null==(y=(b=this.callbacks).onNetworkInfo)||y.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=(P=this.callbacks).onFrameDataUpdate)||R.call(P,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}},e.getSubtitleText=function(){return this.subtitleText},e.isSubtitleVisible=function(){return this.subtitleVisible},t}(),APIForwarder=/*#__PURE__*/function(){function t(t){this.client=t}var e=t.prototype;return e.speak=function(t,e,n,r){void 0===e&&(e=!0),void 0===n&&(n=!0),void 0===r&&(r={}),this.client.sendApiCall("speak",[t,e,n,r])},e.idle=function(){this.client.sendApiCall("idle",[])},e.listen=function(){this.client.sendApiCall("listen",[])},e.think=function(){this.client.sendApiCall("think",[])},e.interactiveidle=function(){this.client.sendApiCall("interactiveidle",[])},e.interrupt=function(t){this.client.sendApiCall("interrupt",[t])},e.changeLayout=function(t){this.client.sendApiCall("changeLayout",[t])},e.changeWalkConfig=function(t){this.client.sendApiCall("changeWalkConfig",[t])},e.setVolume=function(t){this.client.sendApiCall("setVolume",[t])},e.changeAvatarVisible=function(t){this.client.sendApiCall("changeAvatarVisible",[t])},e.switchInvisibleMode=function(){this.client.sendApiCall("switchInvisibleMode",[])},e.destroy=function(t){void 0===t&&(t="user"),this.client.sendApiCall("destroy",[t])},e.init=function(t){this.client.send({type:"init",config:t})},t}();function _catch$2(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var _iteratorSymbol="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function _settle(t,e,n){if(!t.s){if(n instanceof _Pact){if(!n.s)return void(n.o=_settle.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle.bind(null,t,e),_settle.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var _Pact=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){var r=new t,i=this.s;if(i){var s=1&i?e:n;if(s){try{_settle(r,1,s(this.v))}catch(t){_settle(r,2,t)}return r}return this}return this.o=function(t){try{var i=t.v;1&t.s?_settle(r,1,e?e(i):i):n?_settle(r,1,n(i)):_settle(r,2,i)}catch(t){_settle(r,2,t)}},r},t}();function _isSettledPact(t){return t instanceof _Pact&&1&t.s}function _forTo(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact(o))return void o.then(a,i||(i=_settle.bind(null,r=new _Pact,2)));o=o.v}r?_settle(r,1,o):r=o}catch(t){_settle(r||(r=new _Pact),2,t)}}(),r}function _forOf(t,e,n){if("function"==typeof t[_iteratorSymbol]){var r,i,s,a=function(t){try{for(;!((r=o.next()).done||n&&n());)if((t=e(r.value))&&t.then){if(!_isSettledPact(t))return void t.then(a,s||(s=_settle.bind(null,i=new _Pact,2)));t=t.v}i?_settle(i,1,t):i=t}catch(t){_settle(i||(i=new _Pact),2,t)}},o=t[_iteratorSymbol]();if(a(),o.return){var l=function(t){try{r.done||o.return()}catch(t){}return t};if(i&&i.then)return i.then(l,function(t){throw l(t)});l()}return i}if(!("length"in t))throw new TypeError("Object is not iterable");for(var h=[],c=0;c<t.length;c++)h.push(t[c]);return _forTo(h,function(t){return e(h[t])},n)}function _for(t,e,n){for(var r;;){var i=t();if(_isSettledPact(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!_isSettledPact(s)){r=1;break}s=s.s}if(e){var a=e();if(a&&a.then&&!_isSettledPact(a)){r=2;break}}}var o=new _Pact,l=_settle.bind(null,o,2);return(0===r?i.then(c):1===r?s.then(h):a.then(d)).then(void 0,l),o;function h(r){s=r;do{if(e&&(a=e())&&a.then&&!_isSettledPact(a))return void a.then(d).then(void 0,l);if(!(i=t())||_isSettledPact(i)&&!i.v)return void _settle(o,1,s);if(i.then)return void i.then(c).then(void 0,l);_isSettledPact(s=n())&&(s=s.v)}while(!s||!s.then);s.then(h).then(void 0,l)}function c(t){t?(s=n())&&s.then?s.then(h).then(void 0,l):h(s):_settle(o,1,s)}function d(){(i=t())?i.then?i.then(c).then(void 0,l):c(i):_settle(o,1,s)}}function checkSecureContextSync(){var t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{var t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};var 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(){var t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,r=void 0!==window.MediaSource,i={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:r,hasMediaSource:r}};return n||r?{name:"audio",supported:!0,severity:"fatal",detail:i}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:i}}function checkWebCodecsSync(){var 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(){var t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}var checkCapability=function(t){void 0===t&&(t=!1);try{var e,n=function(t){return e?t:Promise.resolve(Promise.all([Promise.resolve(r.items.find(function(t){return"secureContext"===t.name})),Promise.resolve(r.items.find(function(t){return"webgl2"===t.name})),Promise.resolve(r.items.find(function(t){return"audio"===t.name})),checkWebCodecsDetailed(),checkWorkerDetailed()])).then(function(t){var e=t.filter(function(t){return"fatal"===t.severity&&!t.supported}).length;return{supported:0===e,fatalCount:e,warnCount:t.filter(function(t){return"warn"===t.severity&&!t.supported}).length,items:t}})},r=checkCapabilitySync(t),i=function(){if(t)return Promise.resolve(Promise.all([Promise.resolve(r.items.find(function(t){return"secureContext"===t.name})),Promise.resolve(r.items.find(function(t){return"audio"===t.name})),checkWorkerDetailed()])).then(function(t){var n=t.filter(function(t){return"fatal"===t.severity&&!t.supported}).length,r=t.filter(function(t){return"warn"===t.severity&&!t.supported}).length;return e=1,{supported:0===n,fatalCount:n,warnCount:r,items:t}})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(t){return Promise.reject(t)}},checkWorkerDetailed=function(){try{var t,e=function(e){return t?e:{name:"worker",supported:!1,severity:"warn",reason:"Web Worker 创建超时(已重试 "+WORKER_CHECK_MAX_ATTEMPTS+" 次)",detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}};if("undefined"==typeof Worker)return Promise.resolve({name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"});var n=1,r=_for(function(){return!t&&n<=WORKER_CHECK_MAX_ATTEMPTS},function(){return!!(n+=1)},function(){return Promise.resolve(probeWorkerExecution()).then(function(e){return"supported"===e.status?(t=1,{name:"worker",supported:!0,severity:"fatal",detail:{attempts:n}}):"failed"===e.status?(t=1,{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}):void 0})});return Promise.resolve(r&&r.then?r.then(e):e(r))}catch(t){return Promise.reject(t)}},checkWebCodecsDetailed=function(){try{return Promise.resolve(_catch$2(function(){function t(){var t=s||a,n=o&&!t?"warn":"fatal";return{name:"webcodecs",supported:t,severity:n,reason:t?void 0:"warn"===n?"WebCodecs 探测异常(运行时将以实际视频配置二次确认)":"浏览器不支持 H.264 解码(默认/软解配置均不可用)",detail:{hasVideoDecoder:e,isAndroid:r,hardwareAcceleration:r?"prefer-software":"default",codecSupport:i}}}var e=void 0!==window.VideoDecoder;if(!e)return{name:"webcodecs",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:e}};var n=(navigator.userAgent||"").toLowerCase(),r=/android/.test(n)||/openharmony|arkweb/.test(n),i={},s=!1,a=!1,o=!1,l=_forOf(["avc1.42E01E","avc1.4D001F","avc1.64001F"],function(t){var e=_catch$2(function(){return Promise.resolve(window.VideoDecoder.isConfigSupported({codec:t,codedWidth:2160,codedHeight:1920})).then(function(e){function n(){i[t]={default:o,software:l}}var o=!(null==e||!e.supported);o&&(a=!0);var l=null,h=function(){if(r){var e=function(){l&&(s=!0)},n=_catch$2(function(){return Promise.resolve(window.VideoDecoder.isConfigSupported({codec:t,codedWidth:2160,codedHeight:1920,hardwareAcceleration:"prefer-software"})).then(function(t){l=!(null==t||!t.supported)})},function(){l=!1});return n&&n.then?n.then(e):e()}o&&(s=!0)}();return h&&h.then?h.then(n):n()})},function(){o=!0,i[t]={default:!1,software:null,error:"probe-failed"}});if(e&&e.then)return e.then(function(){})});return l&&l.then?l.then(t):t()},function(t){return{name:"webcodecs",supported:!1,severity:"fatal",reason:"WebCodecs 探测失败",detail:t}}))}catch(t){return Promise.reject(t)}};function checkCapabilitySync(t){void 0===t&&(t=!1);var e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkWorkerSync());var n=e.filter(function(t){return"fatal"===t.severity&&!t.supported}).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(function(t){return"warn"===t.severity&&!t.supported}).length,items:e}}var WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(function(t){var e=null,n=null,r=!1,i=null,s=function(s){var a;r||(r=!0,null!==i&&clearTimeout(i),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{var a=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(a),(e=new Worker(n)).onmessage=function(t){s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=function(t){s({status:"failed",reason:"Web Worker 创建失败",detail:t})},i=setTimeout(function(){s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}function _catch$1(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var 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}}}var WebCodecOpusEncoder=/*#__PURE__*/function(){function t(t){void 0===t&&(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)}t.isSupported=function(){try{return"undefined"==typeof AudioEncoder?Promise.resolve(!1):Promise.resolve(_catch$1(function(){return Promise.resolve(AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}))).then(function(t){var e;return!0===t.supported&&(null==(e=t.config)||null==(e=e.opus)?void 0:e.frameDuration)===OPUS_FRAME_DURATION_US})},function(){return!1}))}catch(t){return Promise.reject(t)}};var e=t.prototype;return e.init=function(){try{var t=this;return t.isInitialized||(t.encoder=t.createEncoder(),t.isInitialized=!0),Promise.resolve()}catch(t){return Promise.reject(t)}},e.encode=function(t){try{var e=this;if(!e.isInitialized||!e.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(e.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));var n=new Int16Array(t),r=e.timestamp,i=Math.round(1e6*t.length/e.config.sampleRate),s=r+i,a=i/OPUS_FRAME_DURATION_US;if(!Number.isInteger(a))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));var o=new AudioData({format:"s16",sampleRate:e.config.sampleRate,numberOfFrames:n.length,numberOfChannels:e.config.channels,timestamp:r,data:n}),l=new Promise(function(t,n){var i=globalThis.setTimeout(function(){e.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);e.pendingEncode={startTimestampUs:r,endTimestampUs:s,expectedFrameCount:a,chunks:[],resolve:t,reject:n,timeoutId:i}});try{e.encoder.encode(o),e.timestamp=s}catch(t){e.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{o.close()}return Promise.resolve(l)}catch(t){return Promise.reject(t)}},e.reset=function(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}},e.destroy=function(){try{var t=function(){e.encoder=null,e.isInitialized=!1},e=this,n=e.encoder,r=function(){if(n){var t=function(){e.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{n.close()}catch(t){}},r=_catch$1(function(){return Promise.resolve(n.flush()).then(function(){})},function(){});return r&&r.then?r.then(t):t()}}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.createEncoder=function(){var t,e=this;return(t=new AudioEncoder({output:function(n){e.encoder===t&&e.handleOutput(n)},error:function(n){if(e.encoder===t){var r=n instanceof Error?n:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",r),e.failPending(r)}}})).configure(buildAudioEncoderConfig(this.config)),t},e.handleOutput=function(t){var e=this.pendingEncode;if(e)if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(!(e.chunks.length<e.expectedFrameCount)){var n=e.chunks.map(function(t,n){var r,i,s=new Uint8Array(t.byteLength);t.copyTo(s);var a=null!=(r=null==(i=e.chunks[n+1])?void 0:i.timestamp)?r:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),r=n.reduce(function(t,e){return t+e.durationMs},0);n.some(function(t){return t.durationMs!==OPUS_FRAME_DURATION_US/1e3})||r!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}},e.failPending=function(t){var e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))},t}(),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},WebMMuxer=/*#__PURE__*/function(){function t(t){void 0===t&&(t=16e3),this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}var e=t.prototype;return e.writeHeader=function(){if(!this.hasHeader){var 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}},e.feedOpusFrame=function(t,e){void 0===e&&(e=this.frameDuration),this.hasHeader||this.writeHeader();var n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e},e.flush=function(){if(0===this.chunks.length)return new ArrayBuffer(0);for(var t,e=this.chunks.reduce(function(t,e){return t+e.length},0),n=new Uint8Array(e),r=0,i=_createForOfIteratorHelperLoose(this.chunks);!(t=i()).done;){var s=t.value;n.set(s,r),r+=s.length}return this.chunks=[],n.buffer},e.reset=function(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0},e.encodeVINT=function(t,e){if(void 0!==e){for(var n=new Uint8Array(e),r=e-1;r>=0;r--)n[r]=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)},e.encodeID=function(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])},e.encodeUint=function(t){if(0===t)return new Uint8Array([0]);for(var e=[],n=t;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)},e.encodeString=function(t){return(new TextEncoder).encode(t)},e.encodeFloat32=function(t){var e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)},e.encodeElement=function(t,e){var n=this.encodeID(t),r=this.encodeVINT(e.length),i=new Uint8Array(n.length+r.length+e.length);return i.set(n,0),i.set(r,n.length),i.set(e,n.length+r.length),i},e.encodeUintElement=function(t,e){return this.encodeElement(t,this.encodeUint(e))},e.encodeStringElement=function(t,e){return this.encodeElement(t,this.encodeString(e))},e.encodeFloat32Element=function(t,e){return this.encodeElement(t,this.encodeFloat32(e))},e.concatArrays=function(t){for(var e,n=t.reduce(function(t,e){return t+e.length},0),r=new Uint8Array(n),i=0,s=_createForOfIteratorHelperLoose(t);!(e=s()).done;){var a=e.value;r.set(a,i),i+=a.length}return r},e.buildEBMLHeader=function(){var 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)},e.buildSegmentInfo=function(){var 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)},e.buildOpusTracks=function(){var 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)]),r=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,r)},e.buildCluster=function(t,e){var n=this.encodeUintElement(EBML_ID.Timecode,t),r=this.encodeVINT(1),i=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([r,i,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)},t}(),PcmWebMEncoder=/*#__PURE__*/function(){function t(){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}t.isSupported=function(){return WebCodecOpusEncoder.isSupported()};var e=t.prototype;return e.init=function(){try{return Promise.resolve(this.opusEncoder.init()).then(function(){})}catch(t){return Promise.reject(t)}},e.encode=function(t){try{var e=this;if(1600!==t.length)throw new Error("PCM 音频块必须为 1600 samples,实际为 "+t.length);if(e.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");e.pendingBlocks+=1;var n=e.generation,r=new Int16Array(t),i=e.queue.then(function(){try{return e.destroyed||n!==e.generation?Promise.resolve(new ArrayBuffer(0)):Promise.resolve(e.opusEncoder.encode(r)).then(function(t){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(var r,i=_createForOfIteratorHelperLoose(t);!(r=i()).done;){var s=r.value;e.muxer.feedOpusFrame(s.data,s.durationMs)}return e.muxer.flush()})}catch(t){return Promise.reject(t)}}).finally(function(){e.pendingBlocks-=1});return e.queue=i.then(function(){},function(){}),Promise.resolve(i)}catch(t){return Promise.reject(t)}},e.reset=function(){var t=this,e=++this.generation;this.queue=this.queue.then(function(){t.destroyed||e!==t.generation||(t.opusEncoder.reset(),t.muxer.reset())})},e.destroy=function(){try{var t=this;return t.destroyed=!0,t.generation+=1,Promise.resolve(t.opusEncoder.destroy()).then(function(){return Promise.resolve(t.queue).then(function(){t.muxer.reset()})})}catch(t){return Promise.reject(t)}},t}(),MediaRecorderEncoder=/*#__PURE__*/function(){function t(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}t.isSupported=function(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")};var e=t.prototype;return e.init=function(){try{var t=this,e=window.AudioContext||window.webkitAudioContext;t.audioCtx=new e({sampleRate:16e3});var n=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"}),r=URL.createObjectURL(n);return Promise.resolve(t.audioCtx.audioWorklet.addModule(r)).then(function(){URL.revokeObjectURL(r),t.workletNode=new AudioWorkletNode(t.audioCtx,"pcm-injector-processor"),t.destination=t.audioCtx.createMediaStreamDestination(),t.workletNode.connect(t.destination);var e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.recorder=new MediaRecorder(t.destination.stream,{mimeType:e,audioBitsPerSecond:24e3}),t.recorder.ondataavailable=function(e){e.data&&e.data.size>0&&e.data.arrayBuffer().then(function(e){if(t.nextResolve){var n=t.nextResolve;t.nextResolve=null,n(e)}else t.dataQueue.push(e)})};var n=function(){if("suspended"===t.audioCtx.state)return Promise.resolve(t.audioCtx.resume()).then(function(){})}();if(n&&n.then)return n.then(function(){})})}catch(t){return Promise.reject(t)}},e.feedPCM=function(t){try{var e=this;return e.workletNode&&e.recorder?(e.isRecording||(e.recorder.start(100),e.isRecording=!0),e.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),Promise.resolve(e.dataQueue.length>0?e.dataQueue.shift():new Promise(function(t){var n=setTimeout(function(){e.nextResolve=null,t(null)},200);e.nextResolve=function(e){clearTimeout(n),t(e)}}))):Promise.resolve(null)}catch(t){return Promise.reject(t)}},e.reset=function(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]},e.destroy=function(){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},t}();function _catch(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var XmovAvatar=/*#__PURE__*/function(){function t(t){var e=this;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=function(){},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=function(){e.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:function(t){if(e.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!e.isInitialized)return window.avatarSDKLogger.warn(e.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void e.cleanupBeforeInitComplete("network_offline_before_init");e.status!==AvatarStatus.offline&&e.offlineHandle()},onlineCallback:function(t){var n;if(e.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!e.isInitialized)return window.avatarSDKLogger.warn(e.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void e.cleanupBeforeInitComplete("network_online_before_init");null==(n=e.ttsa)||n.clearReconnectTimer(),e.isStartRetry&&e.triggerReconnect()}})}var e=t.prototype;return e.getStatus=function(){return this.status},e.getIsInitialized=function(){return this.isInitialized},e.getUniqueSpeakId=function(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||"0-"+this.getSessionId()},e.initializeSDK=function(t){try{var e,n,r,i=this;if(!navigator.onLine)return i.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"}),Promise.resolve();var s=i,a=t,o=t.containerId,l=t.container,h=t.appId,c=t.appSecret,d=t.gatewayServer,u=t.cacheServer,f=t.config,p=(null!=(e=null==f||null==(n=f.layout)?void 0:n.avatar)?e:{}).scale;null!=f&&null!=(r=f.layout)&&null!=(r=r.avatar)&&r.scale&&(f.layout.avatar.scale=validateScaleWithDecimal(void 0===p?1:p,"initializeSDK"));var m=_extends({},f||{},{raw_audio:!isSupportMES()});if(l&&l instanceof HTMLElement)i.el=l;else{var _=document.querySelector(o);if(!_)return i.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:"containerId: "+o+" 不存在"}),Promise.resolve();i.el=_}var g=document.createElement("div");g.setAttribute("id","avatar-bg-container"),g.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),i.el.appendChild(g);var v=i.el.getAttribute("style");return i.el.setAttribute("style",v?"position:relative;overflow:hidden;"+v:"position:relative;overflow:hidden;"),i.resourceManager=new ResourceManager({sdkInstance:i,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:a.sessionRequestData,appId:h,appSecret:c,gatewayServer:d,cacheServer:u,config:m,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo:function(e){s.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:function(t){null==i.options.onStartSessionWarning||i.options.onStartSessionWarning(t)}}),i.renderScheduler=new RenderScheduler({sdkInstance:i,container:i.el,resourceManager:i.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:i.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:function(t){var e,n,r;null==i.onDownloadProgress||i.onDownloadProgress(t),null==(e=i.el)||e.setAttribute("style",(null==(n=i.el)?void 0:n.style.cssText)+"opacity:"+(100===t?"1":"0")+";"),i.isInitialized=100===t,100===t&&(i.pendingInvisibleMode||i.status===AvatarStatus.online||i.status===AvatarStatus.invisible||i.onStatusChange(AvatarStatus.online),i.resourceManager._setOfflineCache(),null==(r=i.ttsa)||r.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(function(){var t,e;null==(t=i.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.0.0-beta.16",resolution:null==(e=i.resourceManager.getConfig())?void 0:e.resolution,download_speed:s.networkInfo.downlink||0}))},20),i.enableAudioPlaybackCapture())},onStateChange:function(e){i.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:function(e,n){null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&i.getStatus()!==AvatarStatus.online||!i.isInitialized||(window.avatarSDKLogger.log(i.TAG,"Status:===== 渲染中,状态: rendering",i.getSessionId()),i.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:function(e,n,r){null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,r)},onWalkStateChange:function(e){null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:function(t){var e;null==(e=i.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:function(e,n){null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:function(t){var e;null==(e=i.debugOverlay)||e.setAudioInfo(t)},setEventData:function(t){var e;null==(e=i.debugOverlay)||e.setEventData(t)},renderFrameCallback:function(t){i.renderFrameCallback(t),i.handleReplaySend(t)},reportMessage:function(t){i.onMessage(t)},sendSdkPoint:function(t,e,n){var r;null==(r=i.ttsa)||r.sendSdkPoint(t,e,n)},sendMessage:function(t,e){var n;null==(n=i.ttsa)||n.send(t,e)},onFPSUpdate:function(e){null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:function(e){null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=f&&f.walk_config&&i.changeWalkConfig(f.walk_config),null!=f&&f.layout&&i.changeLayout(f.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{},Promise.resolve()}catch(t){return Promise.reject(t)}},e.initializeClient=function(t){var e=this,n=t.containerId,r=t.container;if(r&&r instanceof HTMLElement)this.el=r;else{var i,s,a=document.querySelector(n);if(!a)return void(null==(i=(s=this.options).onMessage)||i.call(s,{code:EErrorCode.CONTAINER_NOT_FOUND,message:"containerId: "+n+" 不存在"}));this.el=a}var o=this.el.getAttribute("style");this.el.setAttribute("style",o?"position:relative;overflow:hidden;"+o:"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:function(t){null==e._clientOnDownloadProgress||e._clientOnDownloadProgress(t),t>=100&&!e.isInitialized&&(e.isInitialized=!0)},onSessionId:function(t){e._clientSessionId=t,window.avatarSDKLogger.log(e.TAG,"[client] 收到 session_id:",t)}});var l=t.streamingServer||"ws://"+location.hostname+":8080";this._streamingClient=new StreamingClient({url:l,onReady:function(){if(window.avatarSDKLogger.log(e.TAG,"[client] 双方就绪,等待 Server 推流..."),e._pendingInit){var t;e._pendingInit=!1;var n=e._pendingInitConfig;e._pendingInitConfig=null,window.avatarSDKLogger.log(e.TAG,"[client] 补发 init 命令"),null==(t=e._apiForwarder)||t.init(n)}},onOffer:function(t){var n;null==(n=e._videoPlayer)||n.handleOffer(t)},onIce:function(t){var n;null==(n=e._videoPlayer)||n.addIceCandidate(t)},onEventProxy:function(t,n,r){var i;null==(i=e._eventDispatcher)||i.dispatch(t,n,r)},onError:function(t){null==e.options.onMessage||e.options.onMessage({code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:function(){e.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:function(){window.avatarSDKLogger.log(e.TAG,"[client] WebRTC 已连接"),e.onStatusChange(AvatarStatus.online)},onDisconnected:function(){e.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)},e.renderFrameCallback=function(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()},e.init=function(t){try{var e=this;return Promise.resolve(checkCapability(e.options.audioOnlyMode)).then(function(n){if(n.supported){if(e.destroyed=!1,e.isInitialized=!1,e.incompleteInitializationCleanupPromise=null,e.startConnectTime=Date.now(),!e._isClientMode){var r=t.onDownloadProgress,i=t.initModel;return e.onDownloadProgress=function(t){15===t&&(e.sessionResTime=Date.now()),80===t&&(e.charbinResTime=Date.now()),r(t)},i===InitModel.invisible&&(e.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render),Promise.resolve(e.resourceManager.load(e.onDownloadProgress.bind(e))).then(function(t){if(e.destroyed)window.avatarSDKLogger.warn(e.TAG,"sdk destroyed during load, aborting after resourceManager load");else{if(null!=t&&t.socket_io_url&&null!=t&&t.token)return e.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),e.debugOverlay=new DebugOverlay(e,t),e.ttsa=e.connectTtsa(t),e.renderScheduler.init(),e.renderScheduler.setAvatarCanvasVisible(e.avatarCanvasVisible),window.performanceTracker.setReportFunc(e.ttsa),window.addEventListener("beforeunload",e.handleBeforeUnload),document.addEventListener("visibilitychange",e.boundVisibilityChange),t;window.avatarSDKLogger.error(e.TAG,"init error, socket_io_url or token is empty reload")}})}var s;e._clientOnDownloadProgress=t.onDownloadProgress||null;var a,o={appId:e.options.appId,appSecret:e.options.appSecret,gatewayServer:e.options.gatewayServer,cacheServer:e.options.cacheServer,headers:e.options.headers,tag:e.options.tag,gateway_type:e.options.gateway_type,env:e.options.env,config:e.options.config,hardwareAcceleration:e.options.hardwareAcceleration,enableDebugger:e.options.enableDebugger,initModel:t.initModel,scaleDownBy:e.options.scaleDownBy||1,useAlphaMask:e.options.useAlphaMask};null!=(s=e._streamingClient)&&s.isConnected()?null==(a=e._apiForwarder)||a.init(o):(e._pendingInit=!0,e._pendingInitConfig=o,window.avatarSDKLogger.log(e.TAG,"[client] WebSocket 未连接,init 命令暂存"))}else{var l="浏览器能力检查失败: "+n.items.filter(function(t){return"fatal"===t.severity&&!t.supported}).map(function(t){return t.reason}).join("; ");e.onMessage({code:EErrorCode.INIT_ERROR,message:l})}})}catch(t){return Promise.reject(t)}},e.setAudioPlaybackDataHandler=function(t){this.options.onAudioPlaybackData=t},e.restartAudioPlaybackCapture=function(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)},e.enableAudioPlaybackCapture=function(){var t,e=this;return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(function(){e.captureSetupPromise=null}):this.setupAudioCapture().finally(function(){e.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve()},e.setupAudioCapture=function(){try{var t=this,e=document.getElementById("xmov-avatar-audio");return e&&t.options.onAudioPlaybackData?t.captureAudioCtx||t.captureSource?Promise.resolve():void 0===window.AudioWorkletNode?(t.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"}),Promise.resolve()):Promise.resolve(_catch(function(){return Promise.resolve(PcmWebMEncoder.isSupported()).then(function(n){return n?(t.pcmWebMEncoder=new PcmWebMEncoder,Promise.resolve(t.pcmWebMEncoder.init()).then(function(){if(t.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==t.captureAudioCtx.sampleRate)throw new Error("浏览器无法创建 16000 Hz AudioContext: "+t.captureAudioCtx.sampleRate);t.captureSource=t.captureAudioCtx.createMediaElementSource(e),t.captureSource.connect(t.captureAudioCtx.destination);var n=!1,r=!0,i=0,s=0,a=function(e){var a=++t.captureGeneration;n=!0,r=!0,i=Date.now()-100,s=0,t.captureLastSpeechId=e,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){var e;a===t.captureGeneration&&(null==(e=t.pcmWebMEncoder)||e.reset())})};t.restartPlaybackCaptureImpl=function(){n&&a(t.renderScheduler.getSpeechId())};var o=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"}),l=URL.createObjectURL(o);return Promise.resolve(t.captureAudioCtx.audioWorklet.addModule(l)).then(function(){function e(){var e;if("running"!==t.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(e=window.avatarSDKLogger)||e.log(t.TAG,"[AudioCapture] 初始化成功,采样率:",t.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}URL.revokeObjectURL(l),t.captureWorklet=new AudioWorkletNode(t.captureAudioCtx,"audio-capture-processor"),t.captureSource.connect(t.captureWorklet),t.captureWorklet.connect(t.captureAudioCtx.destination),t.captureEncodeQueue=Promise.resolve(),t.captureWorklet.port.onmessage=function(e){if(t.options.onAudioPlaybackData){var o=e.data,l=o.hasAudio,h=o.pcmData,c=t.renderScheduler.getSpeechId();if(l&&!n||l&&n&&c!==t.captureLastSpeechId?a(c):!l&&n&&function(){var e=++t.captureGeneration;n=!1,t.captureLastSpeechId=-2,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){var n;e===t.captureGeneration&&(null==(n=t.pcmWebMEncoder)||n.reset())})}(),l&&n&&h instanceof ArrayBuffer){var d=t.captureGeneration,u=r;r=!1;var f=i+100*s;s+=1,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){try{var e;return Promise.resolve(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(h))).then(function(e){e&&0!==e.byteLength&&d===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:e,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:f,speech_id:c}))})}catch(t){return Promise.reject(t)}}).catch(function(e){var n;null==(n=window.avatarSDKLogger)||n.error(t.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",e)})}}};var o=function(){if("suspended"===t.captureAudioCtx.state)return Promise.resolve(t.captureAudioCtx.resume()).then(function(){})}();return o&&o.then?o.then(e):e()})})):void t.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"})})},function(e){function n(){var n,r;t.captureAudioCtx=null,null==(n=t.pcmWebMEncoder)||n.destroy(),t.pcmWebMEncoder=null,null==(r=window.avatarSDKLogger)||r.error(t.TAG,"[AudioCapture] 初始化失败:",e)}if(t.captureGeneration++,t.restartPlaybackCaptureImpl=null,t.captureWorklet){try{t.captureWorklet.port.onmessage=null,t.captureWorklet.disconnect()}catch(t){}t.captureWorklet=null}try{var r;null==(r=t.captureSource)||r.disconnect()}catch(t){}t.captureSource=null;var i=function(){if(t.captureAudioCtx&&"closed"!==t.captureAudioCtx.state)return Promise.resolve(t.captureAudioCtx.close().catch(function(){})).then(function(){})}();return i&&i.then?i.then(n):n()})):Promise.resolve()}catch(t){return Promise.reject(t)}},e.setupPCMCapture=function(){try{var t,e=this;if(!e.options.onAudioPlaybackData)return Promise.resolve();var n,r=null==(t=e.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();return r?Promise.resolve(PcmWebMEncoder.isSupported()).then(function(t){var n,i=MediaRecorderEncoder.isSupported();if(!t&&!i)return null==(n=window.avatarSDKLogger)||n.warn(e.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void e.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});var s=_catch(function(){function n(){return e.restartPlaybackCaptureImpl=function(){var t,n;e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=e.renderScheduler.getSpeechId(),e.pcmEncodeId++,null==(t=e.pcmWebMEncoder)||t.reset(),null==(n=e.mediaRecorderEncoder)||n.reset(),r.resetCaptureBuffer()},Promise.resolve(r.attachCapture(function(t){var n=t.pcmData,i=t.hasAudio;try{var s;return Promise.resolve(_catch(function(){function t(t){if(s)return t;if(d){var n=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:d,codec:"opus",isFirstChunk:n,sampleRate:16e3,samples:1600,timestamp:a,speech_id:h})}}if(e.options.onAudioPlaybackData){var a=Date.now()-100;if(r.isPlaying){var o,l,h=e.renderScheduler.getSpeechId();if(h!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=h,e.pcmEncodeId++,null==(o=e.pcmWebMEncoder)||o.reset(),null==(l=e.mediaRecorderEncoder)||l.reset(),r.resetCaptureBuffer()),i){var c=e.pcmEncodeId,d=null,u=performance.now(),f=function(){if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){var t=new Int16Array(n);return Promise.resolve(e.pcmWebMEncoder.encode(t)).then(function(t){var n;if(d=t,c!==e.pcmEncodeId)return null==(n=window.avatarSDKLogger)||n.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"),void(s=1);if(0!==d.byteLength){var r,i=performance.now()-u;i>10&&(null==(r=window.avatarSDKLogger)||r.warn(e.TAG,"[PCMCapture] WebCodecs 编码耗时过长: "+i.toFixed(2)+"ms"))}else s=1})}return function(){if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder)return Promise.resolve(e.mediaRecorderEncoder.feedPCM(n)).then(function(t){var n;if(d=t,c!==e.pcmEncodeId)return null==(n=window.avatarSDKLogger)||n.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"),void(s=1);if(d){var r,i=performance.now()-u;i>10&&(null==(r=window.avatarSDKLogger)||r.warn(e.TAG,"[PCMCapture] MediaRecorder 编码耗时过长: "+i.toFixed(2)+"ms"))}else s=1})}()}();return f&&f.then?f.then(t):t(f)}}else r.resetCaptureBuffer()}},function(t){var n;null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}))}catch(t){return Promise.reject(t)}})).then(function(){var t;null==(t=window.avatarSDKLogger)||t.log(e.TAG,"[PCMCapture] PCM 捕获初始化成功,编码路径: "+e.pcmCaptureMode)})}var i=t?(e.pcmWebMEncoder=new PcmWebMEncoder,Promise.resolve(e.pcmWebMEncoder.init()).then(function(){e.pcmCaptureMode="webcodec"})):(e.mediaRecorderEncoder=new MediaRecorderEncoder,Promise.resolve(e.mediaRecorderEncoder.init()).then(function(){e.pcmCaptureMode="mediarecorder"}));return i&&i.then?i.then(n):n()},function(t){var n,r,i;null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(r=e.pcmWebMEncoder)||r.destroy(),e.pcmWebMEncoder=null,null==(i=e.mediaRecorderEncoder)||i.destroy(),e.mediaRecorderEncoder=null,e.pcmCaptureMode="none"});return s&&s.then?s.then(function(){}):void 0}):(null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.visibilitychange=function(){if(document.hidden){var t,e,n,r=null==(t=this.renderScheduler)?void 0:t.getRenderState();r===RenderState.rendering||r===RenderState.resumed?null==(e=this.renderScheduler)||e.pauseRender():null==(n=this.renderScheduler)||n.pauseForBackground()}else{var i,s,a,o;if((null==(i=this.renderScheduler)?void 0:i.getRenderState())===RenderState.paused)null==(o=this.renderScheduler)||o.resumeRender();else if(null!=(s=this.ttsa)&&s.getStatus()){var l;null==(l=this.renderScheduler)||l.forceSyncDecoder()}null!=(a=this.ttsa)&&a.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode()),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(function(){})}},e.setReplayData=function(t){this.replayData=t},e.handleReplaySend=function(t){if(this.replayData)for(var e,n=this.replayData.filter(function(e){return Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type}),r=_createForOfIteratorHelperLoose(n);!(e=r()).done;){var i,s=e.value;"state_change"===s.event_type?null==(i=this.ttsa)||i.stateChange(s.event_data.state,s.event_data.params):"send_text"===s.event_type?this.speak(s.event_data.ssml,s.event_data.is_start,s.event_data.is_end,s.event_data.extra):window.avatarSDKLogger.log(this.TAG,"[handleReplaySend] 未知事件类型: "+s)}},e.connectTtsa=function(t){var e=this;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:function(){var n,r,i,s,a,o;null==(n=e.ttsa)||n.sendSdkPoint("connect_sdk",{timestamp:e.startConnectTime}),null==(r=e.ttsa)||r.sendSdkPoint("connect_sdk_success",{timestamp:e.connectSuccessTime}),null==(i=e.ttsa)||i.sendSdkPoint("session_processing_time",{timestamp:e.sessionResTime}),null==(s=e.ttsa)||s.sendSdkPoint("Char_bin_download_time",{timestamp:e.charbinResTime}),null==(a=e.ttsa)||a.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),e.onTtsaReady(t),null==(o=e.ttsa)||o.syncTimestamp()},handleMessage:function(t,n){var r;e.isfirstReceive&&t===EFrameDataType.BODY&&(null==(r=e.ttsa)||r.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),e.isfirstReceive=!1),e.renderScheduler.handleData(t,n)},handleAAFrame:function(t){null==e.options.onAAFrameHandle||e.options.onAAFrameHandle(t)},runStartFrameIndex:function(t){e.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:function(t){e.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:function(){e.reloadSuccess()},enterOfflineMode:function(){e.offlineHandle()},reStartSDK:function(){e.reStartSession()},sendVoiceEnd:function(){var t;null==(t=e.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:function(){var t,n;return null!=(t=null==(n=e.renderScheduler)?void 0:n.getCurrentFrameIndex())?t:0}})},e.start=function(){var t;this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online),this.renderScheduler.render(),null==(t=this.ttsa)||t.start()},e.onTtsaReady=function(t){this.start()},e._reload=function(){try{var t=this;return Promise.resolve(t.resourceManager._reload()).then(function(e){var n,r=function(){if(e&&!t.destroyed)return Promise.resolve(t.onSessionReloaded(e)).then(function(){if(t.destroyed)return n=1,null;t.ttsa=t.connectTtsa(e),t.ttsa._setResumeInfoCallback(t.resourceManager._getSessionId(),t.renderScheduler._getResumeInfo.bind(t.renderScheduler))})}();return r&&r.then?r.then(function(t){return n?t:e}):n?r:e})}catch(t){return Promise.reject(t)}},e.onSessionReloaded=function(t){return Promise.resolve()},e.onSessionReloadExhausted=function(t){},e.restartSessionForTransport=function(t){try{var e=this;return e.renderScheduler.interrupt("in_offline_mode"),Promise.resolve(e.resourceManager.stopSession(t)).then(function(){var t;e.destroyed||(null==(t=e.ttsa)||t.close(),e.status!==AvatarStatus.offline&&e.offlineHandle(),e.reStartSession())})}catch(t){return Promise.reject(t)}},e.cancelSessionRestart=function(){this.resetRetryState(),this.clearAllRetryTimers()},e.reloadSuccess=function(){var t,e=this;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(function(){window.clearInterval(e._offlineTimer)},1e3)},e.stop=function(){try{return Promise.resolve(this.renderScheduler.stop()).then(function(){})}catch(t){return Promise.reject(t)}},e.isDestroyed=function(){return this.destroyed},e.destroyClient=function(){try{var t,e,n,r=this;if(r.destroyed)return window.avatarSDKLogger.warn(r.TAG,"SDK 已销毁,忽略重复销毁请求"),Promise.resolve();if(r.destroyed=!0,r._isClientMode)return r._streamingClient&&(r._streamingClient.destroy(),r._streamingClient=null),r._videoPlayer&&(r._videoPlayer.destroy(),r._videoPlayer=null),r._eventDispatcher=null,r._apiForwarder=null,r.el=null,window.removeEventListener("beforeunload",r.handleBeforeUnload),window.avatarSDKLogger.log(r.TAG,"薄客户端 SDK 已销毁"),Promise.resolve();if(r.cancelSessionRestart(),-1!==r._offlineTimer&&(clearInterval(r._offlineTimer),r._offlineTimer=-1),r.ttsa&&(r.ttsa.close(),r.ttsa=null),r.renderScheduler&&r.renderScheduler.destroy(),r.resourceManager&&r.resourceManager.destroy(),r.debugOverlay&&(r.debugOverlay.destroy(),r.debugOverlay=null),r.networkMonitor)try{r.networkMonitor.destroy(),r.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(r.TAG,"销毁 networkMonitor 时出错",t)}if(r.pcmEncodeId++,r.captureGeneration++,r.restartPlaybackCaptureImpl=null,r.captureWorklet){try{r.captureWorklet.port.onmessage=null,r.captureWorklet.disconnect()}catch(t){}r.captureWorklet=null}if(r.captureSource){try{r.captureSource.disconnect()}catch(t){}r.captureSource=null}if(r.captureAudioCtx){try{r.captureAudioCtx.close()}catch(t){}r.captureAudioCtx=null}var i=null==(t=r.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();return i&&i.detachCapture(),null==(e=r.pcmWebMEncoder)||e.destroy(),r.pcmWebMEncoder=null,null==(n=r.mediaRecorderEncoder)||n.destroy(),r.mediaRecorderEncoder=null,r.pcmCaptureLastSpeechId=-2,r.pcmCaptureFirstChunk=!0,r.pcmCaptureMode="none",r.el=null,r.startConnectTime=0,r.connectSuccessTime=0,r.sessionResTime=0,r.charbinResTime=0,r.isfirstReceive=!0,r.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",r.handleBeforeUnload),document.removeEventListener("visibilitychange",r.boundVisibilityChange),window.avatarSDKLogger.log(r.TAG,"SDK 已销毁"),Promise.resolve()}catch(t){return Promise.reject(t)}},e.destroy=function(t){void 0===t&&(t="user");try{var e,n=function(n){var i;return e?n:(null==(i=r.ttsa)||i.sendSdkPoint("close_session",{reason:t}),Promise.resolve(r.resourceManager.stopSession(t)).then(function(t){return Promise.resolve(r.destroyClient()).then(function(){return t&&r.onStatusChange(AvatarStatus.close),t})}))},r=this;r.replayData=null;var i=function(){var n;if(r._isClientMode)return null==(n=r._apiForwarder)||n.destroy(t),Promise.resolve(r.destroyClient()).then(function(){r.onStatusChange(AvatarStatus.close),e=1})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(t){return Promise.reject(t)}},e.idle=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())},e.listen=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())},e.think=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())},e.interactiveidle=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())},e.speak=function(t,e,n,r){var i,s,a,o;if(void 0===e&&(e=!0),void 0===n&&(n=!0),void 0===r&&(r={client_speak_id:"",client_frame:0}),!this._isClientMode){this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),r.client_frame=null!=(i=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?i:0;var l=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,r);return this.renderScheduler.resume(),l}null==(o=this._apiForwarder)||o.speak(t,e,n,r)},e.setOffsetFrame=function(t){this.renderScheduler.setOffsetFrame(t)},e.syncTimestamp=function(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)},e.notifyEnterInvisibleMode=function(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()},e.notifyExitInvisibleMode=function(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()},e.setVolume=function(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)},e.getSessionId=function(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id},e.showDebugInfo=function(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())},e.hideDebugInfo=function(){var t;null==(t=this.debugOverlay)||t.hide()},e.changeAvatarVisible=function(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)},e.cleanupBeforeInitComplete=function(t){var e,n=this,r=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,"清理初始化未完成的资源,原因: "+t),this.isInitialized=!1;var i=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==i||i.catch(function(t){window.avatarSDKLogger.warn(r.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=function(){try{var t=_catch(function(){return Promise.resolve(i).then(function(){return Promise.resolve(n.destroyClient()).then(function(){})})},function(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(t){return Promise.reject(t)}}(),this.incompleteInitializationCleanupPromise},e.reportInitializationFailure=function(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e:e})},e.offlineHandle=function(){var t=this;this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(function(){if(t.status!==AvatarStatus.offline)return clearInterval(t._offlineTimer),void(t._offlineTimer=-1);t.renderScheduler._offlineRun()},this._offlineInterval)},e.stopSessionFromSocket=function(t){try{return Promise.resolve(this.resourceManager.stopSession(t)).then(function(){})}catch(t){return Promise.reject(t)}},e.offlineMode=function(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()},e.onlineMode=function(){NetworkMonitor.ONLINE&&this._reload()},e.onMessage=function(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(r){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",r)}var r=Errors(t);t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&this.options.onMessage(r),null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(r)},e.onStatusChange=function(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))},e.switchInvisibleMode=function(){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 未初始化,无法切换隐身模式")},e.setInvisibleMode=function(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)},e.getPendingInvisibleMode=function(){return this.pendingInvisibleMode||!1},e.getRenderState=function(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init},e.changeLayout=function(t){var e;if(this._isClientMode){var n;null==(n=this._apiForwarder)||n.changeLayout(t)}else{var r=(t.avatar||{}).scale;t.avatar.scale=validateScaleWithDecimal(void 0===r?1:r,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}},e.changeWalkConfig=function(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))},e.interrupt=function(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)},e.triggerReconnect=function(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()},e.reStartSession=function(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())},e._retryImpl=function(){try{var t=this;if(t.retryRound>t.maxRetryRound||!t.isRetrying)return Promise.resolve();var e=1e3;return t.retryCount>1&&(e=1e3*Math.pow(2,t.retryCount)),t.retryTimer=window.setTimeout(function(){try{return t.retryTimer=-1,!t.isRetrying||t.destroyed?Promise.resolve():Promise.resolve(_catch(function(){return Promise.resolve(t._reload()).then(function(e){if(t.isRetrying&&!t.destroyed)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()})},function(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()}))}catch(t){return Promise.reject(t)}},e),Promise.resolve()}catch(t){return Promise.reject(t)}},e.clearAllRetryTimers=function(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)},e.resetRetryState=function(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1},e.seekToFrame=function(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)},e.startRecoder=function(){try{var t=this;try{var e,n,r=null==(e=t.el)?void 0:e.querySelector("canvas"),i=null==(n=t.el)?void 0:n.querySelector("audio");if(!r||!i)return console.error("找不到 canvas 或 audio 元素"),Promise.resolve();var s=r.captureStream(60),a=[];if(t.captureSource&&t.captureAudioCtx){var o=t.captureAudioCtx.createMediaStreamDestination();t.captureSource.connect(o),a=o.stream.getAudioTracks()}else if("function"==typeof i.captureStream)a=i.captureStream().getAudioTracks();else{if("function"!=typeof i.mozCaptureStream)return window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频"),Promise.resolve();a=i.mozCaptureStream().getAudioTracks()}t.stream=new MediaStream([].concat(s.getVideoTracks(),a)),t.recordedChunks=[],t.mediaRecorder=new MediaRecorder(t.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),t.mediaRecorder.ondataavailable=function(e){e.data&&e.data.size>0&&t.recordedChunks.push(e.data)},t.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}return Promise.resolve()}catch(t){return Promise.reject(t)}},e.stopRecoder=function(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(function(t){return t.stop()}),window.avatarSDKLogger.log("⏹ 停止录制"))},e.exportVideo=function(){if(this.recordedChunks.length){var 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)}else window.avatarSDKLogger.error("没有录制到数据")},e.getOptions=function(){return this.options},e.simulateContextLoss=function(t,e){void 0===t&&(t=5e3),void 0===e&&(e=!1),this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")},e.getRecoveryStatus=function(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null},e.testStagedRecovery=function(){try{return this.renderScheduler?Promise.resolve(this.renderScheduler.testStagedRecovery()):(window.avatarSDKLogger.warn("[Test] renderScheduler not initialized"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)},_createClass(t,[{key:"businessENV",get:function(){return this._env}}])}();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,module.exports=XmovAvatar;
|
|
1
|
+
function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function _defineProperties(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,_toPropertyKey(r.key),r)}}function _createClass(t,e,n){return e&&_defineProperties(t.prototype,e),n&&_defineProperties(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function _createForOfIteratorHelperLoose(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=_unsupportedIterableToArray(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}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 r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_extends.apply(null,arguments)}function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPrimitive(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return"symbol"==typeof e?e:e+""}function _unsupportedIterableToArray(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(t,e):void 0}}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={}));var 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"},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={}));var FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk",DataCacheQueue=/*#__PURE__*/function(){function t(){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}var e=t.prototype;return e._updateBodyImageBitmap=function(t){var e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(var n,r=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(n=r()).done;){var i=n.value,s=i[0],a=i[1];a.body_id<t.body_id&&a.frameIndex>=t.frameIndex&&(a.frame.close(),this._bodyQueue.delete(s))}this._bodyQueue.set(t.frameIndex,t)},e.clearOldFrames=function(t){for(var e,n=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(e=n()).done;){var r=e.value,i=r[0];i>=t&&(r[1].frame.close(),this._bodyQueue.delete(i))}},e.clearOldFaceData=function(t){this._facialQueue=this._facialQueue.filter(function(e){return e.frameIndex>=t}),this._realFacialQueue=this._realFacialQueue.filter(function(e){return e.frameIndex>=t})},e.setVideoIdList=function(t){this.videoIdList.includes(t)||this.videoIdList.push(t)},e.getVideoIdList=function(){return this.videoIdList},e._getBodyImageBitmap=function(t){for(var e,n=this._bodyQueue.get(t),r=_createForOfIteratorHelperLoose(this._bodyQueue.entries());!(e=r()).done;){var i=e.value,s=i[0];s<t&&(i[1].frame.close(),this._bodyQueue.delete(s))}if(n)return n},e.getBodyVideoNameListLength=function(){var t=[];return this.bodyQueue.forEach(function(e){t.includes(e.name)||t.push(e.name)}),t.length},e._getFaceImageBitmap=function(t,e){for(var n=null,r=this._facialQueue.length-1;r>=0;r--){var i=this._facialQueue[r];if(i.frameIndex===t&&i.body_id===e){n=i;break}}return this._facialQueue=this._facialQueue.filter(function(e){return e.frameIndex>=t}),n},e._updateFacial=function(t){var e;(e=this._facialQueue).push.apply(e,t)},e._getRealFaceImageBitmap=function(t,e){for(var n=null,r=this._realFacialQueue.length-1;r>=0;r--){var i=this._realFacialQueue[r];if((null==i?void 0:i.frameIndex)===t&&(null==i?void 0:i.body_id)===e){n=i;break}}return this._realFacialQueue=this._realFacialQueue.filter(function(e){return(null==e?void 0:e.frameIndex)>=t}),n},e._updateRealFacial=function(t){var e;(e=this._realFacialQueue).push.apply(e,t)},e.clearAllFaceData=function(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")},e._updateAudio=function(t){var e;(e=this.audioQueue).push.apply(e,t)},e._clearAudio=function(t){this.audioQueue=-1!==t?this.audioQueue.filter(function(e){return e.sid!==t}):[]},e._getAudio=function(t){var e=this.audioQueue.findIndex(function(e){return e.sf===t});if(-1!==e)return this.audioQueue.splice(e,1)[0]},e._getAudioInterval=function(t,e){var n=this.audioQueue.filter(function(n){return n.sf>=t&&n.sf<=e});if(0!==n.length){var r=n[n.length-1],i=this.audioQueue.findIndex(function(t){return t.id===r.id});return this.audioQueue.splice(i,1),r}},e._updateUiEvent=function(t){var e;(e=this.eventQueue).push.apply(e,t)},e.clearOldEvent=function(t){this.eventQueue=this.eventQueue.filter(function(e){return e.sf>=t})},e.clearSubtitleOn=function(t){this.eventQueue=this.eventQueue.map(function(e){var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(function(e){return e.speech_id>t||"subtitle_on"!==e.type})})})},e._clearEvent=function(){this.eventQueue=[]},e._getEvent=function(t){var e=this.eventQueue.filter(function(e){return e.sf===t});if(0!==e.length)return this.eventQueue=this.eventQueue.filter(function(e){return e.sf!==t}),this._mergeEventsBySf(e)},e._getEventInterval=function(t,e){var n=this.eventQueue.filter(function(n){return n.sf>=t&&n.sf<=e});if(0!==n.length)return this.eventQueue=this.eventQueue.filter(function(n){return!(n.sf>=t&&n.sf<=e)}),this._mergeEventsBySf(n)},e._mergeEventsBySf=function(t){for(var e,n={},r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var i,s=e.value,a=s.sf;n[a]||(n[a]=_extends({},s,{e:[]})),(i=n[a].e).push.apply(i,s.e)}var o=Object.values(n);if(0===o.length)return null;if(o.length>1){var l=[];return o.forEach(function(t){return l.push.apply(l,t.e)}),_extends({},o[0],{mergeFrameFlag:1,e:l})}return o[0]},e.checkValidData=function(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,r;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==(r=this.audioQueue[0])?void 0:r.sf)){var i=this.audioQueue.findIndex(function(e){return e.sf>=t[0].sf});-1!==i&&(this.audioQueue.length=i)}}},e.destroy=function(){this._bodyQueue.forEach(function(t){t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]},_createClass(t,[{key:"currentPlayState",get:function(){return this._currentPlayState},set:function(t){this._currentPlayState=t}},{key:"currentTtsaState",get:function(){return this._currentTtsaState},set:function(t){this._currentTtsaState=t}},{key:"bodyQueue",get:function(){return Array.from(this._bodyQueue.values())}},{key:"facialQueue",get:function(){return this._facialQueue}},{key:"realFacialQueue",get:function(){return this._realFacialQueue}}])}(),GLDevice=/*#__PURE__*/function(){function t(t){var e=this;this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;var n=function(){var t=e.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");e.gl=t,e._lost_context_sim=e.gl.getExtension("WEBGL_lose_context"),e.shaderStage={vertex:e.gl.VERTEX_SHADER,fragment:e.gl.FRAGMENT_SHADER},e._ElementTypeMap_JS2GL={Uint8Array:e.gl.UNSIGNED_BYTE,Uint8ClampedArray:e.gl.UNSIGNED_BYTE,Int8Array:e.gl.BYTE,Uint16Array:e.gl.UNSIGNED_SHORT,Int16Array:e.gl.SHORT,Uint32Array:e.gl.UNSIGNED_INT,Int32Array:e.gl.INT,Float16Array:e.gl.HALF_FLOAT,Float32Array:e.gl.FLOAT};var n=[[e.gl.UNSIGNED_BYTE,[[e.gl.RED,e.gl.R8],[e.gl.RED_INTEGER,e.gl.R8UI],[e.gl.RG,e.gl.RG8],[e.gl.RG_INTEGER,e.gl.RG8UI],[e.gl.RGB,e.gl.RGB8],[e.gl.RGB_INTEGER,e.gl.RGB8UI],[e.gl.RGBA,e.gl.RGBA8],[e.gl.RGBA_INTEGER,e.gl.RGBA8UI]]],[e.gl.BYTE,[[e.gl.RED,e.gl.R8_SNORM],[e.gl.RED_INTEGER,e.gl.R8I],[e.gl.RG,e.gl.RG8_SNORM],[e.gl.RG_INTEGER,e.gl.RG8I],[e.gl.RGB,e.gl.RGB8_SNORM],[e.gl.RGB_INTEGER,e.gl.RGB8I],[e.gl.RGBA,e.gl.RGBA8_SNORM],[e.gl.RGBA_INTEGER,e.gl.RGBA8I]]],[e.gl.UNSIGNED_SHORT,[[e.gl.RED_INTEGER,e.gl.R16UI],[e.gl.RG_INTEGER,e.gl.RG16UI],[e.gl.RGB_INTEGER,e.gl.RGB16UI],[e.gl.RGBA_INTEGER,e.gl.RGBA16UI],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT16]]],[e.gl.SHORT,[[e.gl.RED_INTEGER,e.gl.R16I],[e.gl.RG_INTEGER,e.gl.RG16I],[e.gl.RGB_INTEGER,e.gl.RGB16I],[e.gl.RGBA_INTEGER,e.gl.RGBA16I]]],[e.gl.UNSIGNED_INT,[[e.gl.RED_INTEGER,e.gl.R32UI],[e.gl.RG_INTEGER,e.gl.RG32UI],[e.gl.RGB_INTEGER,e.gl.RGB32UI],[e.gl.RGBA_INTEGER,e.gl.RGBA32UI],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT24]]],[e.gl.INT,[[e.gl.RED_INTEGER,e.gl.R32I],[e.gl.RG_INTEGER,e.gl.RG32I],[e.gl.RGB_INTEGER,e.gl.RGB32I],[e.gl.RGBA_INTEGER,e.gl.RGBA32I]]],[e.gl.HALF_FLOAT,[[e.gl.RED,e.gl.R16F],[e.gl.RG,e.gl.RG16F],[e.gl.RGB,e.gl.RGB16F],[e.gl.RGBA,e.gl.RGBA16F]]],[e.gl.FLOAT,[[e.gl.RED,e.gl.R32F],[e.gl.RG,e.gl.RG32F],[e.gl.RGB,e.gl.RGB32F],[e.gl.RGBA,e.gl.RGBA32F],[e.gl.DEPTH_COMPONENT,e.gl.DEPTH_COMPONENT32F]]],[e.gl.UNSIGNED_SHORT_5_6_5,[[e.gl.RGB,e.gl.RGB565]]],[e.gl.UNSIGNED_SHORT_4_4_4_4,[[e.gl.RGBA,e.gl.RGBA4]]],[e.gl.UNSIGNED_SHORT_5_5_5_1,[[e.gl.RGBA,e.gl.RGB5_A1]]],[e.gl.UNSIGNED_INT_2_10_10_10_REV,[[e.gl.RGBA,e.gl.RGB10_A2]]],[e.gl.UNSIGNED_INT_10F_11F_11F_REV,[[e.gl.RGB,e.gl.R11F_G11F_B10F]]],[e.gl.UNSIGNED_INT_5_9_9_9_REV,[[e.gl.RGB,e.gl.RGB9_E5]]],[e.gl.UNSIGNED_INT_24_8,[[e.gl.DEPTH_STENCIL,e.gl.DEPTH24_STENCIL8]]],[e.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[e.gl.DEPTH_STENCIL,e.gl.DEPTH32F_STENCIL8]]]];e._FormatTypeMap_Ext2Int=new Map;for(var r=0,i=n;r<i.length;r++){for(var s,a=i[r],o=a[0],l=a[1],h=new Map,c=_createForOfIteratorHelperLoose(l);!(s=c()).done;){var d=s.value;h.set(d[0],d[1])}e._FormatTypeMap_Ext2Int.set(o,h)}var u={GL_RED:e.gl.RED,GL_RED_INTEGER:e.gl.RED_INTEGER,GL_RG:e.gl.RG,GL_RG_INTEGER:e.gl.RG_INTEGER,GL_RGB:e.gl.RGB,GL_RGB_INTEGER:e.gl.RGB_INTEGER,GL_RGBA:e.gl.RGBA,GL_RGBA_INTEGER:e.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:e.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:e.gl.DEPTH_STENCIL};e._FormatTypeMap_Ext2Str=new Map;for(var f=0,p=Object.entries(u);f<p.length;f++){var m=p[f];e._FormatTypeMap_Ext2Str.set(m[1],m[0])}};this.frameID=null,this.cbRender=function(){},this._onContextLost=function(t){t.preventDefault(),e.stop()},this._onContextRestored=n,this._onContextCreationError=function(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),n()}var e=t.prototype;return e.compileShaderProgram=function(t){var e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(var n=0,r=Object.entries(t);n<r.length;n++){var i=r[n],s=i[1],a=this.gl.createShader(this.shaderStage[i[0]]);if(!a)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(a,s),this.gl.compileShader(a),!this.gl.getShaderParameter(a,this.gl.COMPILE_STATUS)){var o=this.gl.getShaderInfoLog(a);throw this.gl.deleteShader(a),new Error("WebGL shader compile failed:"+o)}this.gl.attachShader(e,a)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){var l=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+l)}return e},e.getShaderProgramUniformLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getUniformLocation(t,s)}return r},e.getShaderProgramUniformBlockLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getUniformBlockIndex(t,s)}return r},e.getShaderProgramAttribLocation=function(t,e){for(var n,r={},i=_createForOfIteratorHelperLoose(e);!(n=i()).done;){var s=n.value;r[s]=this.gl.getAttribLocation(t,s)}return r},e.getGLArrayElementType=function(t){var e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null},e.getGLTexInternalFormat=function(t,e){var n=this._FormatTypeMap_Ext2Int.get(e);if(n){var r=n.get(t);if(r)return r}return null},e.texImage2D=function(t,e,n,r,i,s){var a,o=this.getGLArrayElementType(s);if(!o)throw new Error("Unsupported data format: "+s[Symbol.toStringTag]);var l=this.getGLTexInternalFormat(i,o);if(!l)throw new Error("No available internal format for "+s[Symbol.toStringTag]+" and "+(null!=(a=this._FormatTypeMap_Ext2Str.get(i))?a:"unknown")+".");this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,r,0,i,o,s)},e.texImage3D=function(t,e,n,r,i,s,a){var o,l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);var 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,r,i,0,s,l,a)},e.run=function(t,e){var n=this;if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;var r=function(t,i){n.running&&(n.syncMediaTime=i.mediaTime,n.cbRender(n),n.frameID=e.requestVideoFrameCallback(r))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(r)}else{var i=function(){n.running&&(n.cbRender(n),n.frameID=requestAnimationFrame(i))};i()}},e.refresh=function(){this.cbRender(this)},e.getSyncMediaTime=function(){return this.syncMediaTime},e.stop=function(){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},e.simulateContextFault=function(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())},e.captureFrame=function(){var 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}},e.destroy=function(){if(!this._isDestroyed&&this.gl){var t=this.gl;try{var 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){var n=this.canvas.getContext("2d");n&&n.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}}},t}(),_performanceText;function length(t){return Math.sqrt(t.reduce(function(t,e){return t+e*e},0))}function normalize(t){var e=length(t);return t.map(function(t){return t/e})}function mvmul(t,e){for(var n=t.length,r=e.length,i=Array(n),s=0;s<n;s++){i[s]=0;for(var a=0;a<r;a++)i[s]+=t[s][a]*e[a]}return i}function mmul(t,e){for(var n=t.length,r=e.length,i=e[0].length,s=Array(n),a=0;a<n;a++){for(var o=Array(i),l=0;l<i;l++){o[l]=0;for(var h=0;h<r;h++)o[l]+=t[a][h]*e[h][l]}s[a]=o}return s}function transpose(t){for(var e=t.length,n=t[0].length,r=Array(n),i=0;i<n;i++){for(var s=Array(e),a=0;a<e;a++)s[a]=t[a][i];r[i]=s}return r}function identity(t){for(var e=Array(t),n=0;n<t;n++){for(var r=Array(t),i=0;i<t;i++)r[i]=n==i?1:0;e[n]=r}return e}function det3(t){var 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])-t[0][0]*t[1][2]*t[2][1]}function inv3(t){var 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){for(var e=[[].concat(t[0]),[].concat(t[1]),[].concat(t[2]),[].concat(t[3])],n=[0,0,0,0],r=[0,0,0,0],i=0,s=0;s<4;s++){for(var a=0,o=s;o<4;o++)for(var l=s;l<4;l++)Math.abs(e[o][l])>a&&(a=Math.abs(e[o][l]),n[s]=o,r[s]=l);if(a<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[s]!=s)for(var h=0;h<4;h++)i=e[s][h],e[s][h]=e[n[s]][h],e[n[s]][h]=i;if(r[s]!=s)for(var c=0;c<4;c++)i=e[c][s],e[c][s]=e[c][r[s]],e[c][r[s]]=i;e[s][s]=1/e[s][s];for(var d=0;d<4;d++)d!=s&&(e[s][d]*=e[s][s]);for(var u=0;u<4;u++)if(u!=s)for(var f=0;f<4;f++)f!=s&&(e[u][f]-=e[u][s]*e[s][f]);for(var p=0;p<4;p++)p!=s&&(e[p][s]*=-e[s][s])}for(var m=3;m>=0;m--){if(r[m]!=m)for(var _=0;_<4;_++)i=e[m][_],e[m][_]=e[r[m]][_],e[r[m]][_]=i;if(n[m]!=m)for(var g=0;g<4;g++)i=e[g][m],e[g][m]=e[g][n[m]],e[g][n[m]]=i}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){var e=t[0],n=t[1],r=t[2],i=t[3];return[[e*e+n*n-r*r-i*i,2*(n*r-i*e),2*(n*i+r*e)],[2*(n*r+i*e),e*e-n*n+r*r-i*i,2*(r*i-n*e)],[2*(n*i-r*e),2*(r*i+n*e),e*e-n*n-r*r+i*i]]}function GivensTransform(t,e,n,r){for(var i=Math.sin(r),s=Math.cos(r),a=t[0].length,o=0;o<a;o++){var l=i*t[e][o]+s*t[n][o];t[e][o]=s*t[e][o]-i*t[n][o],t[n][o]=l}}function Euler_to_mat(t,e){void 0===e&&(e="xyz");var 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){for(var e=t.length,n=t[0].length,r=Array(e*n),i=0;i<e;i++)for(var s=0;s<n;s++)r[i*n+s]=t[i][s];return r}var 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"};_performanceText={},_performanceText[performanceConstant.load_resource]="加载资源",_performanceText[performanceConstant.ttsa_connect]="ttsa连接",_performanceText[performanceConstant.ttsa_ready]="ttsa准备返回first_start_timestamp",_performanceText[performanceConstant.first_avatar_render]="前端处理好第一帧渲染数据",_performanceText[performanceConstant.first_webgl_render]="前端处理好第一帧webgl渲染",_performanceText[performanceConstant.ttsa_body_res]="ttsa返回body",_performanceText[performanceConstant.start_action_res]="触发行为返回",_performanceText[performanceConstant.start_action_render]="触发行为并渲染耗时",_performanceText[performanceConstant.load_video]="视频加载",_performanceText[performanceConstant.decode_video]="视频解码",_performanceText[performanceConstant.voice_response_play]="speak音频响应",_performanceText[performanceConstant.first_decode_video]="第一帧视频解码",_performanceText[performanceConstant.first_render]="第一帧webgl渲染";var PerformanceTracker=/*#__PURE__*/function(){function t(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=function(){},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}var e=t.prototype;return e.getFirstInfo=function(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}},e.markStart=function(t,e){this.marks.set(t,{state:e,time:performance.now()})},e.markEnd=function(t,e){var n=this.marks.get(t);if(n&&(!e||"string"!=typeof e||e===(null==n?void 0:n.state))){var r=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:r}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,r),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=r),t===performanceConstant.first_render&&(this.firstRenderTime=r),r}},e.getAllMetrics=function(){return Object.fromEntries(this.measures.entries())},e.getVideoMetrics=function(){var t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(function(t){return[performanceConstant.decode_video,performanceConstant.load_video].includes(t[0])}))},e.setReportFunc=function(t){this.reportFunc=t},e.reportMetric=function(){var t,e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){var n,r=Object.fromEntries(Object.entries(e).filter(function(t){return![performanceConstant.load_video,performanceConstant.decode_video].includes(t[0])}));for(var i in Object.keys(r).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(r)),r)i!==performanceConstant.decode_video&&i!==performanceConstant.load_video&&this.measures.delete(i)}},e.setOnStateRenderChange=function(t){this.onStateRenderChange=t},t}();window.performanceTracker=new PerformanceTracker;var 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"}}var 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"],GLPipeline=/*#__PURE__*/function(){function t(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=function(){return 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=function(){},this.device=t,this.sendSdkPoint=e,this.reinitialize()}var e=t.prototype;return e.assembleBackgroundPipeline=function(){this._ub_shadow_fx_data=new Float32Array(32);var 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);var r=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r),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);var i={};i.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.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=i,this.device.gl.bindVertexArray(null);var 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},e.assembleMeshPipelines=function(t){if(t.char){for(var e=t.char,n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)},r=0;r<e.mesh.length;r++){for(var i,s=0,a=_createForOfIteratorHelperLoose(e.mesh[r].textureModels);!(i=a()).done;){var o=i.value.data.size[0]+3;o-=o%4,s=Math.max(s,o)}n.max_pca_component_count=Math.max(n.max_pca_component_count,s);var l=e.mesh[r].blendshapes.size[2]+3;l-=l%4,n.max_bs_count=Math.max(n.max_bs_count,l)}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);var h=generateMeshPipelineShader(this.meshStatistics),c=this.device.compileShaderProgram({vertex:h.vertex,fragment:h.fragment}),d=this.device.getShaderProgramUniformLocation(c,uniform_var_list_mesh),u=this.device.getShaderProgramUniformBlockLocation(c,uniform_block_list_mesh);this.meshPipelineInfo={program:c,progUniforms:d,progUniformBlocks:u},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),c=this.device.compileShaderProgram({vertex:h.vertex,fragment:h.fragment_mask}),d=this.device.getShaderProgramUniformLocation(c,uniform_var_list_mesh),u=this.device.getShaderProgramUniformBlockLocation(c,uniform_block_list_mesh),this.maskPipelineInfo={program:c,progUniforms:d,progUniformBlocks:u},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(var f=0;f<e.mesh.length;f++){var p={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(p.VAO),null===this.device.getGLArrayElementType(e.mesh[f].blendshapes.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].blendshapes.data);if(p.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[f].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[f].UVCoord.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].UVCoord.data);if(p.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[f].UVCoord.data),!0,0,0),e.mesh[f].opacity){if(null===this.device.getGLArrayElementType(e.mesh[f].opacity.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].opacity.data);p.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[f].opacity.data),!0,0,0)}if(p.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].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),p.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,p.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[f].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[f].triangles.data))throw new Error("Data type unsupported by WebGL: "+e.mesh[f].triangles.data);if(p.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,p.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[f].triangles.data,this.device.gl.STATIC_DRAW),p.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,p.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),p.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,p.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[f].blendshapes.size[2]>0){for(var m=[Math.ceil(e.mesh[f].blendshapes.size[2]/4),e.mesh[f].blendshapes.size[0]*e.mesh[f].blendshapes.size[1]],_=Math.ceil(Math.sqrt(m[0]*m[1])),g=4*m[0],v=new Float32Array(_*_*4),y=0;y<m[1];y++){for(var b=0;b<e.mesh[f].blendshapes.size[2];b++)v[y*g+b]=e.mesh[f].blendshapes.data[y*e.mesh[f].blendshapes.size[2]+b];for(var S=e.mesh[f].blendshapes.size[2];S<g;S++)v[y*g+S]=0}if(p.textures.u_image_bs=this.device.gl.createTexture(),!p.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,p.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,_,_,this.device.gl.RGBA,v),p.uniformUInts.u_bs_count=m[0]}else p.uniformUInts.u_bs_count=0;for(var E,w=_createForOfIteratorHelperLoose(e.mesh[f].textureModels);!(E=w()).done;){var x=E.value,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);var A=this.device.getGLArrayElementType(x.data.data),R={texture:T,unsigned:this.device.gl.UNSIGNED_BYTE===A||this.device.gl.UNSIGNED_SHORT===A||this.device.gl.UNSIGNED_INT===A},P=x.data.data;if("Float64Array"===x.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===A&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===A&&!this.compat_features.OES_texture_half_float_linear){for(var B=x.data.size[1]*x.data.size[2]*3,C=new Uint8Array(x.data.size[0]*B),I=new Float32Array(x.data.size[0]),k=0;k<x.data.size[0];k++){for(var D=1e-6,U=0;U<B;U++)D=Math.max(D,Math.abs(x.data.data[k*B+U]));for(var O=1/D,F=0;F<B;F++)C[k*B+F]=Math.round(255*(x.data.data[k*B+F]*O*.5+.5));I[k]=D}P=C,R.unsigned=!0,R.scalingFactor=I}x.scalingFactor&&(R.scalingFactor=x.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,x.data.size[1],x.data.size[2],x.data.size[0],this.device.gl.RGB,P),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),p.texturePCAModels.push(R)}this.meshInfos.push(p)}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);var L=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,L),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);var M=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,M),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);var 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.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,M),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,N),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,L)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;var z=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,z),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,z)}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{for(var G=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3),j=0;j<G.length;j++)G[j]=Math.round(255*t.LUT.data[j]);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,G)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null},e.getProjMat=function(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())},e.initFrame=function(){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)},e.renderBackground=function(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);var e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);var n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){var r=t.fx.shadow,i=this.getBillboardShadowGeometryInfo(r.refPos,r.light,"point"===r.lightType);e+=4;for(var s=0;s<3;s++)for(var a=0;a<3;a++)this._ub_shadow_fx_data[4*s+a]=i.Mat_World2ObjImage[a][s];for(var o=0;o<3;o++)for(var l=0;l<3;l++)this._ub_shadow_fx_data[4*o+l+12]=i.Mat_ShadowImage2World[l][o];for(var h=0;h<3;h++)this._ub_shadow_fx_data[24+h]=r.tint[h];this._ub_shadow_fx_data[27]=r.intensity,this._ub_shadow_fx_data[28]=r.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)},e.renderMesh=function(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);var n,r=t.char,i=new Float32Array(flatten(this.getProjMat(r.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),n=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]);for(var a=r.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(r.skeleton.length),l=0;l<r.skeleton.length;l++){var h=a[l].apply(this.initSkeletonStatus[l].inv());o[l]=h.homogeneous_matrix()}for(var c=0,d=0;d<Math.min(this.meshStatistics.max_bones,r.skeleton.length);d++){for(var u=0;u<4;u++)for(var f=0;f<4;f++)this._ub_rig_info_data[c+4*u+f]=o[d][f][u];c+=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,i),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,n);for(var p=0;p<r.mesh.length;p++)if(r.mesh[p].genMask){var m=this.meshInfos[p];if(r.mesh[p].blendshapes.size[2]>0){c=16*this.meshStatistics.max_bones;for(var _=Math.min(r.mesh[p].blendshapeIndices.length,this.meshStatistics.max_bs_count),g=0;g<_;g++)this._ub_rig_info_data[c+g]=e.data.blendshapeWeights[r.mesh[p].blendshapeIndices[g]];for(var v=_;v<this.meshStatistics.max_bs_count;v++)this._ub_rig_info_data[c+v]=0}var y=0;for(var b in r.mesh[p].opacity&&(y+=1),m.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[b],m.uniformUInts[b]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,y),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,m.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,m.buffers.ub_rig_info),this.device.gl.bindVertexArray(m.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,m.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,m.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,r.mesh[p].triangles.itemSize(),this.device.getGLArrayElementType(r.mesh[p].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,i),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,n);for(var S=!0,E=0;E<r.mesh.length;E++){var w=this.meshInfos[E],x=w.texturePCAModels[e.data.mesh[E].textureModelIndex];if(r.mesh[E].blendshapes.size[0]>0){c=16*this.meshStatistics.max_bones;for(var T=Math.min(r.mesh[E].blendshapeIndices.length,this.meshStatistics.max_bs_count),A=0;A<T;A++)this._ub_rig_info_data[c+A]=e.data.blendshapeWeights[r.mesh[E].blendshapeIndices[A]];for(var R=T;R<this.meshStatistics.max_bs_count;R++)this._ub_rig_info_data[c+R]=0}var P=0;for(var B in r.mesh[E].opacity&&(P+=1),null!==this.LUTTexture&&(P+=2),x.unsigned&&(P+=4),S!=r.mesh[E].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!r.mesh[E].genMask),S=r.mesh[E].genMask),w.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[B],w.uniformUInts[B]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,P),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,w.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,w.buffers.ub_rig_info);var C=Math.min(e.data.mesh[E].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(var I=1;I<C;I++)this._ub_pca_info_data[I]=e.data.mesh[E].texturePCAWeights[I-1];if(x.scalingFactor)for(var k=0;k<C;k++)this._ub_pca_info_data[k]*=x.scalingFactor[k];for(var D=C;D<this.meshStatistics.max_pca_component_count;D++)this._ub_pca_info_data[D]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,w.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,w.buffers.ub_pca_info),this.device.gl.bindVertexArray(w.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,w.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,w.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),x.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,x.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,r.mesh[E].triangles.itemSize(),this.device.getGLArrayElementType(r.mesh[E].triangles.data),0)}S||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)},e.reinitialize=function(){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)},e.setSyncMedia=function(t){var e=this;this.device.run(function(t){return e.render()},t)},e.setCharData=function(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null},e.setFrameDataCallback=function(t){this.frameDataCallback=t},e.setGamma=function(t,e,n){this.currentGamma={r:t,g:e,b:n}},e.setColorBalance=function(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}},e.getBillboardTransform2D=function(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};var n=this.getProjMat(this.charData.char.cameraConfig),r=inv4(n),i=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=i[3][0]/i[3][1],a=[r[0][0]-e[0]*r[3][0],r[1][0]-e[1]*r[3][0],r[2][0]-e[2]*r[3][0]],o=[r[0][1]-t[0]*r[3][1],r[1][1]-t[1]*r[3][1],r[2][1]-t[2]*r[3][1]],l=[r[0][1]-e[0]*r[3][1],r[1][1]-e[1]*r[3][1],r[2][1]-e[2]*r[3][1]],h=s*Math.sqrt([r[0][0]-t[0]*r[3][0],r[1][0]-t[1]*r[3][0],r[2][0]-t[2]*r[3][0]].reduce(function(t,e){return t+e*e},0)/a.reduce(function(t,e){return t+e*e},0)),c=s*Math.sqrt(o.reduce(function(t,e){return t+e*e},0)/l.reduce(function(t,e){return t+e*e},0));return{offsetX:.5*(i[0][1]/i[3][1]-i[0][0]/i[3][0]-(h-1)),offsetY:.5*(1-c-(i[1][1]/i[3][1]-i[1][0]/i[3][0])),scaleX:h,scaleY:c}},e.getBillboardShadowGeometryInfo=function(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};var r=this.getProjMat(this.charData.char.cameraConfig),i=inv4(r),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]);var o=transpose(mmul(inv3(a),s)),l=mvmul(r,[t[0],t[1],t[2],1]),h=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[r[0][0],r[0][2],r[0][1]*t[1]+r[0][3]],[r[1][0],r[1][2],r[1][1]*t[1]+r[1][3]],[r[3][0],r[3][2],r[3][1]*t[1]+r[3][3]]])),Mat_World2ObjImage:inv3([[i[0][0],i[0][1],i[0][2]*h+i[0][3]],[i[1][0],i[1][1],i[1][2]*h+i[1][3]],[i[3][0],i[3][1],i[3][2]*h+i[3][3]]])}},e.render=function(){var t,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()},e.renderFrame=function(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()},e.destroy=function(){var t,e,n,r,i=this;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(function(t){t.VAO&&i.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(function(t){t&&i.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(function(t){t&&i.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(function(t){t.texture&&i.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!=(r=this.maskPipelineInfo)&&r.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)},t}(),containerWidgetMaps=new Map,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;var e=t.getAttribute("data-widget-container-id");if(e)return e;var n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){var e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}var 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:function(t){var e=t.axis_id,n=t.x_location,r=t.y_location,i=t.width,s=t.height,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");var o="position:absolute;";return o+=void 0!==e?"z-index:"+e+";":"z-index:1;",void 0!==n&&void 0!==r&&(o+="top:"+100*r+"%;left:"+100*n+"%;"),void 0!==i&&void 0!==s&&(o+="width:"+100*i+"%;height:"+100*s+"%;"),a.setAttribute("style",o),a},_getWidgetKey:function(t,e){return t+"-"+(null!=e?e:"default")},_replaceWidget:function(t,e,n,r){var i=this._getWidgetKey(t,e),s=getContainerElement(r||this._currentInstance);if(s){var a=getContainerWidgetMap(s);if(a.has(i)){var o=a.get(i);o&&o.parentNode&&o.remove()}a.set(i,n)}},WIDGET_PIC:function(t,e){var n=this._el(t),r=document.createElement("img");return r.crossOrigin="anonymous",r.setAttribute("style","width:100%;height:100%;"),r.src=t.image,n.appendChild(r),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE:function(t,e){var n=t.type,r=t.text,i=t.axis_id,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){var a=getContainerWidgetMap(s),o=this._getWidgetKey("WIDGET_SUBTITLE",i);if(a.has(o)){var l=a.get(o);l&&l.parentNode&&l.remove(),a.delete(o)}}return null}var h=this._el(t);return h.innerHTML=r,h.setAttribute("style",h.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",i,h,e),h},destroy:function(t){var e=getContainerElement(t||this._currentInstance);if(e){var n=getContainerId(e);if(containerWidgetMaps.has(n)){var r=containerWidgetMaps.get(n);r.forEach(function(t,e){(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),r.clear(),containerWidgetMaps.delete(n)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(function(t){t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var n=[0,0,0],r=0;r<3;r++)n[r]=t.dataview.getUint8(t.offset),t.offset+=1;var i=e.split(".").map(function(t){return 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)});for(var e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset),n=0;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;var r=e.slice(0,n);return new TextDecoder("utf-8").decode(r)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var e=0,n=0;;){var r=t.dataview.getUint8(t.offset);t.offset++;var i=e|(127&r)<<n;if(i<e)throw new Error("Integer too large to decode.");if(e=i,!(128&r))break;n+=7}return e}var 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);var Tensor=/*#__PURE__*/function(){function t(t,e){this.size=t,this.data=e}var e=t.prototype;return e.itemSize=function(){for(var t,e=1,n=_createForOfIteratorHelperLoose(this.size);!(t=n()).done;)e*=t.value;return e},e.byteSize=function(){return this.itemSize()*this.data.BYTES_PER_ELEMENT},t.zeros=function(e,n){void 0===n&&(n=Float32Array);for(var r=1,i=0;i<e.length;i++)r*=e[i];for(var s=new n(r),a=0;a<r;a++)s[a]=0;return new t(e,s)},e.part=function(){var e=[].slice.call(arguments);if(e.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");for(var n=[],r=1,i=e.length;i<this.size.length;i++)n.push(this.size[i]),r*=this.size[i];var s=0;e.length>0&&(s+=e[0]);for(var a=1;a<e.length;a++)s*=this.size[a],s+=e[a];return new t(n,this.data.slice(s*=r,s+r))},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var n=e.dataview.getUint8(e.offset);e.offset++;for(var r=new Array(n),i=1,s=0;s<n;s++)r[s]=decodeLongInt(e),i*=r[s];var a=String.fromCodePoint(e.dataview.getUint8(e.offset));e.offset++;var o=TensorDataTypeMap[a];if(void 0===o)throw new Error('Unsupported tensor element type "'+a+'".');var l=i*o.BYTES_PER_ELEMENT,h=new o(e.dataview.buffer.slice(e.offset,e.offset+l));return e.offset+=l,new t(r,h)},t}();function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});for(var e=[null];;){var n=decodeStr(t);if(""==n)break;var r=null;if("text/plain;charset=UTF-8"===n){var i=decodeLongInt(t),s=new Uint8Array(t.dataview.buffer,t.offset,i);t.offset+=i,r=new TextDecoder("utf-8").decode(s)}else if("application/json;charset=UTF-8"==n){var a=decodeLongInt(t),o=new Uint8Array(t.dataview.buffer,t.offset,a);t.offset+=a;var l=new TextDecoder("utf-8");r=JSON.parse(l.decode(o))}else if("application/octet-stream"===n)r=Tensor.deserialize(t);else{var h=decodeLongInt(t),c=t.dataview.buffer.slice(t.offset,t.offset+h);t.offset+=h,r=new Blob([c],{type:n})}e.push(r)}return e}var CameraConfig=/*#__PURE__*/function(){function t(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}var e=t.prototype;return e.getIntrinsicMatrix=function(t){var e=25.4*this.filmAperture[0];return[[this.focalLength/(e/t[0]),0,t[0]/2],[0,this.focalLength/(e*t[1]/t[0]/t[1]),t[1]/2],[0,0,1]]},e.getProjMatrix=function(t,e,n){void 0===e&&(e=.01),void 0===n&&(n=Infinity);var r,i,s=t[0],a=t[1],o=this.getIntrinsicMatrix(t);return Infinity===n?(r=-1,i=-2*e):(r=-(n+e)/(n-e),i=-2*n*e/(n-e)),[[2*o[0][0]/s,0,(s-2*o[0][2])/s,0],[0,2*o[1][1]/a,(a-2*o[1][2])/a,0],[0,0,r,i],[0,0,-1,0]]},e.getExtrinsicMatrix=function(){var t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(function(e){return e*t}),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(function(t){return-t})))},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var n=new t;n.focalLength=e.dataview.getFloat32(e.offset,!0);for(var r=0;r<2;r++)n.filmAperture[r]=e.dataview.getFloat32(e.offset+4*(r+1),!0);for(var i=0;i<3;i++)n.translation[i]=e.dataview.getFloat32(e.offset+4*(i+3),!0);for(var s=0;s<3;s++)n.rotation[s]=e.dataview.getFloat32(e.offset+4*(s+6),!0);return e.offset+=36,n},t}(),RigidTransform=/*#__PURE__*/function(){function t(t,e){void 0===t&&(t=[0,0,0]),void 0===e&&(e=[1,0,0,0]),this.translation=t,this.rotQuaternion=e}var e=t.prototype;return e.apply=function(e){if(e instanceof t){var n=quaternion_mul(this.rotQuaternion,e.rotQuaternion);n=normalize(n);for(var r=mvmul(quaternion_to_mat(this.rotQuaternion),e.translation),i=0;i<3;i++)r[i]+=this.translation[i];return new t(r,n)}for(var s=mvmul(this.matrix(),e),a=0;a<3;a++)s[a]+=this.translation[a];return s},e.inv=function(){var e=quaternion_conj(this.rotQuaternion);return new t(mvmul(quaternion_to_mat(e),this.translation.map(function(t){return-t})),e)},e.matrix=function(){return quaternion_to_mat(this.rotQuaternion)},e.homogeneous_matrix=function(){return make_homogeneous(this.matrix(),this.translation)},t.deserialize=function(e){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});for(var n=[0,0,0],r=[1,0,0,0],i=0;i<3;i++)n[i]=e.dataview.getFloat32(e.offset+4*i,!0);for(var s=0,a=0;a<3;a++)r[a+1]=e.dataview.getFloat32(e.offset+4*(a+3),!0),s+=r[a+1]*r[a+1];return r[0]=Math.sqrt(Math.max(1-s,0)),e.offset+=24,new t(n,r)},t}(),IBRMeshInfo=function(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){var n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;for(var r=[],i=[],s=!0;;){var a=decodeLongInt(t);if(0===a){if(!s)break}else r.push(a-1);s=!1;for(var o=[],l=!0,h=0;;){var c=decodeLongInt(t);if(l)for(var d=0;d<c;d++)o.push(h+d);if(l=!l,h+=c,0===c&&h>0)break}i.push(o)}var u=i[0].length;this.blendshapeIndices=r;for(var f,p=e.archivedItems[decodeLongInt(t)],m=Tensor.zeros([u,p.size[1]],p.data.constructor),_=Tensor.zeros([u,p.size[1],this.blendshapeIndices.length],p.data.constructor),g=0,v=_createForOfIteratorHelperLoose(i[0]);!(f=v()).done;){for(var y=f.value,b=0;b<p.size[1];b++)m.data[y*p.size[1]+b]=p.data[g*p.size[1]+b];g++}for(var S=this.blendshapeIndices.length,E=1;E<i.length;E++)for(var w,x=_createForOfIteratorHelperLoose(i[E]);!(w=x()).done;){for(var T=w.value,A=0;A<p.size[1];A++)_.data[(T*p.size[1]+A)*S+E-1]=p.data[g*p.size[1]+A];g++}this.vertices=m,this.blendshapes=_,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(u*e.maxJointsPerVertex),this.jointWeight=new Float32Array(u*e.maxJointsPerVertex);for(var R=0;R<u;R++){for(var P=0;P<e.maxJointsPerVertex;P++)this.jointIndex[R*e.maxJointsPerVertex+P]=t.dataview.getUint8(t.offset),t.offset+=1;for(var B=0;B<e.maxJointsPerVertex;B++)this.jointWeight[R*e.maxJointsPerVertex+B]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}var C=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(C);for(var I=0;I<C;I++)this.textureModels[I]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;var k=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var D=new Float32Array(k),U=0;U<k;U++)D[U]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([k],D);var O=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var F=new Uint16Array(3*O),L=0;L<O;L++)for(var M=0;M<3;M++)F[3*L+M]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([O,3],F);for(var N=new Float32Array(2*k),z=0;z<k;z++)for(var G=0;G<2;G++)N[2*z+G]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([k,2],N);var j=t.dataview.getUint16(t.offset,!0);t.offset+=2;for(var W=new Float32Array(3*k),H=0;H<3*k;H++)W[H]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;for(var V=new Float32Array((j-1)*k*3),$=0;$<j-1;$++)for(var K=0;K<3*k;K++)V[K*(j-1)+$]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([k,3],W),this.blendshapes=new Tensor([k,3,j-1],V),this.blendshapeIndices=[];for(var Y,X=_createForOfIteratorHelperLoose(e.blendshapeIndices);!(Y=X()).done;)this.blendshapeIndices.push(Y.value);this.jointIndex=new Uint8Array(k*e.maxJointsPerVertex),this.jointWeight=new Float32Array(k*e.maxJointsPerVertex);for(var Z=0;Z<k;Z++){for(var q=0;q<e.maxJointsPerVertex;q++)this.jointIndex[Z*e.maxJointsPerVertex+q]=t.dataview.getUint8(t.offset),t.offset+=1;for(var Q=0;Q<e.maxJointsPerVertex;Q++)this.jointWeight[Z*e.maxJointsPerVertex+Q]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}var J=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(J);for(var tt=0;tt<J;tt++){for(var et=[0,0,0,3],nt=0;nt<3;nt++)et[nt]=t.dataview.getUint16(t.offset,!0),t.offset+=2;for(var rt=new Float32Array(et[0]*et[1]*et[2]*3),it=0;it<rt.length;it++)rt[it]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[tt]={data:new Tensor(et,rt)}}}},IBRMeshFrameInfo=/*#__PURE__*/function(){function t(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}return t.deserialize=function(e,n){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var r=e.dataview.getUint8(e.offset);e.offset+=1;for(var i=new Float32Array(n.textureModels[r].data.size[0]-1),s=0;s<i.length;s++)i[s]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;return new t(r,i)},t}(),IBRAnimationGeneratorCharInfo_NN=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e={}),t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});var n=checkVersion(t,__version__),r=[];if(n[0]>2&&(r=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.");for(var i,s=new Set,a=_createForOfIteratorHelperLoose(e.blendshapeMap);!(i=a()).done;)for(var o,l=_createForOfIteratorHelperLoose(i.value);!(o=l()).done;)s.add(o.value);this.blendshapeCount=s.size}var h=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;var c=t.dataview.getUint8(t.offset);t.offset+=1;for(var d=new Array(c),u=0;u<c;u++)d[u]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=d,this.skeleton=new Array(h);for(var f=0;f<h;f++){var p=t.dataview.getUint8(t.offset);p>=this.skeleton.length&&(p=null),t.offset+=1;var m=RigidTransform.deserialize(t);this.skeleton[f]={parent:p,local_transform:m}}this.jointEvalOrder=new Array(h);for(var _=0;_<h;_++)this.jointEvalOrder[_]=t.dataview.getUint8(t.offset),t.offset+=1;var g={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(g.archivedItems=r);var v=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(v);for(var y=0;y<v;y++)n[0]<=2&&(g.blendshapeIndices=e.blendshapeMap[y]),this.mesh[y]=new IBRMeshInfo(t,g)}var e=t.prototype;return e.evalSkeleton=function(){for(var t,e=Array(this.skeleton.length),n=_createForOfIteratorHelperLoose(this.jointEvalOrder);!(t=n()).done;){var r=t.value;e[r]=null==this.skeleton[r].parent?this.skeleton[r].local_transform:e[this.skeleton[r].parent].apply(this.skeleton[r].local_transform)}return e},e.evalSkeletonFromMovable=function(t){for(var e=Array(this.skeleton.length),n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(var r,i=_createForOfIteratorHelperLoose(this.jointEvalOrder);!(r=i()).done;){var s=r.value;null!=this.skeleton[s].parent&&(e[s]=e[this.skeleton[s].parent].apply(this.skeleton[s].local_transform))}return e},t}(),IBRAnimationFrameData_NN=/*#__PURE__*/function(){function t(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}return t.deserialize=function(e,n,r){e instanceof ArrayBuffer&&(e={offset:0,dataview:new DataView(e)});var i=new t,s=n.mesh.length;if(i.mesh=new Array(s),i.blendshapeWeights=new Float32Array(n.blendshapeCount),r[0]>2){for(var a=0;a<s;a++)i.mesh[a]=IBRMeshFrameInfo.deserialize(e,n.mesh[a]);for(var o=0;o<i.blendshapeWeights.length;o++)i.blendshapeWeights[o]=e.dataview.getFloat32(e.offset,!0),e.offset+=4}else for(var l=0;l<s;l++){for(var h=n.mesh[l].blendshapeIndices,c=0;c+1<h.length;c++)i.blendshapeWeights[h[c+1]-1]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;var d=e.dataview.getUint8(e.offset);e.offset+=1;for(var u=new Float32Array(n.mesh[l].textureModels[d].data.size[0]-1),f=0;f<u.length;f++)u[f]=e.dataview.getFloat32(e.offset,!0),e.offset+=4;i.mesh[l]=new IBRMeshFrameInfo(d,u)}i.movableJointTransforms=new Array(n.movableJoints.length);for(var p=0;p<n.movableJoints.length;p++)i.movableJointTransforms[p]=RigidTransform.deserialize(e);return i},t.interp=function(e,n,r,i,s){var a=new t;a.blendshapeWeights=new Float32Array(e.blendshapeWeights.length);for(var o=0;o<a.blendshapeWeights.length;o++)a.blendshapeWeights[o]=i*n.blendshapeWeights[o]+(1-i)*e.blendshapeWeights[o];a.mesh=[];for(var l=0;l<e.mesh.length;l++){for(var h=new IBRMeshFrameInfo(e.mesh[l].textureModelIndex,new Float32Array(e.mesh[l].texturePCAWeights.length)),c=0;c<e.mesh[l].texturePCAWeights.length;c++)h.texturePCAWeights[c]=i*n.mesh[l].texturePCAWeights[c]+(1-i)*e.mesh[l].texturePCAWeights[c];a.mesh.push(h)}a.movableJointTransforms=new Array(r.movableJointTransforms.length);for(var d=0;d<r.movableJointTransforms.length;d++){for(var u,f=!0,p=_createForOfIteratorHelperLoose(s);!(u=p()).done;)if(u.value[0]===d){f=!1;break}f&&(a.movableJointTransforms[d]=r.movableJointTransforms[d])}for(var m,_=_createForOfIteratorHelperLoose(s);!(m=_()).done;){for(var g=m.value,v=g[0],y=g[1],b=e.movableJointTransforms[y].inv().apply(e.movableJointTransforms[v]),S=n.movableJointTransforms[y].inv().apply(n.movableJointTransforms[v]),E=[],w=[],x=0;x<3;x++)E.push(i*S.translation[x]+(1-i)*b.translation[x]);for(var T=0;T<4;T++)w.push(i*S.rotQuaternion[T]+(1-i)*b.rotQuaternion[T]);w=normalize(w);var A=new RigidTransform(E,w);A=r.movableJointTransforms[y].apply(A),a.movableJointTransforms[v]=A}return a},t}();function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});var n=checkVersion(t,__version__),r=t.dataview.getUint32(t.offset,!0);t.offset+=4;for(var i=Array(r),s=0;s<r;s++)i[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return i}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){var t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),r=/Google Inc/.test(e),i=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(r||i)&&s}function getStyleStr(t){return Object.entries(t).map(function(t){var e=t[0],n=t[1],r="number"==typeof n?n.toString():n;return e.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()})+":"+r+";"}).join("")}function updateCanvasXOffset(t,e){var n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+" translateX("+e+"px)";t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){var t=screen.width+"x"+screen.height,e=navigator.userAgent,n=navigator.language,r=Intl.DateTimeFormat().resolvedOptions().timeZone,i=encodeURIComponent(t+"|"+e+"|"+n+"|"+r);return btoa(i)}function getDeviceInfo(){var t=navigator.userAgent,e="Unknown Brand",n="Unknown Model",r="Unknown Version",i="Unknown Browser",s="Unknown Version",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?r="Windows NT "+a[1]:o?r="Android "+o[1]:l?r="iOS "+l[1].replace(/_/g,"."):t.includes("Macintosh")?r="Macintosh":t.includes("Linux")&&(r="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");var h=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),c=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),d=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?(i="Chrome",s=h[1]):c?(i="Safari",s=c[1]):d?(i="Firefox",s=d[1]):u?(i="Edge",s=u[1]):f?(i="Opera",s=f[1]):p&&(i="IE",s=p[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:r,browser:i,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(){var t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}function _settle$2(t,e,n){if(!t.s){if(n instanceof _Pact$2){if(!n.s)return void(n.o=_settle$2.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle$2.bind(null,t,e),_settle$2.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var AvatarRender=/*#__PURE__*/function(){function t(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=function(){},this.onRenderChange=function(){},this.sendVideoInfo=function(){},this.lostHandler=function(){},this.restoreHandler=function(){},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=function(){},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=function(){},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")}var e=t.prototype;return e.resetFaceFrameState=function(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")},e.createPipeline=function(){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()))},e._lostHandler=function(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())},e._restoreHandler=function(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())},e._recoverContext=function(){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);var 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())},e._tryLightRecovery=function(){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}},e._tryMediumRecovery=function(){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}var e,n,r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),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}},e._tryFullRecovery=function(){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}var r=this.canvas,i=r.style.cssText,s=r.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),c=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=h,a.height=c,a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,window.avatarSDKLogger.log("[Recovery] Using reduced resolution: "+h+"x"+c+" (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}},e._onRecoverySuccess=function(){var 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},e._scheduleResolutionRestore=function(){var t=this;this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log("[Recovery] Scheduling resolution restore in "+this.RESOLUTION_RESTORE_DELAY+"ms"),this.resolutionRestoreTimer=setTimeout(function(){t._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)},e._restoreOriginalResolution=function(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");var r=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,i=null!=(e=null==r?void 0:r.width)?e:1080,s=null!=(n=null==r?void 0:r.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=i,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 "+i+"x"+s),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:"Resolution restored to "+i+"x"+s+".",e:{timestamp:Date.now(),resolution:{width:i,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")},e._advanceStage=function(){var t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){var 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},e._scheduleNextAttempt=function(){var t=this,e=this.recoveryBaseDelays[this.recoveryStage],n=this.recoveryMaxAttempts[this.recoveryStage],r=e*Math.pow(2,this.currentStageAttempts),i=Math.min(r,this.recoveryMaxDelay);window.avatarSDKLogger.log("[Recovery] Scheduling "+this.recoveryStage+" attempt "+(this.currentStageAttempts+1)+"/"+n+" in "+i+"ms (base="+e+"ms, exp="+r+"ms)"),this.restoreTimeout=setTimeout(function(){t.isRecovering=!0,t._recoverContext()},i)},e._reportRecoveryFailure=function(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()}})},e.init=function(t){var e,n,r,i,s,a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(r=null==(i=this.options.resourceManager.getConfig())||null==(i=i.resolution)?void 0:i.height)?r: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()},e.style=function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)},e.setCanvasStyle=function(t){var e,n,r,i,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;var h=null!=(e=null!=(n=null==(r=this.walkConfig)?void 0:r.init_point)?n:null==(i=this.options.resourceManager.getConfig())||null==(i=i.walk_config)?void 0:i.init_point)?e:null,c=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},d=c.width,u=void 0===d?1080:d,f=c.height,p=void 0===f?1920:f,m=(null!=(o=null==(l=t.container)?void 0:l.size)?o:[u,p])[1],_=t.avatar||{},g=_.v_align,v=void 0===g?"center":g,y=_.h_align,b=void 0===y?"center":y,S=_.scale,E=void 0===S?1:S,w=_.offset_x,x=void 0===w?0:w,T=_.offset_y,A=void 0===T?0:T;if(null!=h&&(b="left",x=0),"string"==typeof E&&E.includes("vh")){var R=parseFloat(E.replace("vh",""));E=isNaN(R)?1:R/100*m/p}this.scale=Number(E);var P=p*Number(E),B=u*Number(E),C=B/2,I=P/2,k={position:"absolute",zIndex:100,height:P+"px",width:B+"px",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(b){case"left":k.left=null!=h?h-C+"px":"0",k.marginLeft=x+"px";break;case"right":k.right="-"+C+"px",k.marginLeft=x+"px";break;default:k.position="absolute",k.left="50%",k.marginLeft=-C+x+"px"}switch(v){case"top":k.top="0",k.marginTop=A+"px";break;case"bottom":k.bottom="0",k.marginTop=A+"px";break;default:k.position="absolute",k.top="50%",k.marginTop=-I+A+"px"}var D=getStyleStr(k);this.canvas.setAttribute("style",D)},e.setWalkConfig=function(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)},e.setCharacterCanvasAnchor=function(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n,r=(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(r)}else{var i,s=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",s);var a=(null==(i=this.options.resourceManager.getConfig())||null==(i=i.init_events)?void 0:i.find(function(t){return"SetCharacterCanvasAnchor"===t.type}))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1};this.canvas.setAttribute("style",this.canvas.style.cssText+"left: calc("+a.x_location+" * 100%); top: calc("+a.y_location+" * 100%); transform: scale("+a.width+", "+a.height+"); transform-origin: top left;")}},e.computeWeight=function(t){var 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},e.render=function(t){var e,n,r,i,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};var l=this.options.dataCacheQueue._getBodyImageBitmap(t),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),c=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(r=null!=(i=null==l?void 0:l.body_id)?i:null==l?void 0:l.id)?r:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)h=c;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&&c){var d,u,f=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==(d=h)?void 0:d.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,c.FaceFrameData,c.FaceFrameData,f,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)h=c;else if(null!=c&&c.FaceFrameData)if(null===this.lastRealFaceFrameData)h=c;else{var p,m,_=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==(p=h)?void 0:p.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,c.FaceFrameData,c.FaceFrameData,_,(null==(m=this.options.resourceManager.resource_pack)?void 0:m.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 g,v;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(g=this.onStateChange)||g.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==(v=this.onDownloadProgress)||v.call(this,100));var y=!1;if(this.pipeline){var b;try{var S,E,w,x,T,A,R,P=this.options.resourceManager.getIsEnableRobotExpression()?null!=(S=null==(E=h)?void 0:E.FaceFrameData)?S:null:null!=l&&l.hfd&&null!=(w=null==(x=h)?void 0:x.FaceFrameData)?w:null;P&&this.saveAndDownload.appendMultipleToArray("render_faceData",[h]),this.lastFaceFrame=h;var B,C=l.frame;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(B=this.copyCtx)||B.drawImage(l.frame,0,0),C=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:C,data:P,backgroundTexture:null,fx:null!=(T=null==(A=this.options.resourceManager.getConfig())?void 0:A.fx)?T:{},onPostRender:function(){return null}});var I=[0,0,0],k=[].concat(I),D=null!=(R=null==l?void 0:l.offset)?R:0;this.lastBodyOffset=D,k[0]+=D-this.baseWalkOffset;var U=this.pipeline.getBillboardTransform2D([I[0],I[1],I[2]],[k[0],k[1],k[2]]).offsetX*this.canvas.width*this.scale;U!==this.canvasOffsetX&&(this.canvasOffsetX=U,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:U}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(U):updateCanvasXOffset(this.canvas,U)),this.lastFrameIndex=t,y=!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==(b=this.onRenderChange)||b.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:y}}return{canvas:this.canvas,rendered:!1}},e.renderBackground=function(){var t=this.options.resourceManager.getBackgroundImageElement();if(t){var e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage="url("+t.src+")",e.style.backgroundSize="cover",e.style.backgroundPosition="center")}},e._setCurrentBodyFrame=function(t){t&&(this.currentBodyFrame=t)},e._getCurrentBodyFrameInfo=function(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"}},e._getCurrentFrameData=function(t){var e,n,r,i,s,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!=(r=null!=(i=o.body_id)?i:o.id)?r:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}},e.setCanvasVisibility=function(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")},e.getCanvasVisibility=function(){return this.avatarCanvasVisible},e.destroy=function(){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){var t=this.device;this.device=null,requestAnimationFrame(function(){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;var e=document.getElementById("avatar-bg-container");e&&e.parentNode&&e.parentNode.removeChild(e),this.canvas&&this.canvas.parentNode&&this.canvas.remove()},e.setInterrupt=function(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)},e.simulateContextLoss=function(t,e){if(void 0===t&&(t=5e3),void 0===e&&(e=!1),this.device&&this.device.gl){var 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(function(){window.avatarSDKLogger.log("[Test] Auto-restoring context after "+t+"ms..."),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}else window.avatarSDKLogger.warn("[Test] No WebGL device available for testing")},e.getRecoveryStatus=function(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}},e.testStagedRecovery=function(){try{var t=function(){window.avatarSDKLogger.log("[Test] Staged recovery test completed!")},e=this;window.avatarSDKLogger.log("[Test] Starting staged recovery test...");var n=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}],r=_forTo$2(n,function(t){var r=n[t];return window.avatarSDKLogger.log("[Test] Step "+(t+1)+": "+r.desc),Promise.resolve(new Promise(function(t){setTimeout(function(){e.simulateContextLoss(r.delay,r.forceFail),t()},r.delay)})).then(function(){return Promise.resolve(new Promise(function(t){return setTimeout(t,r.delay+2e3)})).then(function(){var n=e.getRecoveryStatus();window.avatarSDKLogger.log("[Test] After step "+(t+1)+":",n)})})});return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){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}var e,n,r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),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}},t}();const _Pact$2=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const t=1&i?e:n;if(t){try{_settle$2(r,1,t(this.v))}catch(t){_settle$2(r,2,t)}return r}return this}return this.o=function(t){try{const i=t.v;1&t.s?_settle$2(r,1,e?e(i):i):n?_settle$2(r,1,n(i)):_settle$2(r,2,i)}catch(t){_settle$2(r,2,t)}},r},t}();function _isSettledPact$2(t){return t instanceof _Pact$2&&1&t.s}function _forTo$2(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact$2(o))return void o.then(a,i||(i=_settle$2.bind(null,r=new _Pact$2,2)));o=o.v}r?_settle$2(r,1,o):r=o}catch(t){_settle$2(r||(r=new _Pact$2),2,t)}}(),r}var BaseTrack=/*#__PURE__*/function(){function t(){}var e=t.prototype;return e.render=function(){},e.stop=function(){},t}(),ImageTrack=/*#__PURE__*/function(t){function e(e,n){var r;return(r=t.call(this)||this).data=e,r.instance=n,r}return _inheritsLoose(e,t),e.prototype.render=function(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null},e}(BaseTrack),SubtitleTrack=/*#__PURE__*/function(t){function e(e,n){var r;return(r=t.call(this)||this).data=e,r.instance=n,r}return _inheritsLoose(e,t),e.prototype.render=function(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)},e}(BaseTrack),TrackRenderer=/*#__PURE__*/function(){function t(t,e){this.TAG="[TrackRenderer]",this.instance=e;var n,r=t.type,i=t.data,s=t.text,a=void 0===s?"":s;"widget_pic"===r&&(this.tracker=new ImageTrack(i,e)),("subtitle_on"===r||"subtitle_off"===r)&&(this.tracker=new SubtitleTrack({type:r,text:a,axis_id:null!=(n=null==i?void 0:i.axis_id)?n:1e3},e))}var e=t.prototype;return e.render=function(){var t;return null==(t=this.tracker)?void 0:t.render()},e.stop=function(){this.tracker.stop()},e.destroy=function(){WidgetDefaultRenderer.destroy(this.instance)},t}(),UIRenderer=/*#__PURE__*/function(){function t(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}var e=t.prototype;return e.render=function(t){var e,n,r,i,s,a,o,l,h,c=this,d=[];if(-1===this.lastFrameIndex){var u=this.options.resourceManager.getConfig();u.init_events&&u.init_events.length>0&&(d=u.init_events.map(function(t){return _extends({},t,{speech_id:0})}))}var f=null;if(f=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,f?f.e=f.e.concat(d):f={e:d}),null!=(e=f)&&e.e){window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(f));var p,m,_=null==(n=f.e)?void 0:n.filter(function(t){return null==(null==t?void 0:t.speech_id)});if(null!=_&&_.length){var g=_.map(function(t){return t.type}).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:"Error: 事件中存在不包含speech_id的事件"+g,e:_})}if(this.enableClientInterrupt&&(f.e=null==(p=f.e)?void 0:p.filter(function(t){return t.speech_id>c.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type})),-1!==this.lastSpeechId&&this.lastSpeechId&&(f.e=null==(m=f.e)?void 0:m.filter(function(t){return(null==t?void 0:t.speech_id)>=c.lastSpeechId})),null!=(r=f.e)&&r.some(function(t){return"speak_start"===t.type})){var v=f.e.find(function(t){return"speak_start"===t.type});this.lastSpeechId=null==v?void 0:v.speech_id,this.onSpeakStateChange("speak_start",v.client_speak_id,(null==v?void 0:v.speech_id)||0)}if((null!=(i=f.e)&&i.some(function(t){return"walk_start"===t.type})||null!=(s=f.e)&&s.some(function(t){return"speak_walk_start"===t.type}))&&this.onWalkStateChange("walk_start"),null!=(a=f.e)&&a.some(function(t){return"voice_start"===t.type})){var y=f.e.find(function(t){return"voice_start"===t.type}),b=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==y?void 0:y.multi_turn_conversation_id}),this.onVoiceStart(b,null==y?void 0:y.client_speak_id)}if((null!=(o=f.e)&&o.some(function(t){return"walk_end"===t.type})||null!=(l=f.e)&&l.some(function(t){return"speak_walk_end"===t.type}))&&this.onWalkStateChange("walk_end"),null!=(h=f.e)&&h.some(function(t){return"voice_end"===t.type})){var S=f.e.find(function(t){return"voice_end"===t.type});this.onVoiceEnd((null==S?void 0:S.client_speak_id)||"",(null==S?void 0:S.speech_id)||0)}["speak_end","speak_error"].forEach(function(t){var e=f.e.find(function(e){return e.type===t});e&&c.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});for(var E=[].concat(f.e),w=0;w<f.e.length;w++){var x=f.e[w];if(!Object.prototype.hasOwnProperty.call(x,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(x);var T=E.indexOf(x);T>-1&&E.splice(T,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[x.type]){WidgetDefaultRenderer.PROXY_WIDGET[x.type](x);var A=E.indexOf(x);A>-1&&E.splice(A,1)}}if(E.length>0)for(var R,P=_createForOfIteratorHelperLoose(E);!(R=P()).done;){var B=new TrackRenderer(R.value,this.options.sdk);this.trackerRenderer.push(B)}return this.trackerRenderer}},e.clearTrackerRenderer=function(){this.trackerRenderer=[]},e.setInterrupt=function(t){this.interruptSpeechId=t},e.destroy=function(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(function(t){return t.destroy()})},t}(),FPSTracker=/*#__PURE__*/function(){function t(t){void 0===t&&(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}var e=t.prototype;return e.tick=function(t){void 0===t&&(t=!0);var e=performance.now();if(this.lastFrameTime>0){var 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},e.getStats=function(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};var t=this.frameTimestamps.reduce(function(t,e){return t+e},0)/this.frameTimestamps.length,e=Math.min.apply(Math,this.frameTimestamps),n=Math.max.apply(Math,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}},e.getCurrentFPS=function(){return this.currentFPS},e.getAverageFPS=function(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)},e.reset=function(){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},e.getDroppedFrames=function(){return this.droppedFrames},t}(),Composition=/*#__PURE__*/function(){function t(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)}var e=t.prototype;return e.compose=function(t){if(!this.audioOnlyMode){var e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);var n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(var r,i=_createForOfIteratorHelperLoose(this.restRenderers);!(r=i()).done;){var s=r.value,a=s.render(t);if(s.clearTrackerRenderer(),a)for(var o,l=_createForOfIteratorHelperLoose(a);!(o=l()).done;){var h=o.value,c=null==h?void 0:h.render();c&&this.container.appendChild(c)}}},e.getFPSStats=function(){return this.fpsTracker.getStats()},e.stop=function(){this.audioRenderer.stop(-1)},e.destroy=function(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(function(t){return t.destroy()})},t}(),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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/\'/g, "'")\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);for(var e=atob(t),n=new Uint8Array(e.length),r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function twoByteToInt16(t,e){var n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){var e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];for(var n=e.length/2,r=new ArrayBuffer(4*n),i=new Float32Array(r),s=0;s<n;s++){var a=2*s,o=twoByteToInt16(e[a],e[a+1]);i[s]=o/32767}return Array.from(i)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];var e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);var n=new Float32Array(e);return Array.from(n)}function _catch$8(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var ParallelDecoder=/*#__PURE__*/function(){function t(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=function(){},this.onDone=function(){},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}var e=t.prototype;return e.getRandomTaskId=function(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)},e.decode=function(t,e){var n=this;if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=function(t,r,i){n.currentDecodedFrameIndex=t.startFrameIndex+i,n._handlePendingAbort(t,i),e(t,r,i)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)},e.clearOldQueue=function(t){this.queue=this.queue.filter(function(e){return e.sf>=t})},e.updateQueue=function(t){if(this.abortAfterFrame=null,0!==this.queue.length){var e,n=this.queue[0].sf,r=t[0].sf;if(r>=this.queue[this.queue.length-1].ef)(e=this.queue).push.apply(e,t);else if(r<n){if(null!==this.currentDecodedFrameIndex&&r>this.currentDecodedFrameIndex+1){this.abortAfterFrame=r-1;var i=this.queue.filter(function(t){return t.ef<r});return void(this.queue=i.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(r===n)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{var s,a=this.queue.findIndex(function(t){return t.sf>=r});-1!==a&&(this.queue.length=a),this.abortAfterFrame=r-1,(s=this.queue).push.apply(s,t)}}else{var o;(o=this.queue).push.apply(o,t)}},e._isIOS=function(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)},e.getQueue=function(){return this.queue.map(function(t){return _extends({},t,{x_offset:[]})})},e.timeoutPromise=function(t,e){return new Promise(function(e,n){setTimeout(function(){n()},t)})},e.loadVideoWithTimeout=function(t){var e=this;return Promise.resolve(_catch$8(function(){return Promise.resolve(Promise.race([e.resourceManager.loadVideo(t),e.timeoutPromise(e.MAX_LOAD_VIDEO_TIMEOUT_MS,"视频 "+t+" 加载超时("+e.MAX_LOAD_VIDEO_TIMEOUT_MS+"ms)")]))},function(){return null}))},e._tryStartNext=function(){try{var t,e,n=this;return e=(null==(t=n.queue)?void 0:t.some(function(t){return null!==n.currentDecodedFrameIndex&&t.sf<n.currentDecodedFrameIndex}))?n._isIOS()?n.maxVideoCount:n.maxVideoCount+1:n._isIOS()?1:n.maxVideoCount,n.dataCacheQueue.getBodyVideoNameListLength()>=e?Promise.resolve():Promise.resolve(function(){if(n.currentParallel<n.maxParallel&&n.queue.length>0){var t,e,r=n.queue.shift();return n.saveAndDownload.appendMultipleToArray("videoData",[_extends({},r,{x_offset:parseUint8ToFloat32(r.x_offset)||[]})]),n._cleanupOldWorkers(null!=(t=null!=(e=r.body_id)?e:r.id)?t:0),n.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,r),r.n?Promise.resolve(n.loadVideoWithTimeout(r.n)).then(function(t){if(!t)return n.currentParallel--,void n._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,r),window.performanceTracker.markStart(performanceConstant.decode_video,r),window.performanceTracker.markStart(performanceConstant.first_decode_video,r),n._startWorker({name:r.n,id:r.id,frameState:r.s,start:r.asf,end:r.aef,hfd:r.hfd,data:t,startFrameIndex:r.sf,endFrameIndex:r.ef,body_id:r.body_id,x_offset:parseUint8ToFloat32(r.x_offset)||[]})}):(n.currentParallel--,n._tryStartNext(),void n.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:"body数据无Name: "+JSON.stringify(r)}))}}())}catch(t){return Promise.reject(t)}},e._startWorker=function(t){var e,n,r,i=this,s=this.currentTaskId;try{r=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}var a=(null!=(e=null!=(n=t.body_id)?n:t.id)?e:0)+"_"+t.name,o=t.data,l=new ArrayBuffer(o.byteLength);new Uint8Array(l).set(new Uint8Array(o)),r.addEventListener("error",function(t){s===i.currentTaskId&&i.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});var h=function(e){if(s===i.currentTaskId)if("frame"===e.data.type)if(i.firstDecodeFrame&&(i.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;i.cacheVideo(),i.onFrame(t,e.data.frame,e.data.index);var o=null!=(n=i.bodyFrameCountMap.get(t.name))?n:0;i.bodyFrameCountMap.set(t.name,o+1),i.abortAfterFrame&&e.data.index+t.startFrameIndex>=i.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",i.abortAfterFrame,t),i.abortOne(a),i.abortAfterFrame=null,i._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var l;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(l=i.bodyFrameCountMap.get(t.name))?l:0)<t.end-t.start-1&&i.bodyFrameCountMap.delete(t.name);var c=i.tasks.get(a);c&&(c.status="done",c.worker.postMessage({type:"abort"})),i.currentParallel--,i.onDone&&i.onDone(t,a),r.removeEventListener("message",h),r.terminate(),i.tasks.delete(a),0===i.currentParallel&&0===i.queue.length&&(i._locked=!1),i._tryStartNext()}else if("error"===e.data.type){var d,u=null!=(d=e.data.error)?d:"",f=u.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;i.reportMessage({code:f,message:u||"视频解码错误",e:{fileName:t.name,error:u}});var p=i.tasks.get(a);p&&(p.status="error",p.worker.postMessage({type:"abort"})),i.currentParallel--,i.onDone&&i.onDone(t,a),r.removeEventListener("message",h),r.terminate(),i.tasks.delete(a),0===i.currentParallel&&0===i.queue.length&&(i._locked=!1)}};r.addEventListener("message",h),this.tasks.set(a,{worker:r,status:"decoding",onMessage:h,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),r.postMessage({type:"decode",file:{data:l},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:s},[l])},e.cacheVideo=function(){for(var t,e=_createForOfIteratorHelperLoose(this.queue.slice(0,this.cacheVideoCount));!(t=e()).done;)this.resourceManager.preloadVideo(t.value.n)},e.abort=function(){this.tasks.forEach(function(t){var e=t.worker,n=t.onMessage;"decoding"===t.status&&(e.postMessage({type:"abort"}),n&&e.removeEventListener("message",n),e.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null},e.abortOne=function(t){var 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))},e.destroy=function(){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},e._handlePendingAbort=function(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)},e._cleanupOldWorkers=function(t){for(var e,n=_createForOfIteratorHelperLoose(this.tasks);!(e=n()).done;){var r=e.value,i=r[0],s=r[1],a=i.split("_"),o=parseInt(a[0],10);!isNaN(o)&&o<t&&(s.worker.postMessage({type:"abort"}),s.onMessage&&s.worker.removeEventListener("message",s.onMessage),s.worker.terminate(),this.tasks.delete(i))}},e.syncDecode=function(t){var e=this.queue.filter(function(e){return e.ef>t});0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())},e._reload=function(){this._offlineLastFrame=0,this.queue=[]},e._offLineMode=function(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()},e._offlineRun=function(){var t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0},e._putOfflineBodyData=function(t){var 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},t}(),FrameAnimationController=/*#__PURE__*/function(){function t(t){var e=void 0===t?{}:t,n=e.defaultSpeed,r=void 0===n?1:n,i=e.frameRate,s=void 0===i?24:i,a=e.frameCallback;this.startTime=null,this.currentFrame=1,this.speed=r,this.frameCallback=a||null,this.frameRate=s,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}var e=t.prototype;return e.play=function(){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)))},e.pause=function(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)},e.reset=function(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null},e.setSpeed=function(t){this.speed=t},e.gotoFrame=function(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()},e.nextFrame=function(){this.currentFrame++,this._updateFrame()},e.prevFrame=function(){this.gotoFrame(this.currentFrame-1)},e.destroy=function(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1},e._animate=function(t){var 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){var n=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;n!==this.currentFrame&&(this.currentFrame=n,this._updateFrame());var r=Date.now()-this.startTimeFromDate,i=Math.floor(Math.floor(r/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=i}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}},e._updateFrame=function(){var 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))},e.getCurrentFrame=function(){if(null!==this.startTime){var t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame},e.updateStartTime=function(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)},_createClass(t,[{key:"playing",get:function(){return this.isPlaying}}])}(),captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t){void 0===t&&(t=navigator);var e=getAudioSession(t);if(!e)return!1;var n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e){void 0===e&&(e=navigator);var n=getAudioSession(e);if(!n)return function(){};var r=playbackSessionRestoredListeners.get(n);return r||(r=new Set,playbackSessionRestoredListeners.set(n,r)),r.add(t),function(){var e,i;null==(e=r)||e.delete(t),0===(null==(i=r)?void 0:i.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}}function _catch$7(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var 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),PCMAudioPlayer=/*#__PURE__*/function(){function t(){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}var e=t.prototype;return e.init=function(){try{var t=this;if(t.isInitialized)return Promise.resolve();configureWebAudioPlaybackSession();var e=window.AudioContext||window.webkitAudioContext;if(!e||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");t.audioCtx=new e({sampleRate:t.SAMPLE_RATE});var n=window.avatarSDKLogger||console;return Promise.resolve(_catch$7(function(){return Promise.resolve(t.audioCtx.audioWorklet.addModule(t.WORKLET_SCRIPT_URL)).then(function(){n.log("[PCMAudioPlayer] Worklet脚本加载完成: "+t.WORKLET_SCRIPT_URL),t.audioWorkletNode=new AudioWorkletNode(t.audioCtx,"pcm-audio-processor"),t.audioWorkletNode.connect(t.audioCtx.destination),n.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),t.audioWorkletNode.port.onmessage=function(e){var r,i;switch(e.data.type){case"cacheStatus":n.log("[PCMAudioPlayer] Worklet缓存状态: "+e.data.size+"字节");break;case"error":n.error("[PCMAudioPlayer] Worklet错误:",e.data.detail);break;case"destroyConfirmed":n.log("[PCMAudioPlayer] Worklet已确认销毁"),null==t.destroyResolve||t.destroyResolve();break;case"syncVolume":void 0!==(null==(r=t.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("volume"))?void 0:r.value)&&(t.audioWorkletNode.parameters.get("volume").value=e.data.volume);break;case"syncSpeed":void 0!==(null==(i=t.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("speed"))?void 0:i.value)&&(t.audioWorkletNode.parameters.get("speed").value=e.data.speed);break;default:n.log("[PCMAudioPlayer] Worklet消息:",e.data)}},t.isInitialized=!0,t.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(function(){t.refreshPlaybackRoute()}),n.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")})},function(t){throw n.error("[PCMAudioPlayer] 初始化失败:",t),t}))}catch(t){return Promise.reject(t)}},e.refreshPlaybackRoute=function(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;var 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(function(e){t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}},e.receivePCMStream=function(t){var 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数据")},e.start=function(){try{var t=function(){e.audioWorkletNode.port.postMessage({type:"start"}),e.isPlaying=!0,n.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")},e=this;if(!e.isInitialized||!e.audioCtx||!e.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");var n=window.avatarSDKLogger||console,r=function(){if("running"!==e.audioCtx.state)return Promise.resolve(e.audioCtx.resume()).then(function(){n.log("[PCMAudioPlayer] AudioContext已恢复运行")})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.pause=function(){if(this.isInitialized&&this.audioWorkletNode){var t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}},e.stop=function(){if(this.isInitialized&&this.audioWorkletNode){var t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}},e.destroy=function(){try{var t=this,e=window.avatarSDKLogger||console;return null==t.unsubscribePlaybackSessionRestored||t.unsubscribePlaybackSessionRestored(),t.unsubscribePlaybackSessionRestored=null,t.detachCapture(),t.isInitialized&&t.audioCtx&&t.audioWorkletNode?Promise.resolve(new Promise(function(n){var r;t.destroyResolve=n,null==(r=t.audioWorkletNode)||r.port.postMessage({type:"destroy"});var i=setTimeout(function(){e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==t.destroyResolve||t.destroyResolve()},300);t.audioWorkletNode&&(t.audioWorkletNode.port.onmessage=function(e){"destroyConfirmed"===e.data.type&&(clearTimeout(i),null==t.destroyResolve||t.destroyResolve())})})).then(function(){function n(){t.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),t.isInitialized=!1,t.isPlaying=!1,t.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")}t.audioWorkletNode.disconnect(),t.audioWorkletNode.port.close(),t.audioWorkletNode=null;var r=function(){if("closed"!==t.audioCtx.state)return Promise.resolve(t.audioCtx.close()).then(function(){})}();return r&&r.then?r.then(n):n()}):(e.log("[PCMAudioPlayer] 播放器未初始化或已销毁"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.attachCapture=function(t){try{var e=this;if(!e.isInitialized||!e.audioCtx||!e.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");return e.captureWorklet?Promise.resolve():(e.captureCallback=t,Promise.resolve(_catch$7(function(){return Promise.resolve(e.audioCtx.audioWorklet.addModule(captureWorkletUrl)).then(function(){var t;e.captureWorklet=new AudioWorkletNode(e.audioCtx,"pcm-capture-processor"),e.audioWorkletNode.connect(e.captureWorklet),e.captureWorklet.port.onmessage=function(t){e.captureCallback&&t.data.pcmData&&e.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(t=window.avatarSDKLogger)||t.log("[PCMAudioPlayer] 捕获节点已挂载")})},function(t){var e;throw null==(e=window.avatarSDKLogger)||e.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t})))}catch(t){return Promise.reject(t)}},e.detachCapture=function(){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},e.resetCaptureBuffer=function(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})},e.getStatus=function(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}},e.setVolume=function(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})},e.setSpeed=function(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})},e.resume=function(){try{var t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(function(){window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(function(t){window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}return Promise.resolve()}catch(t){return Promise.reject(t)}},t}();function _catch$6(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var MediaSourceAudioPlayer=/*#__PURE__*/function(){function t(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()}t.getInstance=function(e){return t.instance||(t.instance=new t(e)),t.instance};var e=t.prototype;return e.createAudioElement=function(t){if(!this.audioElement){var e=document.getElementById("xmov-avatar-audio");if(e)this.audioElement=e;else{var 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}}},e.createNewMediaSource=function(){var t=this;return new Promise(function(e,n){try{if(!t.audioElement)return;t.mediaSource=new MediaSource,t.currentObjectURL=URL.createObjectURL(t.mediaSource),t.audioElement.src=t.currentObjectURL,t.mediaSource.addEventListener("sourceopen",function(){try{if(!t.mediaSource)return;t.sourceBuffer=t.mediaSource.addSourceBuffer(t.MIME_TYPE),t.sourceBuffer.mode="sequence",t.sourceBuffer.addEventListener("updateend",function(){t.isUpdating=!1,t.processQueue()}),t.isInitialized=!0,e()}catch(t){n(t)}}),t.mediaSource.addEventListener("sourceclose",function(){t.isInitialized=!1})}catch(t){n(t)}})},e.destroyCurrentMediaSource=function(t){try{var e=this;try{e.audioElement&&(e.audioElement.pause(),e.audioElement.removeAttribute("src"),e.audioElement.load())}catch(t){}try{e.currentObjectURL&&(URL.revokeObjectURL(e.currentObjectURL),e.currentObjectURL=null)}catch(t){}return e.mediaSource=null,e.sourceBuffer=null,e.isInitialized=!1,e.isPlaying=!1,e.queue=[],e.isUpdating=!1,Promise.resolve(e.createNewMediaSource()).then(function(){t()})}catch(t){return Promise.reject(t)}},e.stop=function(t){this.destroyCurrentMediaSource(t)},e.addAudioSegment=function(t){try{var e=this;return e.isDestroyed||(e.queue.push({data:t}),e.processQueue()),Promise.resolve()}catch(t){return Promise.reject(t)}},e.processQueue=function(){if(!this.isDestroyed&&this.sourceBuffer&&this.mediaSource&&!this.isUpdating&&0!==this.queue.length&&!this.sourceBuffer.updating&&"open"===this.mediaSource.readyState){this.isUpdating=!0;var t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}},e.start=function(){try{var t=this;if(t.isDestroyed||!t.audioElement||t.isPlaying)return Promise.resolve();var e=_catch$6(function(){return t.audioElement.currentTime=0,t.isPlaying=!0,Promise.resolve(t.audioElement.play()).then(function(){window.avatarSDKLogger.log("mseAudioPlayer开始播放",t.getStats(),Date.now())})},function(){});return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.getStats=function(){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"}},e.setSpeed=function(t){this.setPlaybackRate(t)},e.getBufferedRanges=function(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){for(var e=[],n=0;n<this.sourceBuffer.buffered.length;n++){var r=this.sourceBuffer.buffered.start(n).toFixed(2),i=this.sourceBuffer.buffered.end(n).toFixed(2);e.push("["+r+"-"+i+"]")}return e.join(", ")}}catch(t){return"-"}return"-"},e.setVolume=function(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)},e.setPlaybackRate=function(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)},e.destroy=function(){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,t.instance=null},t}();function _catch$5(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var AudioRender=/*#__PURE__*/function(){function t(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)}var e=t.prototype;return e.updateAudioData=function(t){if(this.resourceManager.config.raw_audio&&t[0].sid!==this.oldSpeechId){-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);for(var e,n=0,r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var i;n+=(null==(i=e.value.ad)?void 0:i.length)||0}for(var s,a,o,l=new Uint8Array(n),h=0,c=_createForOfIteratorHelperLoose(t);!(s=c()).done;){var d=s.value;d.ad&&(l.set(new Uint8Array(d.ad),h),h+=d.ad.length)}-1===this.speech_id?(this.speech_id=t[0].sid,null==(a=this.audio)||a.receivePCMStream(l)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(l)):null==(o=this.audio)||o.receivePCMStream(l)}},e._updateAudio=function(t){if(this.mseAudioPlayer&&0!==t.length){var 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(var r,i=_createForOfIteratorHelperLoose(t);!(r=i()).done;){var s=r.value;this.mseCacheAudioData.push({data:s.ad,frameIndex:s.sf,speechId:s.sid})}}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(var a,o=_createForOfIteratorHelperLoose(t);!(a=o()).done;){var l=a.value;if(l.ad){var h=l.ad instanceof ArrayBuffer?l.ad:l.ad.buffer.slice(l.ad.byteOffset,l.ad.byteOffset+l.ad.byteLength);this.mseAudioPlayer.addAudioSegment(h)}}}}},e.render=function(t){try{var e,n=this;if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",n.firstFrameIndex),-1===n.lastFrameIndex&&(n.lastFrameIndex=t),n.options.sdk.getStatus()===AvatarStatus.offline)return Promise.resolve();if(t>=n.firstFrameIndex&&-1!=n.firstFrameIndex&&!n.isPlaying&&n.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),n.isPlaying=!0,null==(e=n.audio)||e.start(),Promise.resolve();var r=function(){if(!n.resourceManager.config.raw_audio&&n.mseAudioPlayer){var e=function(){if(-1!==n.firstFrameIndex&&t>=n.firstFrameIndex&&!n.mseAudioPlayer.isPlaying&&!n.isPlaying){var e=n.mseAudioPlayer.getStats(),r=e.queueLength>0||"-"!==e.bufferedRanges,i=function(){if(r){var i=_catch$5(function(){return window.avatarSDKLogger.log("开始播放",t),n.isPlaying=!0,Promise.resolve(n.mseAudioPlayer.start()).then(function(){window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")})},function(r){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:r,frameIndex:t,firstFrameIndex:n.firstFrameIndex,queueLength:e.queueLength})});if(i&&i.then)return i.then(function(){})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]","等待更多 WebM 音频数据 (frameIndex: "+t+", queueLength: "+e.queueLength+")")}();if(i&&i.then)return i.then(function(){})}}();if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.resume=function(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())},e.pause=function(){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},e.stop=function(t){var e,n,r;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==(r=this.mseAudioPlayer)||r.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(var i,s=_createForOfIteratorHelperLoose(this.cacheAudioData);!(i=s()).done;){var a;null==(a=this.audio)||a.receivePCMStream(i.value)}this.cacheAudioData=[]}},e.addNewAudioSegment=function(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(var t,e=_createForOfIteratorHelperLoose(this.mseCacheAudioData);!(t=e()).done;){var n,r=t.value;r.data&&(null==(n=this.mseAudioPlayer)||n.addAudioSegment(r.data))}this.mseCacheAudioData=[]}},e.setVolume=function(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)},e.setSpeed=function(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)},e.getAudioPlayer=function(){return this.audio},e.destroy=function(){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},t}(),SaveAndDownload=/*#__PURE__*/function(){function t(t,e){void 0===t&&(t="avatarData.json"),void 0===e&&(e=!1),this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}var e=t.prototype;return e.initDownloadButton=function(){var t=this;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",function(){t.download()}),document.body.appendChild(this.downloadButton))},e.writeFields=function(t){this.enabled&&Object.assign(this.data,t)},e.appendMultipleToArray=function(t,e){var n;this.enabled&&(this.data[t]||(this.data[t]=[]),(n=this.data[t]).push.apply(n,e))},e.download=function(){if(this.enabled){var t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}},e.generateJSONContent=function(){return JSON.stringify(this.data,null,2)},e.downloadFile=function(t,e,n){if(this.enabled){var r=new Blob([t],{type:n}),i=URL.createObjectURL(r);this.downloadButton.href=i,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=i}},t}(),RenderScheduler=/*#__PURE__*/function(){function t(t){var e=this;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:function(t){e.onDownloadProgress(t)},onStateChange:function(e){t.onStateChange(e)},onRenderChange:function(n){t.onRenderChange(n,e.renderState),e.renderState=n},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:function(e){t.onWalkStateChange(e)},onVoiceStart:function(e,n){t.onVoiceStateChange("start",e,n)},onVoiceEnd:function(n,r){e.stopAudio(r),t.onVoiceStateChange("end",void 0,n)},onSpeakStateChange:function(n,r,i){"speak_start"===n?(e.currentSpeechId=i,e.avatarRenderer.setInterrupt(!1)):"speak_end"===n&&(e.dataCacheQueue.clearSubtitleOn(i),i>=e.currentSpeechId&&e.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(n,r)},sendSdkPoint:function(e,n,r){t.sendSdkPoint(e,n,r)}}),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:function(t){e.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:function(n,r){if(!e.hasSendTimeJson&&r&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",r),e.sendMessage("client_error",r),e.hasSendTimeJson=!0),t.renderFrameCallback(n+=e.offsetFrame),e.isStartPlay&&(e.composition.compose(n),e.decoder._tryStartNext(),t.onFrameDataUpdate)){var i=e.avatarRenderer._getCurrentFrameData(n);t.onFrameDataUpdate({frameIndex:n,body:i.body,face:i.face})}}})}var e=t.prototype;return e.init=function(){if(!this.audioOnlyMode){var 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})}},e.handleData=function(t,e){var n,r,i;try{var s=this;if(s.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return Promise.resolve();var a=s.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:s.decoder.clearOldQueue(a);var o=a,l=[].concat(e).filter(function(t){return t.ef>o});window.avatarSDKLogger.log(l,"mp4List"),l.length>0&&(s.renderState!==RenderState.paused&&a&&a>e[0].sf&&a>10&&s.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:"Error: 身体数据过期 cur:"+a+"-sf:"+e[0].sf,e:e}),s.decoder.decode(l,function(t,e,n){var r,i;t.start<=n&&t.end>=n&&(s.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&&s.decoder.abortOne((null!=(r=null!=(i=t.body_id)?i:t.id)?r:0)+"_"+t.name))}));break;case EFrameDataType.FACE:s.dataCacheQueue.clearOldFaceData(a);var h=s.handleFaceData(e);h.length>0&&s.saveAndDownload.appendMultipleToArray("faceData",h),s.dataCacheQueue.checkValidData(h,t);for(var c=[],d=[],u=0;u<h.length;u++){var f;null!=(f=h[u])&&f.face_frame_type?d.push(h[u]):c.push(h[u])}d.length&&s.dataCacheQueue._updateFacial(d),c.length&&s.dataCacheQueue._updateRealFacial(c);break;case EFrameDataType.AUDIO:if(s.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),s.renderState!==RenderState.paused&&a>e[0].sf){var p=a?a-e[0].sf:0;s.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:"Error: 音频数据过期 cur:"+a+"-sf:"+e[0].sf,e:{currentFrame:a,sf:e[0].sf,ef:p,timestamp:Date.now()}}),s.sendSdkPoint("audio_data_expired",{currentFrame:a,sf:e[0].sf,ef:p,timestamp:Date.now()})}var m=e[0],_=m.sf,g=m.ef-_;if(g<=0)return Promise.resolve();var v=(a||0)-_;if(v>g)return Promise.resolve();var y=1;if(v>0&&(y=g/Math.max(g-v,.1)),s._speedResetTimer&&clearTimeout(s._speedResetTimer),y>4)return Promise.resolve();s.audioRenderer.setSpeed(y),s._speedResetTimer=setTimeout(function(){s.audioRenderer.setSpeed(1),s._speedResetTimer=null},g*(1e3/24)/y),s.dataCacheQueue.checkValidData(e,t);var b,S=e.map(function(t){return s.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)})});if(S[0].sid<=s.lastSpeechId)return Promise.resolve();s.resourceManager.config.raw_audio?(null==(b=window.avatarSDKLogger)||b.log(s.TAG,"processedAudioData[0].sid",S[0].sid,s.currentSpeechId,s.renderState),s.audioRenderer.updateAudioData(S)):s.audioRenderer._updateAudio(S);break;case EFrameDataType.EVENT:s.dataCacheQueue.clearOldEvent(a);var E=e;s.setEventData({sf:E[0].sf,ef:E[0].ef,event:E[0].e});for(var w,x=!1,T=null,A=null,R=_createForOfIteratorHelperLoose(E);!(w=R()).done;){var P,B=w.value,C=null!=(P=B.e)?P:[];if(C.some(function(t){return"speak_start"===t.type})&&(x=!0),B.sf<a&&(T||(T=C.find(function(t){return"speak_start"===t.type})||null),A||(A=C.find(function(t){return"voice_start"===t.type})||null),T&&A))break}if(x&&s.audioRenderer.isPlaying){var I;s.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});var k,D,U=E.flatMap(function(t){var e;return null!=(e=t.e)?e:[]}).find(function(t){return"speak_start"===t.type}),O=null!=(I=null==U?void 0:U.speech_id)?I:0,F=s.audioRenderer.speech_id;-1!==F&&F<O&&(s.interrupt("new_speak_start",F),-1!==s.audioRenderer.speech_id&&s.audioRenderer.pause()),U&&(s.currentSpeechId=null!=(k=U.speech_id)?k:0,s.avatarRenderer.setInterrupt(!1),s.uiRenderer.lastSpeechId=null!=(D=U.speech_id)?D:0)}if(T){var L=T.speech_id,M=T.client_speak_id;s.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),s.currentSpeechId=null!=L?L:0,s.avatarRenderer.setInterrupt(!1),s.uiRenderer.lastSpeechId=null!=L?L:0,s.config.onSpeakStateChange("speak_start",null!=M?M:0)}if(A){var N,z;s.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});var G=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");s.config.onVoiceStateChange("start",G,null!=(N=null==(z=A)?void 0:z.client_speak_id)?N:"")}for(var j,W=E.filter(function(t){return-1===t.sf&&-1===t.ef}),H=_createForOfIteratorHelperLoose(W);!(j=H()).done;)for(var V=j.value,$=0;$<V.e.length;$++){var K=V.e[$];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(K);else if(WidgetDefaultRenderer.PROXY_WIDGET){var Y,X;null==(Y=WidgetDefaultRenderer.PROXY_WIDGET)||null==(X=Y[K.type])||X.call(Y,K)}}var Z=E.filter(function(t){return-1!==t.sf});s.dataCacheQueue._updateUiEvent(Z);break;case EFrameDataType.SYNC_FRAME:var q=e;if(null!=(n=s.sdk.getOptions().config)&&n.replay||(null==q?void 0:q.source)!==FRAME_SOURCE_SOURCE)return Promise.resolve();var Q=Date.now()/1e3,J=null!=(r=q.client_time)?r:0,tt=((null!=(i=q.server_client_frame)?i:0)+(Q-J)/2*24).toFixed(0);s.offsetFrame+=Number(tt)-Number(null!=a?a:0);break;default:s.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}return Promise.resolve()}catch(t){return Promise.reject(t)}},e.setOffsetFrame=function(t){this.offsetFrame+=t},e.setVolume=function(t){this.audioRenderer.setVolume(t)},e.runStartFrameIndex=function(){var t;null==(t=this.frameAnimationController)||t.play()},e.stateChangeHandle=function(t){this.dataCacheQueue.currentPlayState=t},e.stopAudio=function(t){this.audioRenderer.stop(t)},e.render=function(){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)},e.stop=function(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()},e.pauseRender=function(){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))},e.resumeRender=function(){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==="))},e.switchInvisibleMode=function(){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+",无法切换隐身模式")}},e.getRenderState=function(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,"getRenderState: "+this.renderState),this.renderState},e.destroy=function(){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()},e.handleFaceData=function(t){try{var e,n=this.resourceManager.resource_pack,r=this.resourceManager.getConfig().framedata_proto_version,i=[].concat(null!=(e=n.blendshape_map)?e:[]);return t.map(function(t){var e=[],n=t.body_id,s=t.sf,a=t.ef,o=t.s,l=t.id,h=t.js,c=t.bsw,d=t.ms,u=t.face_frame_type,f=t.asf,p=t.aef,m=t.n,_=t.cs,g=[];if((null==i?void 0:i.length)>0){for(var v=0;v<i.length;v++){var y=i[v];if((null==y?void 0:y.length)>0)for(var b=0;b<y.length;b++)e[v]||(e[v]=[]),e[v][b]=c[y[b]]}g=Array.from({length:d.length},r?function(t,n){var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=d[n])?void 0:i.index)?r:0,texturePCAWeights:null!=(s=null==(a=d[n])?void 0:a.weights)?s:[]}}:function(t,n){var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=d[n])?void 0:i[0])?r:0,texturePCAWeights:null!=(s=null==(a=d[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:d.length},r?function(t,e){var n,r,i,s;return{blendshapeWeights:0===e?c:[],textureModelIndex:null!=(n=null==(r=d[e])?void 0:r.index)?n:0,texturePCAWeights:null!=(i=null==(s=d[e])?void 0:s.weights)?i:[]}}:function(t,e){var n,r,i,s;return{blendshapeWeights:0===e?c:[],textureModelIndex:null!=(n=null==(r=d[e])?void 0:r[0])?n:0,texturePCAWeights:null!=(i=null==(s=d[e])?void 0:s[1])?i:[]}});return{body_id:n,frameIndex:s,sf:s,ef:a,asf:f,aef:p,n:m,cs:_,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:h.map(r?function(t){return formatMJT(t.translate,t.rotate)}:function(t){return formatMJT(t[0],t[1])}),blendshapeWeights:c}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}},e.forceSyncDecoder=function(){var t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)},e._reload=function(){this.decoder._reload()},e._getResumeInfo=function(){var t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)},e.sendVoiceEnd=function(){var t,e,n,r=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:r,ef:r+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}]}])},e.markReconnectRecover=function(){this.audioRenderer.resume(),this.decoder._reload()},e._offlineMode=function(){var t,e;this.dataCacheQueue._clearEvent();var 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();var r=this.getCurrentFrameIndex();r&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),r),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1},e._offlineRun=function(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()},e.ttsaStateChangeHandle=function(t){this.dataCacheQueue.currentTtsaState=t},e.resume=function(){this.audioRenderer.resume()},e.pauseForBackground=function(){this.audioRenderer.pause()},e.setAvatarCanvasVisible=function(t){this.avatarRenderer.setCanvasVisibility(t)},e.setCharacterCanvasLayout=function(t){this.avatarRenderer.setCharacterCanvasAnchor(t)},e.setWalkConfig=function(t){this.avatarRenderer.setWalkConfig(t)},e.interrupt=function(t,e){var n,r=Date.now(),i=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:i,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(i),this.dataCacheQueue.clearSubtitleOn(i);var 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!=i?i:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(i),this.uiRenderer.setInterrupt(i),Date.now()-r},e.seekToFrame=function(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)},e.getCurrentFrameIndex=function(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame},e.getSpeechId=function(){return this.audioRenderer.speech_id},e.getAudioRenderer=function(){return this.audioRenderer},e.simulateContextLoss=function(t,e){void 0===t&&(t=5e3),void 0===e&&(e=!1),this.avatarRenderer.simulateContextLoss(t,e)},e.getRecoveryStatus=function(){return this.avatarRenderer.getRecoveryStatus()},e.testStagedRecovery=function(){try{return Promise.resolve(this.avatarRenderer.testStagedRecovery())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){return this.avatarRenderer.restartWebGL()},t}();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,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,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,r=e.max_code,i=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,c,d,u,f,p,m=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++)c=t.heap[h],u=n[2*n[2*c+1]+1]+1,u>l&&(u=l,m++),n[2*c+1]=u,c>r||(t.bl_count[u]++,f=0,c>=o&&(f=a[c-o]),p=n[2*c],t.opt_len+=p*(u+f),s&&(t.static_len+=p*(i[2*c+1]+f)));if(0!==m){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]--,m-=2}while(m>0);for(u=l;0!==u;u--)for(c=t.bl_count[u];0!==c;)d=t.heap[--h],d>r||(n[2*d+1]!==u&&(t.opt_len+=(u-n[2*d+1])*n[2*d],n[2*d+1]=u),c--)}},gen_codes=(t,e,n)=>{const r=new Array(MAX_BITS$1+1);let i,s,a=0;for(i=1;i<=MAX_BITS$1;i++)a=a+n[i-1]<<1,r[i]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(r[e]++,e))}},tr_static_init=()=>{let t,e,n,r,i;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,t=0;t<1<<extra_lbits[r];t++)_length_code[n++]=r;for(_length_code[n-1]=r,i=0,r=0;r<16;r++)for(base_dist[r]=i,t=0;t<1<<extra_dbits[r];t++)_dist_code[i++]=r;for(i>>=7;r<D_CODES$1;r++)for(base_dist[r]=i<<7,t=0;t<1<<extra_dbits[r]-7;t++)_dist_code[256+i++]=r;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,r)=>{const i=2*e,s=2*n;return t[i]<t[s]||t[i]===t[s]&&r[e]<=r[n]},pqdownheap=(t,e,n)=>{const r=t.heap[n];let i=n<<1;for(;i<=t.heap_len&&(i<t.heap_len&&smaller(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!smaller(e,r,t.heap[i],t.depth));)t.heap[n]=t.heap[i],n=i,i<<=1;t.heap[n]=r},compress_block=(t,e,n)=>{let r,i,s,a,o=0;if(0!==t.sym_next)do{r=255&t.pending_buf[t.sym_buf+o++],r+=(255&t.pending_buf[t.sym_buf+o++])<<8,i=t.pending_buf[t.sym_buf+o++],0===r?send_code(t,i,e):(s=_length_code[i],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(i-=base_length[s],send_bits(t,i,a)),r--,s=d_code(r),send_code(t,s,n),a=extra_dbits[s],0!==a&&(r-=base_dist[s],send_bits(t,r,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,r=e.stat_desc.static_tree,i=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--,i&&(t.static_len-=r[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 r,i,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=a,a=e[2*(r+1)+1],++o<l&&i===a||(o<h?t.bl_tree[2*i]+=o:0!==i?(i!==s&&t.bl_tree[2*i]++,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=i,0===a?(l=138,h=3):i===a?(l=6,h=3):(l=7,h=4))},send_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,h=4;for(0===a&&(l=138,h=3),r=0;r<=n;r++)if(i=a,a=e[2*(r+1)+1],!(++o<l&&i===a)){if(o<h)do{send_code(t,i,t.bl_tree)}while(0!==--o);else 0!==i?(i!==s&&(send_code(t,i,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=i,0===a?(l=138,h=3):i===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,r)=>{let i;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,r-4,4),i=0;i<r;i++)send_bits(t,t.bl_tree[2*bl_order[i]+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,r)=>{send_bits(t,(STORED_BLOCK<<1)+(r?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,r)=>{let i,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),i=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=i&&(i=s)):i=s=n+5,n+4<=i&&-1!==e?_tr_stored_block$1(t,e,n,r):t.strategy===Z_FIXED$1||s===i?(send_bits(t,(STATIC_TREES<<1)+(r?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(r?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),r&&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,r)=>{let i=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{i=i+e[r++]|0,s=s+i|0}while(--a);i%=65521,s%=65521}return i|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,r)=>{const i=crcTable,s=r+n;t^=-1;for(let n=r;n<s;n++)t=t>>>8^i[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_init,_tr_stored_block:_tr_stored_block,_tr_flush_block:_tr_flush_block,_tr_tally:_tr_tally,_tr_align:_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH: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_FILTERED,Z_HUFFMAN_ONLY:Z_HUFFMAN_ONLY,Z_RLE:Z_RLE,Z_FIXED:Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN: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,r,i=t.w_size;e=t.hash_size,r=e;do{n=t.head[--r],t.head[r]=n>=i?n-i:0}while(--e);e=i,r=e;do{n=t.prev[--r],t.prev[r]=n>=i?n-i: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,r)=>{let i=t.avail_in;return i>r&&(i=r),0===i?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,i,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,i,n)),t.next_in+=i,t.total_in+=i,i)},longest_match=(t,e)=>{let n,r,i=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,c=t.w_mask,d=t.prev,u=t.strstart+MAX_MATCH;let f=h[s+a-1],p=h[s+a];t.prev_length>=t.good_match&&(i>>=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(r=MAX_MATCH-(u-s),s=u-MAX_MATCH,r>a){if(t.match_start=e,a=r,r>=o)break;f=h[s+a-1],p=h[s+a]}}}while((e=d[e&c])>l&&0!==--i);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,r,i;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-r),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),r+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=HASH(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[i+MIN_MATCH-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,r,i,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,i=t.bi_valid+42>>3,t.strm.avail_out<i)break;if(i=t.strm.avail_out-i,r=t.strstart-t.block_start,n>r+t.strm.avail_in&&(n=r+t.strm.avail_in),n>i&&(n=i),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==r+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===r+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),r&&(r>n&&(r=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+r),t.strm.next_out),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r,t.block_start+=r,n-=r),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:(i=t.window_size-t.strstart,t.strm.avail_in>i&&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++,i+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),i>t.strm.avail_in&&(i=t.strm.avail_in),i&&(read_buf(t.strm,t.window,t.strstart,i),t.strstart+=i,t.insert+=i>t.w_size-t.insert?t.w_size-t.insert:i),t.high_water<t.strstart&&(t.high_water=t.strstart),i=t.bi_valid+42>>3,i=t.pending_buf_size-i>65535?65535:t.pending_buf_size-i,s=i>t.w_size?t.w_size:i,r=t.strstart-t.block_start,(r>=s||(r||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&r<=i)&&(n=r>i?i:r,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===r?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,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),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(r=_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 r=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(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,r,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),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){i=t.strstart+t.lookahead-MIN_MATCH,r=_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<=i&&(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++,r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(r=_tr_tally(t,0,t.window[t.strstart-1]),r&&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&&(r=_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,r,i,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&&(i=t.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){s=t.strstart+MAX_MATCH;do{}while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&i<s);t.match_length=MAX_MATCH-(s-i),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,r,i){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=r,this.func=i}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,r,i,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||e<0||e>9||s<0||s>Z_FIXED||8===r&&1!==a)return err(t,Z_STREAM_ERROR$2);8===r&&(r=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=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+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<<i+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 r=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(r)&&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,r=-1;if(r=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=r<<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,r=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+r>n.pending_buf_size;){let i=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+i),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+=i,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,r-=i}let i=new Uint8Array(n.gzhead.extra);n.pending_buf.set(i.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending+=r,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,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=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>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=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>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r))}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 r=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(r!==BS_FINISH_STARTED&&r!==BS_FINISH_DONE||(n.status=FINISH_STATE),r===BS_NEED_MORE||r===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(r===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 r=t.state,i=r.wrap;if(2===i||1===i&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(1===i&&(t.adler=adler32_1(t.adler,e,n,0)),r.wrap=0,n>=r.w_size){0===i&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let t=new Uint8Array(r.w_size);t.set(e.subarray(n-r.w_size,n),0),e=t,n=r.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(r);r.lookahead>=MIN_MATCH;){let t=r.strstart,e=r.lookahead-(MIN_MATCH-1);do{r.ins_h=HASH(r,r.ins_h,r.window[t+MIN_MATCH-1]),r.prev[t&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=t,t++}while(--e);r.strstart=t,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,r.wrap=i,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: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,r=t.length;n<r;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,r=0,i=t.length;e<i;e++){let i=t[e];n.set(i,r),r+=i.length}return n},common={assign:assign,flattenChunks: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,r,i,s,a=t.length,o=0;for(i=0;i<a;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),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 r=0;r<e;r++)n+=String.fromCharCode(t[r]);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 r,i;const s=new Array(2*n);for(i=0,r=0;r<n;){let e=t[r++];if(e<128){s[i++]=e;continue}let a=_utf8len[e];if(a>4)s[i++]=65533,r+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&r<n;)e=e<<6|63&t[r++],a--;a>1?s[i++]=65533:e<65536?s[i++]=e:(e-=65536,s[i++]=55296|e>>10&1023,s[i++]=56320|1023&e)}}return buf2binstring(s,i)},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:string2buf,buf2string:buf2string,utf8border: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_SYNC_FLUSH,Z_FULL_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_COMPRESSION,Z_DEFAULT_STRATEGY: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,r=this.options.chunkSize;let i,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(r),n.next_out=0,n.avail_out=r),(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(i=deflate_1$2.deflate(n,s),i===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=deflate_1$2.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===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,r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x,T;const A=t.state;n=t.next_in,x=t.input,r=n+(t.avail_in-5),i=t.next_out,T=t.output,s=i-(e-t.avail_out),a=i+(t.avail_out-257),o=A.dmax,l=A.wsize,h=A.whave,c=A.wnext,d=A.window,u=A.hold,f=A.bits,p=A.lencode,m=A.distcode,_=(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),v=p[u&_];e:for(;;){if(y=v>>>24,u>>>=y,f-=y,y=v>>>16&255,0===y)T[i++]=65535&v;else{if(!(16&y)){if(64&y){if(32&y){A.mode=TYPE$1;break t}t.msg="invalid literal/length code",A.mode=BAD$1;break t}v=p[(65535&v)+(u&(1<<y)-1)];continue e}for(b=65535&v,y&=15,y&&(f<y&&(u+=x[n++]<<f,f+=8),b+=u&(1<<y)-1,u>>>=y,f-=y),f<15&&(u+=x[n++]<<f,f+=8,u+=x[n++]<<f,f+=8),v=m[u&g];;){if(y=v>>>24,u>>>=y,f-=y,y=v>>>16&255,16&y){if(S=65535&v,y&=15,f<y&&(u+=x[n++]<<f,f+=8,f<y&&(u+=x[n++]<<f,f+=8)),S+=u&(1<<y)-1,S>o){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(u>>>=y,f-=y,y=i-s,S>y){if(y=S-y,y>h&&A.sane){t.msg="invalid distance too far back",A.mode=BAD$1;break t}if(E=0,w=d,0===c){if(E+=l-y,y<b){b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}}else if(c<y){if(E+=l+c-y,y-=c,y<b){b-=y;do{T[i++]=d[E++]}while(--y);if(E=0,c<b){y=c,b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}}}else if(E+=c-y,y<b){b-=y;do{T[i++]=d[E++]}while(--y);E=i-S,w=T}for(;b>2;)T[i++]=w[E++],T[i++]=w[E++],T[i++]=w[E++],b-=3;b&&(T[i++]=w[E++],b>1&&(T[i++]=w[E++]))}else{E=i-S;do{T[i++]=T[E++],T[i++]=T[E++],T[i++]=T[E++],b-=3}while(b>2);b&&(T[i++]=T[E++],b>1&&(T[i++]=T[E++]))}break}if(64&y){t.msg="invalid distance code",A.mode=BAD$1;break t}v=m[(65535&v)+(u&(1<<y)-1)]}}break}}while(n<r&&i<a);b=f>>3,n-=b,f-=b<<3,u&=(1<<f)-1,t.next_in=n,t.next_out=i,t.avail_in=n<r?r-n+5:5-(n-r),t.avail_out=i<a?a-i+257:257-(i-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,r,i,s,a,o)=>{const l=o.bits;let h,c,d,u,f,p,m=0,_=0,g=0,v=0,y=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 P,B,C,I=null;for(m=0;m<=MAXBITS;m++)A[m]=0;for(_=0;_<r;_++)A[e[n+_]]++;for(y=l,v=MAXBITS;v>=1&&0===A[v];v--);if(y>v&&(y=v),0===v)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(g=1;g<v&&0===A[g];g++);for(y<g&&(y=g),E=1,m=1;m<=MAXBITS;m++)if(E<<=1,E-=A[m],E<0)return-1;if(E>0&&(t===CODES$1||1!==v))return-1;for(R[1]=0,m=1;m<MAXBITS;m++)R[m+1]=R[m]+A[m];for(_=0;_<r;_++)0!==e[n+_]&&(a[R[e[n+_]]++]=_);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,_=0,m=g,f=s,b=y,S=0,d=-1,w=1<<y,u=w-1,t===LENS$1&&w>ENOUGH_LENS$1||t===DISTS$1&&w>ENOUGH_DISTS$1)return 1;for(;;){P=m-S,a[_]+1<p?(B=0,C=a[_]):a[_]>=p?(B=I[a[_]-p],C=T[a[_]-p]):(B=96,C=0),h=1<<m-S,c=1<<b,g=c;do{c-=h,i[f+(x>>S)+c]=P<<24|B<<16|C}while(0!==c);for(h=1<<m-1;x&h;)h>>=1;if(0!==h?(x&=h-1,x+=h):x=0,_++,0===--A[m]){if(m===v)break;m=e[n+a[_]]}if(m>y&&(x&u)!==d){for(0===S&&(S=y),f+=g,b=m-S,E=1<<b;b+S<v&&(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;d=x&u,i[d]=y<<24|b<<16|f-s}}return 0!==x&&(i[f+x]=m-S<<24|64<<16),o.bits=y,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK:Z_BLOCK,Z_TREES: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_BUF_ERROR,Z_DEFLATED: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 r=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!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.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 r=inflateReset2(t,e);return r!==Z_OK$1&&(t.state=null),r},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,r)=>{let i;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)),r>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>r&&(i=r),s.window.set(e.subarray(n-r,n-r+i),s.wnext),(r-=i)?(s.window.set(e.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0},inflate$2=(t,e)=>{let n,r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x=0;const T=new Uint8Array(4);let A,R;const P=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,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,h=n.hold,c=n.bits,d=o,u=l,w=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=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,c-=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,c=0;break;case FLAGS:for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=TIME;case TIME:for(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=OS;case OS:for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=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,c=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(r.subarray(s,s+f),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,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=r[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,r,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=r[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,r,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(;c<16;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(4&n.wrap&&h!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}h=0,c=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(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}t.adler=n.check=zswap32(h),h=0,c=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=c,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&c,c-=7&c,n.mode=CHECK;break}for(;c<3;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}switch(n.last=1&h,h>>>=1,c-=1,3&h){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){h>>>=2,c-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}h>>>=2,c-=2;break;case STORED:for(h>>>=7&c,c-=7&c;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&h,h=0,c=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;i.set(r.subarray(s,s+f),a),o-=f,s+=f,l-=f,a+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;c<14;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(n.nlen=257+(31&h),h>>>=5,c-=5,n.ndist=1+(31&h),h>>>=5,c-=5,n.ncode=4+(15&h),h>>>=4,c-=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(;c<3;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.lens[P[n.have++]]=7&h,h>>>=3,c-=3}for(;n.have<19;)n.lens[P[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],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(v<16)h>>>=_,c-=_,n.lens[n.have++]=v;else{if(16===v){for(R=_+2;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(h>>>=_,c-=_,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,c-=2}else if(17===v){for(R=_+3;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=_,c-=_,E=0,f=3+(7&h),h>>>=3,c-=3}else{for(R=_+7;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=_,c-=_,E=0,f=11+(127&h),h>>>=7,c-=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=c,inffast(t,u),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,h=n.hold,c=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;x=n.lencode[h&(1<<n.lenbits)-1],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(g&&!(240&g)){for(y=_,b=g,S=v;x=n.lencode[S+((h&(1<<y+b)-1)>>y)],_=x>>>24,g=x>>>16&255,v=65535&x,!(y+_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=y,c-=y,n.back+=y}if(h>>>=_,c-=_,n.back+=_,n.length=v,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;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.length+=h&(1<<n.extra)-1,h>>>=n.extra,c-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;x=n.distcode[h&(1<<n.distbits)-1],_=x>>>24,g=x>>>16&255,v=65535&x,!(_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(!(240&g)){for(y=_,b=g,S=v;x=n.distcode[S+((h&(1<<y+b)-1)>>y)],_=x>>>24,g=x>>>16&255,v=65535&x,!(y+_<=c);){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}h>>>=y,c-=y,n.back+=y}if(h>>>=_,c-=_,n.back+=_,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=v,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(R=n.extra;c<R;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}n.offset+=h&(1<<n.extra)-1,h>>>=n.extra,c-=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),m=n.window}else m=i,p=a-n.offset,f=n.length;f>l&&(f=l),l-=f,n.length-=f;do{i[a++]=m[p++]}while(--f);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;i[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;c<32;){if(0===o)break t;o--,h|=r[s++]<<c,c+=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,i,u,a-u):adler32_1(n.check,i,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,c=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;c<32;){if(0===o)break t;o--,h+=r[s++]<<c,c+=8}if(4&n.wrap&&h!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}h=0,c=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=c,(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),d-=t.avail_in,u-=t.avail_out,t.total_in+=d,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,t.next_out-u):adler32_1(n.check,i,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===d&&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 r,i,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(r=t.state,0!==r.wrap&&r.mode!==DICT?Z_STREAM_ERROR$1:r.mode===DICT&&(i=1,i=adler32_1(i,e,n,0),i!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.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: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_NO_FLUSH,Z_FINISH:Z_FINISH,Z_OK:Z_OK,Z_STREAM_END:Z_STREAM_END,Z_NEED_DICT:Z_NEED_DICT,Z_STREAM_ERROR:Z_STREAM_ERROR,Z_DATA_ERROR:Z_DATA_ERROR,Z_MEM_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,r=this.options.chunkSize,i=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(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&i&&(s=inflate_1$2.inflateSetDictionary(n,i),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,i=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=r-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(i)}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:constants};const{Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip}=deflate_1$1,{Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip: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};function _catch$4(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var request=function(t,e){try{var n,r,i,s,a,o,l;void 0===e&&(e={}),s=(n=e).data;var h={method:i=void 0===(r=n.method)?"GET":r,headers:_extends({"Content-Type":"application/json"},void 0===(a=n.headers)?{}:a)};return"GET"===i&&s&&(o=new URLSearchParams(s).toString(),t+=(t.includes("?")?"&":"?")+o),"GET"!==i&&s&&(h.body=JSON.stringify(s)),Promise.resolve(_catch$4(function(){return Promise.resolve(fetch(t,h)).then(function(t){if(!(l=t).ok)throw{status:l.status,statusText:l.statusText,message:"HTTP error! status: "+l.status};return l})},function(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}))}catch(t){return Promise.reject(t)}};function XMLRequest(t){return new Promise(function(e,n){var r,i=new XMLHttpRequest;i.open("GET",t.url),i.responseType="arraybuffer",i.timeout=null!=(r=t.timeout)?r:6e4,i.onload=function(){4===i.readyState&&200===i.status?e([!1,i.response]):n([!0,"HTTP "+i.status+" "+i.statusText])},i.onerror=function(){n([!0,"network error"])},i.ontimeout=function(){n([!0,"timeout after "+i.timeout+"ms"])},i.onabort=function(){n([!0,"aborted"])},i.onprogress=function(e){if(e.lengthComputable){var n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},i.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 r(t,e,r,i,s,a){return n((o=n(n(e,t),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function i(t,e,n,i,s,a,o){return r(e&n|~e&i,t,e,s,a,o)}function s(t,e,n,i,s,a,o){return r(e&i|n&~i,t,e,s,a,o)}function a(t,e,n,i,s,a,o){return r(e^n^i,t,e,s,a,o)}function o(t,e,n,i,s,a,o){return r(n^(e|~i),t,e,s,a,o)}function l(t,e){var r,l,h,c,d;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,f=-271733879,p=-1732584194,m=271733878;for(r=0;r<t.length;r+=16)l=u,h=f,c=p,d=m,u=i(u,f,p,m,t[r],7,-680876936),m=i(m,u,f,p,t[r+1],12,-389564586),p=i(p,m,u,f,t[r+2],17,606105819),f=i(f,p,m,u,t[r+3],22,-1044525330),u=i(u,f,p,m,t[r+4],7,-176418897),m=i(m,u,f,p,t[r+5],12,1200080426),p=i(p,m,u,f,t[r+6],17,-1473231341),f=i(f,p,m,u,t[r+7],22,-45705983),u=i(u,f,p,m,t[r+8],7,1770035416),m=i(m,u,f,p,t[r+9],12,-1958414417),p=i(p,m,u,f,t[r+10],17,-42063),f=i(f,p,m,u,t[r+11],22,-1990404162),u=i(u,f,p,m,t[r+12],7,1804603682),m=i(m,u,f,p,t[r+13],12,-40341101),p=i(p,m,u,f,t[r+14],17,-1502002290),u=s(u,f=i(f,p,m,u,t[r+15],22,1236535329),p,m,t[r+1],5,-165796510),m=s(m,u,f,p,t[r+6],9,-1069501632),p=s(p,m,u,f,t[r+11],14,643717713),f=s(f,p,m,u,t[r],20,-373897302),u=s(u,f,p,m,t[r+5],5,-701558691),m=s(m,u,f,p,t[r+10],9,38016083),p=s(p,m,u,f,t[r+15],14,-660478335),f=s(f,p,m,u,t[r+4],20,-405537848),u=s(u,f,p,m,t[r+9],5,568446438),m=s(m,u,f,p,t[r+14],9,-1019803690),p=s(p,m,u,f,t[r+3],14,-187363961),f=s(f,p,m,u,t[r+8],20,1163531501),u=s(u,f,p,m,t[r+13],5,-1444681467),m=s(m,u,f,p,t[r+2],9,-51403784),p=s(p,m,u,f,t[r+7],14,1735328473),u=a(u,f=s(f,p,m,u,t[r+12],20,-1926607734),p,m,t[r+5],4,-378558),m=a(m,u,f,p,t[r+8],11,-2022574463),p=a(p,m,u,f,t[r+11],16,1839030562),f=a(f,p,m,u,t[r+14],23,-35309556),u=a(u,f,p,m,t[r+1],4,-1530992060),m=a(m,u,f,p,t[r+4],11,1272893353),p=a(p,m,u,f,t[r+7],16,-155497632),f=a(f,p,m,u,t[r+10],23,-1094730640),u=a(u,f,p,m,t[r+13],4,681279174),m=a(m,u,f,p,t[r],11,-358537222),p=a(p,m,u,f,t[r+3],16,-722521979),f=a(f,p,m,u,t[r+6],23,76029189),u=a(u,f,p,m,t[r+9],4,-640364487),m=a(m,u,f,p,t[r+12],11,-421815835),p=a(p,m,u,f,t[r+15],16,530742520),u=o(u,f=a(f,p,m,u,t[r+2],23,-995338651),p,m,t[r],6,-198630844),m=o(m,u,f,p,t[r+7],10,1126891415),p=o(p,m,u,f,t[r+14],15,-1416354905),f=o(f,p,m,u,t[r+5],21,-57434055),u=o(u,f,p,m,t[r+12],6,1700485571),m=o(m,u,f,p,t[r+3],10,-1894986606),p=o(p,m,u,f,t[r+10],15,-1051523),f=o(f,p,m,u,t[r+1],21,-2054922799),u=o(u,f,p,m,t[r+8],6,1873313359),m=o(m,u,f,p,t[r+15],10,-30611744),p=o(p,m,u,f,t[r+6],15,-1560198380),f=o(f,p,m,u,t[r+13],21,1309151649),u=o(u,f,p,m,t[r+4],6,-145523070),m=o(m,u,f,p,t[r+11],10,-1120210379),p=o(p,m,u,f,t[r+2],15,718787259),f=o(f,p,m,u,t[r+9],21,-343485551),u=n(u,l),f=n(f,h),p=n(p,c),m=n(m,d);return[u,f,p,m]}function h(t){var e,n="",r=32*t.length;for(e=0;e<r;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function c(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var r=8*t.length;for(e=0;e<r;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function d(t){var e,n,r="0123456789abcdef",i="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),i+=r.charAt(e>>>4&15)+r.charAt(15&e);return i}function u(t){return unescape(encodeURIComponent(t))}function f(t){return function(t){return h(l(c(t),8*t.length))}(u(t))}function p(t,e){return function(t,e){var n,r,i=c(t),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=l(i,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^i[n],a[n]=1549556828^i[n];return r=l(s.concat(c(e)),512+8*e.length),h(l(a.concat(r),640))}(u(t),u(e))}function m(t,e,n){return e?n?p(e,t):d(p(e,t)):n?f(t):d(f(t))}t.exports?t.exports=m:e.md5=m}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,function(t){return"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0")})}function compareUnicodeCodePoints(t,e){for(var n=Array.from(t,function(t){return t.codePointAt(0)}),r=Array.from(e,function(t){return t.codePointAt(0)}),i=Math.min(n.length,r.length),s=0;s<i;s+=1)if(n[s]!==r[s])return n[s]-r[s];return n.length-r.length}function parseUrlWithoutBase(t){try{var e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){var n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,r,i){var s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(r).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"!=typeof e)return e;for(var n,r={},i=_createForOfIteratorHelperLoose(Object.keys(e).sort(compareUnicodeCodePoints));!(n=i()).done;){var s=n.value;r[s]=t(e[s])}return r}(i),h=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),c=encodeWithMd5(""+o.toLowerCase()+n.toLowerCase()+h+e+a);return s["X-APP-ID"]=t,s["X-TOKEN"]=c,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}var CacheManager=/*#__PURE__*/function(){function t(t){this.cacheServer=t}return t.prototype.getVideo=function(t){return this.cacheServer+"/get_video?url="+encodeURIComponent(t)},t}();function _catch$3(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var ResourceManager=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.getAppInfo=function(){return{appId:this.options.appId}},e.getBackgroundImage=function(){var t=this;return new Promise(function(e,n){try{var r,i,s=new Image;if(s.crossOrigin="anonymous",s.src=(null==(r=t.config)?void 0:r.background_img)||"",null==(i=t.config)||!i.background_img)return;s.onload=function(){t.bg=s,e()},s.onerror=function(n){t.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:s}}),t.bg=null,e()}}catch(t){}})},e.getIsEnableRobotExpression=function(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression},e.getBackgroundImageElement=function(){return this.bg},e.getConfig=function(){return this.config},e.load=function(t){try{var e=this;return e.destroyed=!1,null==t||t(e.progress),e.startSessionTimer&&(clearInterval(e.startSessionTimer),e.startSessionTimer=null),e.startSessionTimer=setInterval(function(){if(e.destroyed||e.progress>=14)return clearInterval(e.startSessionTimer),void(e.startSessionTimer=null);e.progress+=1,null==t||t(e.progress)},100),Promise.resolve(e.startSession()).then(function(n){var r;function i(i){var a,o;if(r)return i;if(!n)return clearInterval(e.startSessionTimer),e.startSessionTimer=null,null;clearInterval(e.startSessionTimer),e.startSessionTimer=null,e.progress=15,null==t||t(e.progress),e.resource_pack=s.resource_pack,e.config=s.config,e.offlineIdle=(null==(a=s.resource_pack)?void 0:a.offline_idle)||[];var l=function(){if(e.resource_pack){var n=function(){var t,n;if(e.getBackgroundImage(),(null==(t=e.mouthShapeLib)||!t.char_info)&&null!=s&&null!=(n=s.resource_pack)&&n.face_ani_char_data&&!e.audioOnlyMode)return o=1,null},r=function(){if(!e.audioOnlyMode)return Promise.resolve(e.loadMouthShapeLib(t)).then(function(){})}();return r&&r.then?r.then(n):n()}}();return l&&l.then?l.then(function(t){return o?t:s}):o?l:s}var s=n;null!=s&&s.session_id&&(e.session_id=s.session_id);var a=function(){if(e.destroyed)return window.avatarSDKLogger.warn(e.TAG,"sdk destroyed during load, aborting after startSession"),Promise.resolve(e.stopSession("destroy_during_init")).then(function(){return r=1,null})}();return a&&a.then?a.then(i):i(a)})}catch(t){return Promise.reject(t)}},e.startSession=function(){var t=this;return Promise.resolve(_catch$3(function(){return Promise.resolve(t._startSession()).then(function(e){return null!=e&&e.verify_res&&(null==t.options.onStartSessionWarning||t.options.onStartSessionWarning(e.verify_res)),e})},function(){return null}))},e._startSession=function(){var t,e=this;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;var n=""+this.options.gatewayServer,r=_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})}),i=headersNeedSign(this.options.appId,this.options.appSecret,"POST",n,r);return request(n,{method:"POST",data:i.data,headers:_extends({},i.headers,this.options.headers)}).then(function(t){return t.json()}).then(function(t){var n;return null!=t&&null!=(n=t.data)&&n.resource_pack?null==t?void 0:t.data:(e.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(function(t){return e.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null})},e.stopSession=function(t){try{var e=this;return Promise.resolve(_catch$3(function(){var n=""+e.options.gatewayServer;if(e.session_id){var r=headersNeedSign(e.options.appId,e.options.appSecret,"DELETE",n,{session_id:e.session_id,stop_reason:t});return Promise.resolve(request(n,{method:"DELETE",data:r.data,headers:_extends({},r.headers,e.options.headers)})).then(function(t){return Promise.resolve(t.json())})}},function(t){e.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}))}catch(t){return Promise.reject(t)}},e.loadMouthShapeLib=function(t){try{var e=this;return Promise.resolve(_catch$3(function(){function n(){var n;function c(i){if(n)return i;var o=performance.now()-a;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:o,downlink:s>0&&o>0?8*s/(o/1e3)/1e6:0,networkStatus:navigator.onLine}),e.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(r,{blendshapeMap:e.resource_pack.blendshape_map||[]})},e.progress+=65,null==t||t(e.progress)}var d=function(){if(!r){var t=_catch$3(function(){var t=e.resource_pack.face_ani_char_data;return a=performance.now(),o=a,l=0,Promise.resolve(XMLRequest({url:t,onProgress:h()})).then(function(t){r=t[1]})},function(t){e.first_load&&(e.first_load=!1,e.stopSession("char_bin_load_error")),null==e.sdk.onMessage||e.sdk.onMessage({code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:i,binError:t}}),n=1});if(t&&t.then)return t.then(function(){})}}();return d&&d.then?d.then(c):c(d)}if(!e.resource_pack.face_ani_char_data)return e.progress+=60,void(null==t||t(e.progress));var r=null,i=null,s=0,a=0,o=0,l=0,h=function(){return function(n,r){if(r){var i=performance.now(),s=i-o,a=r.loaded-l;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:s,downlink:s>0&&a>0?8*a/(s/1e3)/1e6:0,networkStatus:navigator.onLine}),l=r.loaded,o=i,null==t||t(e.progress+.65*n)}}},c=_catch$3(function(){var t=e.resource_pack.face_ani_char_data+".gz";return a=performance.now(),o=a,l=0,Promise.resolve(XMLRequest({url:t,onProgress:h()})).then(function(t){var e=pako.ungzip(new Uint8Array(t[1])),n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e),r=n})},function(t){i=t,r=null});return c&&c.then?c.then(n):n()},function(t){e.first_load&&(e.first_load=!1,e.stopSession("char_bin_load_error")),null==e.sdk.onMessage||e.sdk.onMessage({code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}))}catch(t){return Promise.reject(t)}},e.getMouthShapeLib=function(){return this.mouthShapeLib},e.getVideoUrl=function(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}),"";var e,n=""+this.resource_pack.body_data_dir+t+".mp4";return this.cacheServer?null==(e=this.cacheServer)?void 0:e.getVideo(n):n},e.preloadVideo=function(t){try{return this.videoCache.has(t)?Promise.resolve():Promise.resolve(this.loadVideo(t))}catch(t){return Promise.reject(t)}},e.loadVideo=function(t){try{var e,n=function(n){if(e)return n;r.isProcessingVideo=!0;var i=r.downloadVideo(t);return r.downloadingVideos.set(t,i),_finallyRethrows$1(function(){return Promise.resolve(i)},function(e,n){if(r.downloadingVideos.delete(t),r.isProcessingVideo=!1,e)throw n;return n})},r=this,i=r.videoCache.get(t)||r.offlineCache.get(t);if(i){if(i.data)return r.updateCacheAccess(t),Promise.resolve(i.data);window.avatarSDKLogger.warn(r.TAG,"发现无效缓存条目: "+t+",正在删除"),r.videoCache.delete(t)}var s=function(){if(r.downloadingVideos.has(t))return _catch$3(function(){return Promise.resolve(r.downloadingVideos.get(t)).then(function(t){return e=1,t})},function(e){throw r.downloadingVideos.delete(t),window.avatarSDKLogger.warn(r.TAG,t+" 视频下载失败,从下载列表移除"),e})}();return Promise.resolve(s&&s.then?s.then(n):n(s))}catch(t){return Promise.reject(t)}},e.downloadVideo=function(t){try{var e=this,n=e.getVideoUrl(t);return n?Promise.resolve(_catch$3(function(){return Promise.resolve(e._fetchVideo(n)).then(function(r){var i=r.response,s=r.arrayBuffer;return i.ok?(e.addToCache(t,s),s):(e.first_load&&(e.first_load=!1,e.stopSession("load_video_error")),void e.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:"Error: "+t+" 视频下载失败",e:{name:t,url:n,res:i}}))})},function(r){e.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:"Error: "+t+" 视频下载失败",e:{name:t,url:n,error:r}})})):Promise.resolve()}catch(t){return Promise.reject(t)}},e._fetchVideo=function(t){try{var e=this;if(e.networkInfos.length>=4){var n=e.networkInfos.reduce(function(t,e){return t+e.rtt},0)/e.networkInfos.length,r=e.networkInfos.reduce(function(t,e){return t+e.downlink},0)/e.networkInfos.length;null==e.options.onNetworkInfo||e.options.onNetworkInfo({rtt:n,downlink:r,networkStatus:navigator.onLine}),e.networkInfos.length=0}var i=performance.now();return Promise.resolve(fetch(t)).then(function(t){var n=parseFloat(t.headers.get("Content-Length")||"0"),r=performance.now();return Promise.resolve(t.arrayBuffer()).then(function(s){var a=r-i,o={rtt:a,downlink:8*n/(a/1e3*1e6),networkStatus:navigator.onLine};return e.networkInfos.push(o),{response:t,arrayBuffer:s}})})}catch(t){return Promise.reject(t)}},e.addToCache=function(t,e){for(var n,r=Date.now(),i=0,s=_createForOfIteratorHelperLoose(this.videoCache.values());!(n=s()).done;)i+=n.value.data.byteLength;if(i+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),i=0;for(var a,o=_createForOfIteratorHelperLoose(this.videoCache.values());!(a=o()).done;)i+=a.value.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)for(var l,h=.5*this.maxCacheSize,c=_createForOfIteratorHelperLoose(Array.from(this.videoCache.entries()).sort(function(t,e){return t[1].lastAccessTime-e[1].lastAccessTime}));!(l=c()).done;){var d=l.value,u=d[0],f=d[1];if(i<=h)break;this.videoCache.delete(u),i-=f.data.byteLength}}this.videoCache.set(t,{data:e,lastAccessTime:r,accessCount:1})},e.startCacheCleanup=function(){var t=this;this.cacheCleanupInterval=setInterval(function(){t.cleanupCache()},3e5)},e.cleanupCache=function(){if(!this.isProcessingVideo){for(var t,e=Date.now(),n=Array.from(this.videoCache.entries()).sort(function(t,e){return t[1].lastAccessTime-e[1].lastAccessTime}),r=0,i=[],s=_createForOfIteratorHelperLoose(this.videoCache.entries());!(t=s()).done;)r+=t.value[1].data.byteLength;for(var a,o=_createForOfIteratorHelperLoose(n);!(a=o()).done;){var l=a.value,h=l[1];e-h.lastAccessTime>6e5&&(i.push(l[0]),r-=h.data.byteLength)}if(r>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(var c,d=_createForOfIteratorHelperLoose(n);!(c=d()).done;){var u=c.value,f=u[0],p=u[1];if(!i.includes(f)&&(i.push(f),r-=p.data.byteLength,this.videoCache.size-i.length<=2||r<=.8*this.maxCacheSize&&this.videoCache.size-i.length<=.8*this.maxCacheEntries))break}for(var m=0,_=i;m<_.length;m++)this.videoCache.delete(_[m])}},e.updateCacheAccess=function(t){var e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)},e.clearAllCache=function(){this.videoCache.clear()},e._getOfflineIdle=function(){return this.offlineIdle},e._getSessionId=function(){return this.session_id||""},e._reload=function(){try{var t=this;return Promise.resolve(t.startSession()).then(function(e){var n;function r(e){var r;return n?e:(t.resource_pack=i.resource_pack,t.config=i.config,t.offlineIdle=(null==(r=i.resource_pack)?void 0:r.offline_idle)||[],t.resource_pack&&t.getBackgroundImage(),i)}if(!e)return null;var i=e;t.session_id=null==i?void 0:i.session_id;var s=function(){if(t.destroyed)return Promise.resolve(t.stopSession("destroy_during_reload")).then(function(){return n=1,null})}();return s&&s.then?s.then(r):r(s)})}catch(t){return Promise.reject(t)}},e._setOfflineCache=function(){try{var t=this;if(!t.offlineIdle||0===t.offlineIdle.length)return Promise.resolve();t.offlineCache.clear();var e=t.offlineIdle.map(function(t){return t.n});return Promise.resolve(_forOf$1(e,function(e){var n=_catch$3(function(){return Promise.resolve(t._runOfflineCache(e)).then(function(){})},function(){});if(n&&n.then)return n.then(function(){})}))}catch(t){return Promise.reject(t)}},e._runOfflineCache=function(t){try{var e=this,n=e.getVideoUrl(t);return n?Promise.resolve(e._fetchVideo(n).then(function(n){e.offlineCache.set(t,{data:n.arrayBuffer})})):Promise.resolve()}catch(t){return Promise.reject(t)}},e.destroy=function(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0},t}();function _finallyRethrows$1(t,e){try{var n=t()}catch(t){return e(!0,t)}return n&&n.then?n.then(e.bind(null,!1),e.bind(null,!0)):e(!1,n)}var _iteratorSymbol$1="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function _settle$1(t,e,n){if(!t.s){if(n instanceof _Pact$1){if(!n.s)return void(n.o=_settle$1.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle$1.bind(null,t,e),_settle$1.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var _Pact$1=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){var r=new t,i=this.s;if(i){var s=1&i?e:n;if(s){try{_settle$1(r,1,s(this.v))}catch(t){_settle$1(r,2,t)}return r}return this}return this.o=function(t){try{var i=t.v;1&t.s?_settle$1(r,1,e?e(i):i):n?_settle$1(r,1,n(i)):_settle$1(r,2,i)}catch(t){_settle$1(r,2,t)}},r},t}();function _isSettledPact$1(t){return t instanceof _Pact$1&&1&t.s}function _forTo$1(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact$1(o))return void o.then(a,i||(i=_settle$1.bind(null,r=new _Pact$1,2)));o=o.v}r?_settle$1(r,1,o):r=o}catch(t){_settle$1(r||(r=new _Pact$1),2,t)}}(),r}function _forOf$1(t,e,n){if("function"==typeof t[_iteratorSymbol$1]){var r,i,s,a=function(t){try{for(;!((r=o.next()).done||n&&n());)if((t=e(r.value))&&t.then){if(!_isSettledPact$1(t))return void t.then(a,s||(s=_settle$1.bind(null,i=new _Pact$1,2)));t=t.v}i?_settle$1(i,1,t):i=t}catch(t){_settle$1(i||(i=new _Pact$1),2,t)}},o=t[_iteratorSymbol$1]();if(a(),o.return){var l=function(t){try{r.done||o.return()}catch(t){}return t};if(i&&i.then)return i.then(l,function(t){throw l(t)});l()}return i}if(!("length"in t))throw new TypeError("Object is not iterable");for(var h=[],c=0;c<t.length;c++)h.push(t[c]);return _forTo$1(h,function(t){return e(h[t])},n)}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},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 r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},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 P}),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 _}),n.d(e,"encodeDateToTimeSpec",function(){return v}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return b}),n.d(e,"encodeTimestampExtension",function(){return y}),n.d(e,"decodeTimestampExtension",function(){return S});var r=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return a},i=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,r=0;r<e;){var i=t.charCodeAt(r++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&r<e){var s=t.charCodeAt(r);56320==(64512&s)&&(++r,i=((1023&i)<<10)+(1023&s)+65536)}n+=4294901760&i?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 c(t,e,n){for(var r=e,s=r+n,a=[],o="";r<s;){var l=t[r++];if(128&l)if(192==(224&l)){var h=63&t[r++];a.push((31&l)<<6|h)}else if(224==(240&l)){h=63&t[r++];var c=63&t[r++];a.push((31&l)<<12|h<<6|c)}else if(240==(248&l)){var d=(7&l)<<18|(h=63&t[r++])<<12|(c=63&t[r++])<<6|63&t[r++];d>65535&&(a.push((d-=65536)>>>10&1023|55296),d=56320|1023&d),a.push(d)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,i(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,i(a))),o}var d=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 r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function m(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var _=-1;function g(t){var e,n=t.sec,r=t.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var i=new Uint8Array(4);return(e=new DataView(i.buffer)).setUint32(0,n),i}var s=n/4294967296,a=4294967295&n;return i=new Uint8Array(8),(e=new DataView(i.buffer)).setUint32(0,r<<2|3&s),e.setUint32(4,a),i}return i=new Uint8Array(12),(e=new DataView(i.buffer)).setUint32(0,r),p(e,4,n),i}function v(t){var e=t.getTime(),n=Math.floor(e/1e3),r=1e6*(e-1e3*n),i=Math.floor(r/1e9);return{sec:n+i,nsec:r-1e9*i}}function y(t){return t instanceof Date?g(v(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:m(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:_,encode:y,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,r=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{var i=1+e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(r=this.builtInEncoders[n])&&null!=(i=r(t,e)))return new f(-1-n,i);for(n=0;n<this.encoders.length;n++){var r,i;if(null!=(r=this.encoders[n])&&null!=(i=r(t,e)))return new f(n,i)}return t instanceof f?t:null},t.prototype.decode=function(t,e,n){var r=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return r?r(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],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A=function(){function t(t,e,n,r,i,s,a){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=100),void 0===r&&(r=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,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),r=new DataView(e);n.set(this.bytes),this.view=r,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 r=t.length,i=n,s=0;s<r;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<r){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[i++]=a>>18&7|240,e[i++]=a>>12&63|128,e[i++]=a>>6&63|128):(e[i++]=a>>12&15|224,e[i++]=a>>6&63|128)}else e[i++]=a>>6&31|192;e[i++]=63&a|128}else e[i++]=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,r,i=t.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: "+i);this.writeU8(221),this.writeU32(i)}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&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,r,i=0;try{for(var s=T(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&i++}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},t.prototype.encodeMap=function(t,e){var n,r,i=Object.keys(t);this.sortKeys&&i.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,i):i.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(i),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&&(r=a.return)&&r.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 r=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,r)}(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 P(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 B(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var C=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 r=this.caches[n-1],i=r.length;t:for(var s=0;s<i;s++){for(var a=r[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],r={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},t.prototype.decode=function(t,e,n){var r=this.get(t,e,n);if(null!=r)return r;var i=c(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,i),i},t}(),I=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},k=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={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise(function(r,i){!function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)}(r,i,(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 C,N=function(){function t(t,e,n,r,i,s,a,o){void 0===t&&(t=w.defaultCodec),void 0===n&&(n=4294967295),void 0===r&&(r=4294967295),void 0===i&&(i=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=r,this.maxArrayLength=i,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),r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),this.setBuffer(r)}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,r,i;return function(t,e,n,r){return new(n||(n=Promise))(function(e,i){function s(t){try{o(r.next(t))}catch(t){i(t)}}function a(t){try{o(r.throw(t))}catch(t){i(t)}}function o(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(s,a)}o((r=r.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,h,c,d,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=k(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(),r={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),n&&!n.done&&(i=e.return)?[4,i.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw c=(h=this).headByte,d=h.pos,u=h.totalPos,new RangeError("Insufficient data in parcing "+B(c)+" at "+u+" ("+d+" 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 r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof D?Promise.resolve(n.value.v).then(l,h):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function c(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,r,i,s,a,o,l,h,c;return I(this,function(d){switch(d.label){case 0:n=e,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),i=k(t),d.label=2;case 2:return[4,D(i.next())];case 3:if((s=d.sent()).done)return[3,12];if(a=s.value,e&&0===r)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,D(this.decodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=d.sent())instanceof F))throw o;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=d.sent(),h={error:l},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(c=i.return)?[4,D(c.call(i))]:[3,16];case 15:d.sent(),d.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!=(r=t-128)){this.pushMapState(r),this.complete();continue t}e={}}else if(t<160){if(0!=(r=t-144)){this.pushArrayState(r),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!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(221===t){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(222===t){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue t}e={}}else if(223===t){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue t}e={}}else if(196===t){var r=this.lookU8();e=this.decodeBinary(r,1)}else if(197===t)r=this.lookU16(),e=this.decodeBinary(r,2);else if(198===t)r=this.lookU32(),e=this.decodeBinary(r,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)r=this.lookU8(),e=this.decodeExtension(r,1);else if(200===t)r=this.lookU16(),e=this.decodeExtension(r,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+B(t));r=this.lookU32(),e=this.decodeExtension(r,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;i.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}i.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: "+B(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 r,i=this.pos+e;return r=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,i,t):s&&t>u?function(t,e,n){var r=t.subarray(e,e+n);return d.decode(r)}(this.bytes,i,t):c(this.bytes,i,t),this.pos+=e+t,r},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,r=this.bytes.subarray(n,n+t);return this.pos+=e+t,r},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),r=this.decodeBinary(t,e+1);return this.extensionCodec.decode(r,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=m(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 j=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=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)},H=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof W?Promise.resolve(n.value.v).then(l,h):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}function l(t){o("next",t)}function h(t){o("throw",t)}function c(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function V(t){return null!=t[Symbol.asyncIterator]?t:function(t){return H(this,arguments,function(){var e,n,r;return j(this,function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,W(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,W(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(r),[4,W(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var $=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function a(t){try{l(r.next(t))}catch(t){s(t)}}function o(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((r=r.apply(t,e||[])).next())})},K=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=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),$(this,void 0,void 0,function(){var n;return K(this,function(r){return n=V(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=V(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=V(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,r)=>withNativeBlob$1&&e instanceof Blob?n?r(e):encodeBlobAsBase64(e,r):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?r(e):encodeBlobAsBase64(new Blob([e]),r):r(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,r,i,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),c=new Uint8Array(h);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],r=lookup$1[t.charCodeAt(e+1)],i=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],c[l++]=n<<2|r>>4,c[l++]=(15&r)<<4|i>>2,c[l++]=(3&i)<<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,r=new Array(n);let i=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{r[s]=t,++i===n&&e(r.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),r=[];for(let t=0;t<n.length;t++){const i=decodePacket(n[t],e);if(r.push(i),"error"===i.type)break}return r};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),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 r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let r=0,i=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===r){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(totalLength(n)<2)break;const t=concatChunks(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){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}i=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(totalLength(n)<i)break;const t=concatChunks(n,i);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),r=0}if(0===i||i>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,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.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],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].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 r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,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,r=n.length;t<r;t++){let r=n[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[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],r=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}r&&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(),r=createPacketEncoderStream();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();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("["),r=t.indexOf("]");-1!=n&&-1!=r&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=i[a]||"";return-1!=n&&-1!=r&&(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,r){e&&(n[e]=r)}),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,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),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 r=()=>{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 i(){n||(n=!0,h(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",r),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 r=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),r=parse(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}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 r=0;r<t.length;r++)n[r]=_deconstructPacket(t[r],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=_deconstructPacket(t[r],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),r=e.buffers;return r.unshift(n),r}}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 r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(r,e)}else n.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=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(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}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:protocol,get PacketType(){return PacketType},Encoder:Encoder,Decoder: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,r,i;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===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._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 r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=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"))},r),s=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(t,e)=>t?r(t):n(e);i.withError=!0,e.push(i),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,...r)=>{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,...r)),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(...r){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:r}))}}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 r=e.parser||parser;this.encoder=new r.Encoder,this.decoder=new r.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 r=on(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",i);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(r),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"),r=n.source,i=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[i]&&n.path in cache[i].nsps?s=new Manager(r,e):(cache[i]||(cache[i]=new Manager(r,e)),s=cache[i]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;function _finallyRethrows(t,e){try{var n=t()}catch(t){return e(!0,t)}return n&&n.then?n.then(e.bind(null,!1),e.bind(null,!0)):e(!1,n)}Object.assign(lookup,{Manager:Manager,Socket: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),r=0,i=2,s=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,a){n[r]=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];i.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 r=Array(64),i=Array(123),s=0;s<64;)i[r[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 i,s=null,a=[],o=0,l=0;e<n;){var h=t[e++];switch(l){case 0:a[o++]=r[h>>2],i=(3&h)<<4,l=1;break;case 1:a[o++]=r[i|h>>4],i=(15&h)<<2,l=2;break;case 2:a[o++]=r[i|h>>6],a[o++]=r[63&h],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=r[i],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 r,s=n,o=0,l=0;l<t.length;){var h=t.charCodeAt(l++);if(61==h&&1<o)break;if((h=i[h])===rt)throw Error(a);switch(o){case 0:r=h,o=1;break;case 1:e[n++]=r<<2|(48&h)>>4,r=h,o=2;break;case 2:e[n++]=(15&r)<<4|(60&h)>>2,r=h,o=3;break;case 3:e[n++]=(3&r)<<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 r=[];function i(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 c=Array(arguments.length-1),d=0;d<c.length;)c[d]=arguments[++d];if(d=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=c[d++];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"%"}),d!==c.length)throw Error("parameter count mismatch");return r.push(e),i}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+r.join("\n ")+"\n}"}return i.toString=s,i}).verbose=!1},{}],4:[function(t,e,n){function r(){this.i={}}(e.exports=r).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},r.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},r.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var r=t(1),i=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&i&&i.readFile?i.readFile(t,function(r,i){return r&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):r?n(r):n(null,e.binary?i:i.toString("utf8"))}):s.xhr(t,e,n):r(s,this,t,e)}s.xhr=function(t,e,n){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(4!==r.readyState)return rt;if(0!==r.status&&200!==r.status)return n(Error("status "+r.status));if(e.binary){if(!(t=r.response))for(var t=[],i=0;i<r.responseText.length;++i)t.push(255&r.responseText.charCodeAt(i));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,r.responseText)},e.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",t),r.send()}},{1:1,7:7}],6:[function(t,e,n){function r(t){function e(t,e,n,r){var i=e<0?1:0;t(0===(e=i?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(i<<31|2139095040)>>>0:e<11754943508222875e-54?(i<<31|Math.round(e/1401298464324817e-60))>>>0:(i<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,r)}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 r(t,e,n){d[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){d[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],d[0]}function c(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],d[0]}var d,u,f,p,m;function _(t,e,n,r,i,s){var a,o=r<0?1:0;0===(r=o?-r:r)?(t(0,i,s+e),t(0<1/r?0:2147483648,i,s+n)):isNaN(r)?(t(0,i,s+e),t(2146959360,i,s+n)):17976931348623157e292<r?(t(0,i,s+e),t((o<<31|2146435072)>>>0,i,s+n)):r<22250738585072014e-324?(t((a=r/5e-324)>>>0,i,s+e),t((o<<31|a/4294967296)>>>0,i,s+n)):(t(4503599627370496*(a=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,i,s+e),t((o<<31|r+1023<<20|1048576*a&1048575)>>>0,i,s+n))}function g(t,e,n,r,i){return e=t(r,i+e),r=2*((t=t(r,i+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(i=t>>>20&2047)?n?NaN:1/0*r:0==i?5e-324*r*n:r*Math.pow(2,i-1075)*(n+4503599627370496)}function v(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 y(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?(d=new Float32Array([-0]),u=new Uint8Array(d.buffer),t.writeFloatLE=(m=128===u[3])?r:l,t.writeFloatBE=m?l:r,t.readFloatLE=m?h:c,t.readFloatBE=m?c:h):(t.writeFloatLE=e.bind(null,i),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=(m=128===p[7])?v:y,t.writeDoubleBE=m?y:v,t.readDoubleLE=m?b:S,t.readDoubleBE=m?S:b):(t.writeDoubleLE=_.bind(null,i,0,4),t.writeDoubleBE=_.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function i(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=r(r)},{}],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 r=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},i=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=r(t);t="",n&&(t=e.shift()+"/");for(var i=0;i<e.length;)".."===e[i]?0<i&&".."!==e[i-1]?e.splice(--i,2):n?e.splice(i,1):++i:"."===e[i]?e.splice(i,1):++i;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=i(e)),!r(e)&&(t=(t=n?t:i(t)).replace(/(?:\/|^)[^/]+$/,"")).length?i(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var r=n||8192,i=r>>>1,s=null,a=r;return function(n){return n<1||i<n?t(n):(r<a+n&&(s=t(r),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,r=0;r<t.length;++r)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(r+1))?(++r,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,s=[],a=0;e<n;)(r=t[e++])<128?s[a++]=r:191<r&&r<224?s[a++]=(31&r)<<6|63&t[e++]:239<r&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(r>>10),s[a++]=56320+(1023&r)):s[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,s)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var r,i,s=n,a=0;a<t.length;++a)(r=t.charCodeAt(a))<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(++a,e[n++]=(r=65536+((1023&r)<<10)+(1023&i))>>18|240,e[n++]=r>>12&63|128):e[n++]=r>>12|224,e[n++]=r>>6&63|128),e[n++]=63&r|128);return n-s}},{}],11:[function(t,e,n){e.exports=i;var r=/\/|\./;function i(t,e){r.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),i[t]=e}i("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),i("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),i("timestamp",{Timestamp:e}),i("empty",{Empty:{fields:{}}}),i("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}}}}),i("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}}}}),i("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),i.get=function(t){return i[t]||null}},{}],12:[function(t,e,n){var r=t(15),i=t(37);function s(t,e,n,i){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(d%s){",i);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}',i,i,i),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",i,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',i)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,n,i);else{var h=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",i,i);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",i,i,h)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":t("m%s=String(d%s)",i,i);break;case"bool":t("m%s=Boolean(d%s)",i,i)}}return t}function a(t,e,n,i){if(e.resolvedType)e.resolvedType instanceof r?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,n,i,i,n,i,i):t("d%s=types[%i].toObject(m%s,o)",i,n,i);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("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",i,i,i,i,s?"true":"",i);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",i,i,i,i,i);break;default:t("d%s=m%s",i,i)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=i.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=i.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 r||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof r||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(i.compareFieldsById);if(!e.length)return i.codegen()("return {}");for(var n=i.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=[]",i.safeProp(s[h].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),h=0;h<o.length;++h)n("d%s={}",i.safeProp(o[h].name));n("}")}if(l.length){for(n("if(o.defaults){"),h=0;h<l.length;++h){var c,d=i.safeProp((f=l[h]).name);f.resolvedType instanceof r?n("d%s=o.enums===String?%j:%j",d,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",d)("}else")("d%s=o.longs===String?%j:%i",d,f.typeDefault.toString(),f.typeDefault.toNumber()):f.bytes?(c="["+Array.prototype.slice.call(f.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",d,String.fromCharCode.apply(String,f.typeDefault))("else{")("d%s=%s",d,c)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",d,d)("}")):n("d%s=%j",d,f.typeDefault)}n("}")}var u=!1;for(h=0;h<e.length;++h){var f,p=t.e.indexOf(f=e[h]);d=i.safeProp(f.name),f.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",d,d)("d%s={}",d)("for(var j=0;j<ks2.length;++j){"),a(n,f,p,d+"[ks2[j]]")("}")):f.repeated?(n("if(m%s&&m%s.length){",d,d)("d%s=[]",d)("for(var j=0;j<m%s.length;++j){",d),a(n,f,p,d+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",d,f.name),a(n,f,p,d),f.partOf&&n("if(o.oneofs)")("d%s=%j",i.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 r?"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"),i.defaults[a.keyType]!==rt?e("k=%j",i.defaults[a.keyType]):e("k=null"),i.defaults[o]!==rt?e("value=%j",i.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:"),i.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(i.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),i.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"),i.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)):i.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 r=t(15),i=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(),c=t.e.indexOf(h),d=h.resolvedType instanceof r?"int32":h.type,u=i.basic[d];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|i.mapKey[h.keyType],h.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",c,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,d,e),n("}")("}")):h.repeated?(n("if(%s!=null&&%s.length){",e,e),h.packed&&i.packed[d]!==rt?n("w.uint32(%i).fork()",(h.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",d,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,h,c,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(h.id<<3|u)>>>0,d,e)),n("}")):(h.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,h.name),u===rt?a(n,h,c,e):n("w.uint32(%i).%s(%s)",(h.id<<3|u)>>>0,d,e))}return n("return w")};var r=t(15),i=t(36),s=t(37);function a(t,e,n,r){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,i,s,a){if(r.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=i,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){var e=this;return r.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(function(t){var n=Object.assign({},e.h);e.o[t]=Object.assign(n,e.valuesOptions&&e.valuesOptions[t]&&e.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,r){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 r&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=r||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 i.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=h;var r,i=t(24),s=(((h.prototype=Object.create(i.prototype)).constructor=h).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function h(t,e,n,r,s,h,c){if(o.isObject(r)?(c=s,h=r,r=s=rt):o.isObject(s)&&(c=h,h=s,s=rt),i.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(r!==rt&&!l.test(r=r.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=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===r,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=c}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 r&&"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 i.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 r?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 r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.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 r&&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 i.prototype.u.call(this,this.f||t)},h.d=function(t,e,n,r){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(i,s){o.decorateType(i.constructor).add(new h(s,t,e,n,{default:r}))}},h.p=function(t){r=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var r=e.exports=t(18);r.build="light",r.load=function(t,e,n){return(e="function"==typeof e?(n=e,new r.Root):e||new r.Root).load(t,n)},r.loadSync=function(t,e){return(e=e||new r.Root).loadSync(t)},r.encoder=t(14),r.decoder=t(13),r.verifier=t(40),r.converter=t(12),r.ReflectionObject=t(24),r.Namespace=t(23),r.Root=t(29),r.Enum=t(15),r.Type=t(35),r.Field=t(16),r.OneOf=t(25),r.MapField=t(20),r.Service=t(33),r.Method=t(22),r.Message=t(21),r.wrappers=t(41),r.types=t(36),r.util=t(37),r.ReflectionObject.p(r.Root),r.Namespace.p(r.Type,r.Service,r.Enum),r.Root.p(r.Type),r.Field.p(r.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 r=n;function i(){r.util.p(),r.Writer.p(r.BufferWriter),r.Reader.p(r.BufferReader)}r.build="minimal",r.Writer=t(42),r.BufferWriter=t(43),r.Reader=t(27),r.BufferReader=t(28),r.util=t(39),r.rpc=t(31),r.roots=t(30),r.configure=i,i()},{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 r=t(16),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,i,a,o){if(r.call(this,t,e,i,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(i.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return r.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(r,i){s.decorateType(r.constructor).add(new a(i,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=i;var r=t(39);function i(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}i.create=function(t){return this.$type.create(t)},i.encode=function(t,e){return this.$type.encode(t,e)},i.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},i.decode=function(t){return this.$type.decode(t)},i.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},i.verify=function(t){return this.$type.verify(t)},i.fromObject=function(t){return this.$type.fromObject(t)},i.toObject=function(t,e){return this.$type.toObject(t,e)},i.prototype.toJSON=function(){return this.$type.toObject(this,r.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var r=t(24),i=(((s.prototype=Object.create(r.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,h,c){if(i.isObject(a)?(l=a,a=o=rt):i.isObject(o)&&(l=o,o=rt),e!==rt&&!i.isString(e))throw TypeError("type must be a string");if(!i.isString(n))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");r.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=c}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 i.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),r.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=d;var r,i,s,a=t(24),o=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Namespace",t(16)),l=t(37),h=t(25);function c(t,e){if(!t||!t.length)return rt;for(var n={},r=0;r<t.length;++r)n[t[r].name]=t[r].toJSON(e);return n}function d(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}d.fromJSON=function(t,e){return new d(t,e.options).addJSON(e.nested)},d.arrayToJSON=c,d.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},d.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(d.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),d.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",c(this.nestedArray,t)])},d.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?r:e.values!==rt?s:e.methods!==rt?i:e.id!==rt?o:d).fromJSON(n[a],e));return this},d.prototype.get=function(t){return this.nested&&this.nested[t]||null},d.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},d.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof r||t instanceof h||t instanceof s||t instanceof i||t instanceof d))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof d&&t instanceof d)||e instanceof r||e instanceof i)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 r||this instanceof i||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)},d.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)},d.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 r=t.shift();if(n.nested&&n.nested[r]){if(!((n=n.nested[r])instanceof d))throw Error("path conflicts with non-namespace objects")}else n.add(n=new d(r))}return e&&n.addJSON(e),n},d.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 d?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},d.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(function(e){e.g(t)})),this},d.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 r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var i=this.root.j&&this.root.j["."+r];if(i&&(!e||~e.indexOf(i.constructor)))return i;if((i=this.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;if(!n)for(var s=this;s.parent;){if((i=s.parent.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;s=s.parent}return null},d.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof d&&(t=t.slice(1),r=n.k(t,t.join(".")));else for(var i=0;i<this.nestedArray.length;++i)this.v[i]instanceof d&&(n=this.v[i].k(t,e))&&(r=n);return this.b[e]=r},d.prototype.lookupType=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such type: "+t)},d.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},d.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[r,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},d.prototype.lookupService=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},d.p=function(t,e,n){r=t,i=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=h).className="ReflectionObject";var r,i=t(25),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 r,i,a=this.parsedOptions;return n?(r=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(i=r[t],n,e):((r={})[t]=s.setProperty({},n,e),a.push(r)):((i={})[t]=e,a.push(i)),this},h.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),r=0;r<n.length;++r)this.setOption(n[r],t[n[r]],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 r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,i){if(Array.isArray(e)||(n=e,e=rt),r.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=i}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 i)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 i))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){r.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);r.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 r=t(34),i=t(29),s=t(35),a=t(16),o=t(20),l=t(25),h=t(15),c=t(33),d=t(22),u=t(24),f=t(36),p=t(37),m=/^[1-9][0-9]*$/,_=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,v=/^-?0[x][0-9a-fA-F]+$/,y=/^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 i||(n=e,e=new i);var T,A,R,P,B,C,I=(n=n||x.defaults).preferTrailingComment||!1,k=r(t,n.alternateCommentMode||!1),D=k.next,U=k.push,O=k.peek,F=k.skip,L=k.cmnt,M=!0,N="proto2",z=e,G=[],j={},W=n.keepCase?function(t){return t}:p.camelCase;function H(t,e,n){var r=x.filename;return n||(x.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(r?r+", ":"")+"line "+k.line+")")}function V(){var t,e=[];do{if('"'!==(t=D())&&"'"!==t)throw H(t)}while(e.push(D()),F(t),'"'===(t=O())||"'"===t);return e.join("")}function $(t){var e=D();switch(e){case"'":case'"':return U(e),V();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,r=1;switch("-"==(n[0]||"")&&(r=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(m.test(n))return r*parseInt(n,10);if(g.test(n))return r*parseInt(n,16);if(y.test(n))return r*parseInt(n,8);if(S.test(n))return r*parseFloat(n);throw H(n,"number",!0)}catch(n){if(t&&w.test(e))return e;throw H(e,"value")}}function K(t,e){var n;do{if(!e||'"'!==(r=O())&&"'"!==r)try{t.push([n=Y(D()),F("to",!0)?Y(D()):n])}catch(n){if(!(e&&w.test(r)&&2023<=N))throw n;t.push(r)}else{var r=V();if(t.push(r),2023<=N)throw H(r,"id")}}while(F(",",!0));var i={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};Z(i,function(t){if("option"!==t)throw H(t);tt(i,t),F(";")},function(){nt(i)})}function Y(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(_.test(t))return parseInt(t,10);if(v.test(t))return parseInt(t,16);if(b.test(t))return parseInt(t,8)}throw H(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,r,i=t;if(E.test(r=D()))return Z(n=new c(r),function(t){if(!X(n,t)){if("rpc"!==t)throw H(t);var e=n,r=L(),i=t;if(!E.test(t=D()))throw H(t,"name");var s,a,o,l=t;if(F("("),F("stream",!0)&&(a=!0),!w.test(t=D()))throw H(t);if(s=t,F(")"),F("returns"),F("("),F("stream",!0)&&(o=!0),!w.test(t=D()))throw H(t);F(")");var h=new d(l,i,s,t,a,o);h.comment=r,Z(h,function(t){if("option"!==t)throw H(t);tt(h,t),F(";")}),e.add(h)}}),i.add(n),i===z&&G.push(n),1;throw H(r,"service name");case"extend":var s,a=t;if(i=e,w.test(i=D()))return s=i,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 H(t);U(t),Q(a,"optional",s)}}),1;throw H(i,"reference")}}function Z(t,e,n){var r,i=k.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=x.filename),F("{",!0)){for(;"}"!==(r=D());)e(r);F(";",!0)}else n&&n(),F(";"),t&&("string"!=typeof t.comment||I)&&(t.comment=L(i)||t.comment)}function q(t,e){if(!E.test(e=D()))throw H(e,"type name");var n=new s(e);Z(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,r=(F("<"),D());if(f.mapKey[r]===rt)throw H(r,"type");F(",");var i=D();if(!w.test(i))throw H(i,"type");F(">");var s=D();if(!E.test(s))throw H(s,"name");F("=");var a=new o(W(s),Y(D()),r,i);Z(a,function(t){if("option"!==t)throw H(t);tt(a,t),F(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==N)throw H(t);case"repeated":Q(n,t);break;case"optional":if("proto3"===N)Q(n,"proto3_optional");else{if("proto2"!==N)throw H(t);Q(n,"optional")}break;case"oneof":if(s=n,r=t,!E.test(r=D()))throw H(r,"name");var h=new l(W(r));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 H(t);U(t),Q(n,"optional")}}),t.add(n),t===z&&G.push(n)}function Q(t,e,n){var r=D();if("group"===r){var i=t,o=e;if(2023<=N)throw H("group");var h,c,d=D();if(E.test(d))return d===(c=p.lcFirst(d))&&(d=p.ucFirst(d)),F("="),u=Y(D()),(h=new s(d)).group=!0,(c=new a(c,u,d,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 H(t)}}),void i.add(h).add(c);throw H(d,"name")}for(;r.endsWith(".")||O().startsWith(".");)r+=D();if(!w.test(r))throw H(r,"type");var u=D();if(!E.test(u))throw H(u,"name");u=W(u),F("=");var f=new a(u,Y(D()),r,e,n);Z(f,function(t){if("option"!==t)throw H(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 H(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,r=t;if(!E.test(r))throw H(r,"name");F("=");var i=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 H(t);tt(s,t),F(";")},function(){nt(s)}),void e.add(r,i,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&&(r=D(),F(")"),e="("+r+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var r=e.split("."),i=r[0]+".";e=r[1];continue}i=e}else a=a?a+e:e;e=D()}var s=function t(e,n){if(F("{",!0)){for(var r={};!F("}",!0);){if(!E.test(P=D()))throw H(P,"name");if(null===P)throw H(P,"end of input");var i,s,a=P;if(F(":",!0),"{"===O())i=t(e,n+"."+P);else if("["===O()){if(i=[],F("[",!0)){for(;s=$(!0),i.push(s),F(",",!0););F("]"),void 0!==s&&et(e,n+"."+P,s)}}else i=$(!0),et(e,n+"."+P,i);var o=r[a];o&&(i=[].concat(o).concat(i)),r[a]=i,F(",",!0),F(";",!0)}return r}var l=$(!0);return et(e,n,l),l}(t,s=a?i.concat(a):i),a=a&&"."===a[0]?a.slice(1):a;i=i&&"."===i[i.length-1]?i.slice(0,-1):i,t.setParsedOption&&t.setParsedOption(i,s,a)}function et(t,e,n){z===t&&/^features\./.test(e)?j[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(F("[",!0)){for(;tt(t,"option"),F(",",!0););F("]")}}for(;null!==(P=D());)switch(P){case"package":if(!M)throw H(P);if(T!==rt)throw H("package");if(T=D(),!w.test(T))throw H(T,"name");z=z.define(T),F(";");break;case"import":if(!M)throw H(P);switch(C=void 0,O()){case"weak":C=R=R||[],D();break;case"public":D();default:C=A=A||[]}B=V(),F(";"),C.push(B);break;case"syntax":if(!M)throw H(P);if(F("="),(N=V())<2023)throw H(N,"syntax");F(";");break;case"edition":if(!M)throw H(P);if(F("="),N=V(),!["2023"].includes(N))throw H(N,"edition");F(";");break;case"option":tt(z,P),F(";",!0);break;default:if(X(z,P)){M=!1;continue}throw H(P)}return G.forEach(function(t){t.f=N,Object.keys(j).forEach(function(e){t.getOption(e)===rt&&t.setOption(e,j[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 r,i=t(39),s=i.LongBits,a=i.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 i.Buffer?function(t){return(l.create=function(t){return i.Buffer.isBuffer(t)?new r(t):d(t)})(t)}:d}var c,d="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._=i.Array.prototype.subarray||i.Array.prototype.slice,l.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;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=i.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=i.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=i.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){r=t,l.create=h(),r.p();var e=i.Long?"toLong":"toNumber";i.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 r=t(27),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.p=function(){i.Buffer&&(s.prototype._=i.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=d;var r,i,s,a=t(23),o=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Root",t(16)),l=t(15),h=t(25),c=t(37);function d(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}d.fromJSON=function(t,e){return e=e||new d,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},d.prototype.resolvePath=c.path.resolve,d.prototype.fetch=c.fetch,d.prototype.load=function t(e,n,r){"function"==typeof n&&(r=n,n=rt);var a=this;if(!r)return c.asPromise(t,a,e,n);var o=r===u;function l(t,e){if(r){if(o)throw t;e&&e.resolveAll();var n=r;r=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 d(t,e){try{if(c.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),c.isString(e)){i.filename=t;var r,s=i(e,a,n),d=0;if(s.imports)for(;d<s.imports.length;++d)(r=h(s.imports[d])||a.resolvePath(t,s.imports[d]))&&f(r);if(s.weakImports)for(d=0;d<s.weakImports.length;++d)(r=h(s.weakImports[d])||a.resolvePath(t,s.weakImports[d]))&&f(r,!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?d(t,s[t]):(++p,setTimeout(function(){--p,d(t,s[t])}));else if(o){var n;try{n=c.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}d(t,n)}else++p,a.fetch(t,function(n,i){--p,r&&(n?e?p||l(null,a):l(n):d(t,i))})}var p=0;c.isString(e)&&(e=[e]);for(var m,_=0;_<e.length;++_)(m=a.resolvePath("",e[_]))&&f(m);return o?a.resolveAll():p||l(null,a),a},d.prototype.loadSync=function(t,e){if(c.isNode)return this.load(t,e,u);throw Error("not supported")},d.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,r=e.parent.lookup(e.extend);if(r)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),r.get(n.name)||((n.declaringField=e).extensionField=n,r.add(n)),1}d.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 r)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 r||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},d.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]},d.p=function(t,e,n){r=t,i=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=i;var r=t(39);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function t(e,n,i,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return r.asPromise(t,o,e,n,i,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 i))try{n=i[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}},i.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 r=t(23),i=(((o.prototype=Object.create(r.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){r.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 r=Object.keys(e.methods),s=0;s<r.length;++s)n.add(i.fromJSON(r[s],e.methods[r[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=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",r.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]||r.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){r.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&&(r.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(function(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 i?l((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof i){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 r.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var r,i=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((r=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");i[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:r,q:r.resolvedRequestType.ctor,s:r.resolvedResponseType.ctor})}return i}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=f;var r=/[\s{}=;:[\],'"()<>]/g,i=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,h=/\s/,c=/\\(.?)/g,d={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(c,function(t,e){switch(e){case"\\":case"":return e;default:return d[e]||""}})}function f(t,e){t=t.toString();var n=0,c=t.length,d=1,f=0,p={},m=[],_=null;function g(t){return Error("illegal "+t+" (line "+d+")")}function v(e){return t[0|e]||""}function y(n,r,i){var s,h={type:t[0|n++]||"",lineEmpty:!1,leading:i},c=n-(i=e?2:3);do{if(--c<0||"\n"==(s=t[0|c]||"")){h.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,r).split(l),m=0;m<u.length;++m)u[m]=u[m].replace(e?o:a,"").trim();h.text=u.join("\n").trim(),p[d]=h,f=d}function b(e){var n=S(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function S(t){for(var e=t;e<c&&"\n"!==v(e);)e++;return e}function E(){if(0<m.length)return m.shift();if(_){var a="'"===_?s:i,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,w(_),_=null,u(o[1]);throw g("string")}var l,f,p,E,x,T=0===n;do{if(n===c)return null;for(l=!1;h.test(p=v(n));)if("\n"===p&&(T=!0,++d),++n===c)return null;if("/"===v(n)){if(++n===c)throw g("comment");if("/"===v(n))if(e){if(x=!1,b((E=n)-1))for(x=!0;(n=S(n))!==c&&(n++,T&&b(n)););else n=Math.min(c,S(n)+1);x&&(y(E,n,T),T=!0),d++}else{for(x="/"===v(E=n+1);"\n"!==v(++n);)if(n===c)return null;++n,x&&(y(E,n-1,T),T=!0),++d}else{if("*"!==(p=v(n)))return"/";E=n+1,x=e||"*"===v(E);do{if("\n"===p&&++d,++n===c)throw g("comment")}while(f=p,p=v(n),"*"!==f||"/"!==p);++n,x&&(y(E,n-2,T),T=!0)}l=!0}}while(l);var A=n;if(r.lastIndex=0,!r.test(v(A++)))for(;A<c&&!r.test(v(A));)++A;return'"'!=(a=t.substring(n,n=A))&&"'"!=a||(_=a),a}function w(t){m.push(t)}function x(){if(!m.length){var t=E();if(null===t)return null;w(t)}return m[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,r=null;return t===rt?(n=p[d-1],delete p[d-1],n&&(e||"*"===n.type||n.lineEmpty)&&(r=n.leading?n.text:null)):(f<t&&x(),n=p[t],delete p[t],!n||n.lineEmpty||!e&&"/"!==n.type||(r=n.leading?null:n.text)),r}},"line",{get:function(){return d}})}f.unescape=u},{}],35:[function(t,e,n){e.exports=v;var r=t(23),i=(((v.prototype=Object.create(r.prototype)).constructor=v).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),h=t(21),c=t(27),d=t(42),u=t(37),f=t(14),p=t(13),m=t(40),_=t(12),g=t(41);function v(t,e){r.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 y(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(v.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]],r=n.id;if(this.S[r])throw Error("duplicate id "+r+" in "+this);this.S[r]=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=v.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 r={};for(n=0;n<this.oneofsArray.length;++n)r[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,r)}}}),v.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),r=0;r<t.fieldsArray.length;++r)(e=t.e[r]).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]]")},v.fromJSON=function(t,e){for(var n=new v(t,e.options),h=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),c=0;c<h.length;++c)n.add((void 0!==e.fields[h[c]].keyType?o:a).fromJSON(h[c],e.fields[h[c]]));if(e.oneofs)for(h=Object.keys(e.oneofs),c=0;c<h.length;++c)n.add(s.fromJSON(h[c],e.oneofs[h[c]]));if(e.nested)for(h=Object.keys(e.nested),c=0;c<h.length;++c){var d=e.nested[h[c]];n.add((d.id!==rt?a:d.fields!==rt?v:d.values!==rt?i:d.methods!==rt?l:r).fromJSON(h[c],d))}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},v.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",r.arrayToJSON(this.oneofsArray,t),"fields",r.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])},v.prototype.resolveAll=function(){if(this.y){r.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},v.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(function(e){e.u(t)}),this.fieldsArray.forEach(function(e){e.u(t)})),this},v.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},v.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),y(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),y(this)):r.prototype.add.call(this,t)},v.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),y(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),y(this);throw Error(t+" is not a member of "+this)}return r.prototype.remove.call(this,t)},v.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},v.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)},v.prototype.create=function(t){return new this.ctor(t)},v.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var r;return this.encode=f(this)({Writer:d,types:e,util:u}),this.decode=p(this)({Reader:c,types:e,util:u}),this.verify=m(this)({types:e,util:u}),this.fromObject=_.fromObject(this)({types:e,util:u}),this.toObject=_.toObject(this)({types:e,util:u}),(t=g[t])&&((r=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(r),r.toObject=this.toObject,this.toObject=t.toObject.bind(r)),this},v.prototype.encode=function(t,e){return this.setup().encode(t,e)},v.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},v.prototype.decode=function(t,e){return this.setup().decode(t,e)},v.prototype.decodeDelimited=function(t){return t instanceof c||(t=c.create(t)),this.decode(t,t.uint32())},v.prototype.verify=function(t){return this.setup().verify(t)},v.prototype.fromObject=function(t){return this.setup().fromObject(t)},v.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},v.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 r=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(t,e){var n=0,i={};for(e|=0;n<t.length;)i[r[n+e]]=t[n++];return i}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var r,i,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),r=0;r<e.length;)n[r]=t[e[r++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var r=t[n++],i=t[n++];i!==rt&&(e[r]=i)}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),c=(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(r=r||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(i=i||t(15))("Enum"+c++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,r){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,i){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,i);else{if((n=e[s])&&r)return e;n&&(i=[].concat(n).concat(i)),e[s]=i}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=i;var r=t(39);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=i.zero=new i(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.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 i(n,t))},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):s},i.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},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);i.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new i((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)},i.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)},i.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},i.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},i.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 r=n;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)t[r[i]]!==rt&&n||(t[r[i]]=e[r[i]]);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&&i(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}r.asPromise=t(1),r.base64=t(2),r.EventEmitter=t(4),r.float=t(6),r.inquire=t(7),r.utf8=t(10),r.pool=t(9),r.LongBits=t(38),r.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),r.global=r.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.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)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r.L=null,r.V=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r.V(t):new r.Array(t):r.Buffer?r.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){return t=r.LongBits.fromHash(t),r.Long?r.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},r.merge=i,r.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},r.newError=s,r.ProtocolError=s("ProtocolError"),r.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]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r.p=function(){var t=r.Buffer;t?(r.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r.V=t.allocUnsafe||function(e){return new t(e)}):r.L=r.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=i.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var r=0;r<t.fieldsArray.length;++r){var o,l=t.e[r].resolve(),h="m"+i.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,r,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,r,h+"[i]")("}")):(l.partOf&&(o=i.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,r,h)),l.optional&&e("}")}return e("return null")};var r=t(15),i=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,i){if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(%s){",i)("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,i)("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))",i)("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)))",i,i,i,i)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var r=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,i,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 r?(n=t.$type.toObject(t,e),i="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+i,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=d;var r,i=t(39),s=i.LongBits,a=i.base64,o=i.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function h(){}function c(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function d(){this.len=0,this.head=new l(h,0,0),this.tail=this.head,this.states=null}function u(){return i.Buffer?function(){return(d.create=function(){return new r})()}:function(){return new d}}function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=rt,this.val=e}function m(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 _(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}d.create=u(),d.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.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},d.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},d.prototype.int32=function(t){return t<0?this.M(m,10,s.fromNumber(t)):this.uint32(t)},d.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(t){return t=s.from(t),this.M(m,t.length(),t)},d.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(m,t.length(),t)},d.prototype.bool=function(t){return this.M(f,1,t?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(t){return this.M(_,4,t>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(t){return t=s.from(t),this.M(_,4,t.lo).M(_,4,t.hi)},d.prototype.float=function(t){return this.M(i.float.writeFloatLE,4,t)},d.prototype.double=function(t){return this.M(i.float.writeDoubleLE,8,t)};var g=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};d.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(i.isString(t)&&(e=d.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(f,1,0)},d.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(f,1,0)},d.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new l(h,0,0),this.len=0,this},d.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},d.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},d.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},d.p=function(t){r=t,d.create=u(),r.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var r=t(42),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=i.V,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.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 r=0;r<t.length;)e[n++]=t[r++]}},s.prototype.bytes=function(t){var e=(t=i.isString(t)?i.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=i.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 r=void 0===e?t.len:t.pos+e,i=new $root.MeshData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.index=t.int32();break;case 2:if(i.weights&&i.weights.length||(i.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.weights.push(t.float());else i.weights.push(t.float());break;default:t.skipType(7&s)}}return i},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 r=0;r<t.weights.length;++r)n.weights[r]=e.json&&!isFinite(t.weights[r])?String(t.weights[r]):t.weights[r]}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 r=void 0===e?t.len:t.pos+e,i=new $root.JointData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(i.translate&&i.translate.length||(i.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.translate.push(t.float());else i.translate.push(t.float());break;case 2:i.rotate=t.bytes();break;default:t.skipType(7&s)}}return i},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 r=0;r<t.translate.length;++r)n.translate[r]=e.json&&!isFinite(t.translate[r])?String(t.translate[r]):t.translate[r]}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 r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.id=t.int32();break;case 2:i.s=t.string();break;case 3:i.sf=t.int32();break;case 4:i.ef=t.int32();break;case 5:i.bsw=t.bytes();break;case 11:i.cs=t.bytes();break;case 12:i.js&&i.js.length||(i.js=[]),i.js.push($root.JointData.decode(t,t.uint32()));break;case 13:i.ms&&i.ms.length||(i.ms=[]),i.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:i.bodyId=t.int32();break;case 15:i.faceFrameType=t.int32();break;case 16:i.asf=t.int32();break;case 17:i.aef=t.int32();break;case 18:i.n=t.string();break;default:t.skipType(7&s)}}return i},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 r=0;r<t.js.length;++r)n.js[r]=$root.JointData.toObject(t.js[r],e)}if(t.ms&&t.ms.length)for(n.ms=[],r=0;r<t.ms.length;++r)n.ms[r]=$root.MeshData.toObject(t.ms[r],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 r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameDataList;t.pos<r;){var s=t.uint32();if(s===n)break;s>>>3==1?(i.data&&i.data.length||(i.data=[]),i.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return i},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 r=0;r<t.data.length;++r)n.data[r]=$root.FaceFrameData.toObject(t.data[r],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}();var 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:"音频数据过期"},Ttsa=/*#__PURE__*/function(){function t(t){var e=this,n=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=function(){n.wsConnectTimer&&(clearTimeout(n.wsConnectTimer),n.wsConnectTimer=0)},this.initWsTimeoutTimer=function(){n.clearOldWsTimeoutTimer(),n.wsConnectTimer=window.setTimeout(function(){try{var t=_finallyRethrows(function(){function t(){n.reStartSDK()}n.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"});var e=function(){if(n.session_id)return Promise.resolve(n.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT")).then(function(){n.ws.disconnect()})}();return e&&e.then?e.then(t):t()},function(t,e){if(n.clearOldWsTimeoutTimer(),t)throw e;return e});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},1e3*(n.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;var r=lookup(t.url,{query:{token:this.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});r.on("connect",function(){n.clearReconnectTimer(),n.initWsTimeoutTimer(),n.startHeartbeat(),n.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);var t={room:n.room,client_type:"web",invisible_mode:n.sdk.getPendingInvisibleMode()};n.send("enter_room",t),n.sdk.getStatus()===AvatarStatus.offline&&n.sdk.getIsInitialized()&&n.reloadSuccess()}),r.on("first_start_timestamp",function(e){window.avatarSDKLogger.log(n.TAG,"first_start_timestamp",e),n.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(n.TAG,"ready"),n.reloadSuccess(),t.onReady()}),r.on("state_change",function(t){n.ttsaStateChangeHandle(t)}),r.on("tts_audio",function(e){try{var r=msgpack_min.decode(e);n.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:r[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(n.TAG,"下发音频数据tts_audio",r),t.handleMessage(EFrameDataType.AUDIO,r)}catch(t){n.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),r.on("face_data",function(n){try{try{if(e.framedata_proto_version){var r,i=new Uint8Array(n),s=pako.inflate(i);r=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,function(){}).toJSON()||{data:[]}).data.map(function(t){var e=(t.js||[]).map(function(t){return{translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]}}),n=(t.ms||[]).map(function(t){return{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,r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",r)}else{var a=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",a),"speak"!==a[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,a)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}return Promise.resolve()}catch(n){return Promise.reject(n)}}),r.on("body_data",function(e){try{var r=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,r[0].s);var i=r.map(function(t){return _extends({},t,{x_offset:[]})});window.avatarSDKLogger.log(n.TAG,"body_data",JSON.stringify(i),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,r)}catch(t){n.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),r.on("event_data",function(e){try{var r=msgpack_min.decode(e);window.avatarSDKLogger.log(n.TAG,"event_data",JSON.stringify(r)),t.handleMessage(EFrameDataType.EVENT,r)}catch(t){n.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),r.on("sync_frame",function(e){t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),r.on("aa_frame",function(e){window.avatarSDKLogger.log(n.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),r.on("error_message",function(t){n.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),r.on("disconnect",function(e){n.clearOldWsTimeoutTimer(),n.stopHeartbeat(),"io client disconnect"!==e&&(n.enterOfflineFlag?window.avatarSDKLogger.warn(n.TAG,"已在离线处理中,忽略重复的disconnect事件"):(n.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:"client Warning: socket disconnect, "+e}),window.avatarSDKLogger.warn(n.TAG,t.url+" 已断开","disconnect原因",e),n.enterOfflineFlag=!0,n.sdk.getStatus()===AvatarStatus.offline?n.sdk.onStatusChange(AvatarStatus.offline):n.enterOfflineMode(),-1===n.socketReconnectTimer&&n.reconnect_timeout>0&&(n.socketReconnectTimer=window.setTimeout(function(){try{r.disconnect()}catch(t){window.avatarSDKLogger.warn(n.TAG,"disconnect error",t)}n.socketReconnectTimer=-1},1e3*n.reconnect_timeout)),-1===n.reconnectTimer&&(n.reconnectTimer=window.setTimeout(function(){try{try{r.disconnect()}catch(t){window.avatarSDKLogger.warn(n.TAG,"disconnect error",t)}return Promise.resolve(n.sdk.stopSessionFromSocket("WS_TIMEOUT")).then(function(){n.reStartSDK()})}catch(t){return Promise.reject(t)}},1e3*n.reconnect_client_timeout))))}),r.on("client_quit",function(t){window.avatarSDKLogger.warn(n.TAG,"client_quit","断开原因",t),r.disconnect(),n.session_speak_req_id=0,Object.keys(t).length&&n.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)?(n.sdk.destroyClient(),n.sdk.onStatusChange(AvatarStatus.close)):(n.sdk.getStatus()===AvatarStatus.offline?n.sdk.onStatusChange(AvatarStatus.offline):n.enterOfflineMode(),n.reStartSDK())}),r.on("connect_error",function(t){n.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),r.onAny(function(t,e){n.ws.connected&&n.initWsTimeoutTimer()}),this.ws=r}var e=t.prototype;return e.clearReconnectTimer=function(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()},e.clearSocketReconnectTimer=function(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)},e.startHeartbeat=function(){var t=this;this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(function(){t.send("client_heartbeat",{timestamp:Date.now(),frame:t.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)},e.stopHeartbeat=function(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)},e.start=function(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")},e.idle=function(){this.stateChange("idle")},e.listen=function(){this.stateChange("listen")},e.think=function(){this.stateChange("think")},e.interactiveidle=function(){this.stateChange("interactive_idle")},e.enterInvisibleMode=function(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})},e.exitInvisibleMode=function(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})},e.firstStartTimestamp=function(t){var e=Date.now()/1e3,n={server_time:t,client_time:e},r=this._getResumeInfo();this._isResume&&r&&r.client_frame>0?n.resume_from_offline_idle=r:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)},e.syncTimestamp=function(){var t=this;this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(function(){var e=Date.now();if(e-t.lastSyncTime>=t.SYNC_INTERVAL){var n=t.getCurrentFrameIndex();t.sendSyncTimestamp(n),t.lastSyncTime=e}},this.syncTimestampNum)},e.sendSyncTimestamp=function(t){var e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})},e.sendText=function(t,e,n,r){var i;if(void 0===r&&(r={client_speak_id:""}),this.ws.connected){var s=this.getUniqueSpeakId();null!=(i=r)&&i.client_speak_id||(r.client_speak_id=s);var a={ssml:t,is_start:e,is_end:n,extra:r,multi_turn_conversation_id:s,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.1.0"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},r,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:s,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",a),s}},e.sendSdkPoint=function(t,e,n){void 0===e&&(e={}),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"}))},e.stateChange=function(t,e){var 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)},e.sendPerfLog=function(t){},e.changeLayout=function(t){this.send("change_layout",t)},e.changeWalkConfig=function(t){this.send("walk_config",t)},e.send=function(t,e){this.ws.connected&&this.ws.emit(t,e)},e.sendDeviceInfo=function(t){this.send("stat_report",t)},e.getStatus=function(){return this.ws.connected},e._setResumeInfoCallback=function(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e},e._getResumeInfo=function(){if(this.getResumeInfo){var t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null},e.updateUniqueSpeakId=function(){this._uniqueSpeakId+=1},e.getUniqueSpeakId=function(){return this._uniqueSpeakId+"-"+this.session_id},e.close=function(){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)},e.connect=function(){this.ws.connect()},e.seekToFrame=function(t){this.ws.emit("seek_to_frame",{frame:t})},t}();function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{var 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}}var DebugOverlay=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.setAudioInfo=function(t){this.audioInfo=t},e.setEventData=function(t){this.eventInfo=t},e.addError=function(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()},e.show=function(){var t=this;this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(function(){return t.updateTextOnly()},200)),this.updateTextOnly()},e.hide=function(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)},e.destroy=function(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null},e.setVideoInfo=function(t){this.videoInfo=t},e.updateTextOnly=function(){var t,e;if(this.container){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());var 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))}},e.setText=function(t,e){var n=this.domRefs[t];n&&(n.innerHTML=e)},e.copySessionId=function(){var t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(function(){}).catch(function(t){console.warn("复制失败",t)})},e.createOverlay=function(){var t,e=this;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";var n=function(t,n,r){void 0===r&&(r="");var i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML='<span style="color:#888;font-size:11px;">'+n+":</span>";var s=document.createElement("span");return s.style.color="#fff",s.style.fontSize="11px",s.style.marginLeft="4px",s.textContent=r,i.append(s),e.domRefs[t]=s,i},r=document.createElement("h3");r.textContent="🔍 调试信息",r.style.margin="0 0 12px 0",r.style.color="#00ff88",r.style.fontSize="14px";var i=document.createElement("div");i.append(r,n("look_name","角色look_name"),n("video_name","当前视频"),function(){var t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";var n=document.createElement("span");n.style.color="#888",n.style.fontSize="11px",n.textContent="会话 ID:";var r=document.createElement("span");r.style.color="#fff",r.style.fontSize="11px",r.style.wordBreak="break-all",r.style.flex="1",e.domRefs.session_id=r;var 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=function(){return e.copySessionId()},t.append(n,r,i),t}(),n("frame_idx","当前帧"),n("audio_info","下发音频"),n("event_info","下发事件"),n("fps","FPS"));var s=document.createElement("div");s.style.marginBottom="8px",s.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';var a=document.createElement("div");a.style.fontSize="11px",a.style.background="rgba(0,0,0,0.2)",a.style.padding="4px",a.style.borderRadius="4px",a.style.color="#fff",this.domRefs.perf=a,i.append(s,a);var o=document.createElement("div");o.style.borderTop="1px solid #444",o.style.paddingTop="8px",o.style.marginBottom="8px";var l=document.createElement("h4");l.style.margin="0 0 6px 0",l.style.fontSize="12px",l.style.color="#888";var h=document.createElement("span");this.domRefs.error_count=h,l.append("✅ 错误日志 ",h),o.append(l);var c=function(t){var n=document.createElement("pre");return n.style.margin="0 0 4px 0",n.style.padding="6px",n.style.background="rgba(255,255,255,0.05)",n.style.borderRadius="4px",n.style.fontSize="10px",n.style.lineHeight="1.3",n.style.color="#888",n.style.maxHeight="120px",n.style.overflowY="auto",n.style.whiteSpace="pre-wrap",e.domRefs[t]=n,n},d=c("error_log"),u=c("ttsa_error_log");o.append(d,u),i.append(o),i.append(n("mem","内存占用"),n("session_start","会话开始时间"),n("session_duration","会话时长"),n("network","网络信息")),this.container.append(i),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)},e.formatErrors=function(t){var e=this.errors;return 0===(e=e.filter(t?function(t){return t.code===EErrorCode.TTSA_ERROR}:function(t){return t.code!==EErrorCode.TTSA_ERROR})).length?"暂无错误":e.map(function(t){return"["+new Date(t.timestamp).toLocaleTimeString()+"] "+t.code+": "+t.message}).join("\n")},e.updatePerfMetrics=function(){if(window.performanceTracker)for(var t=window.performanceTracker.getVideoMetrics(),e=0,n=Object.entries(t);e<n.length;e++){var r,i=n[e],s=i[0],a=i[1],o=null!=(r=null==a?void 0:a.time)?r:0;this.perfMetrics[s]||(this.perfMetrics[s]={times:[],avg:0,last:0,count:0});var l=this.perfMetrics[s];l.times.push(o),l.last=o,l.count++,l.avg=l.times.reduce(function(t,e){return t+e},0)/l.times.length}},e.formatPerfMetrics=function(){var t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(function(t){var e=t[1];return t[0]+": 最近:"+e.last.toFixed(2)+"ms 平均:"+e.avg.toFixed(2)+"ms 次数:"+e.count}).join("<br>"):"暂无数据"},e.formatMemory=function(){var 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"},e.trackFPS=function(){var t=this,e=function(n){t.frameCount++,n-t.lastFpsUpdate>=1e3&&(t.fps=t.frameCount,t.frameCount=0,t.lastFpsUpdate=n),requestAnimationFrame(e)};requestAnimationFrame(e)},e.updateMemory=function(){var t;if(null!=(t=window.performance)&&t.memory){var e=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}}},e.trackMemory=function(){var t,e=this;null!=(t=window.performance)&&t.memory&&setInterval(function(){return e.updateMemory()},1e3)},e.getNetworkInfo=function(){var t=navigator.connection;return t?"类型:"+t.effectiveType+" 下行:"+t.downlink+"Mbps 延迟:"+t.rtt+"ms":"N/A"},e.applyStyles=function(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"},e.enableDrag=function(t){var e=!1,n=0,r=0,i=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",function(a){e=!0,n=a.clientX,r=a.clientY,i=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",function(a){e&&(t.style.left=i+a.clientX-n+"px",t.style.top=s+a.clientY-r+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",function(){e=!1,document.body.style.userSelect=""})},t}(),NetworkMonitor=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e._initEventListeners=function(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)},e._handleOnline=function(){window.clearTimeout(this.retryTimer),t.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")},e._handleOffline=function(){t.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()},e._attempt=function(){var t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(function(){},t)},e.setState=function(e){t.ONLINE=e},e.destroy=function(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1},t}();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;var isLoggingEnabled=!1;function executeLog(t){isLoggingEnabled&&"function"==typeof t&&t.apply(void 0,[].slice.call(arguments,1))}var sdkLog={log:function(){return executeLog.apply(void 0,[console.log].concat([].slice.call(arguments)))},info:function(){return executeLog.apply(void 0,[console.info].concat([].slice.call(arguments)))},warn:function(){return executeLog.apply(void 0,[console.warn].concat([].slice.call(arguments)))},error:function(){return executeLog.apply(void 0,[console.error].concat([].slice.call(arguments)))}};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){for(var n=t.char,r=n.evalSkeleton(),i=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length),a=0;a<n.skeleton.length;a++){var o=i[a].apply(r[a].inv());s[a]=o.homogeneous_matrix()}for(var l=[],h=0;h<n.mesh.length;h++){for(var c=[],d=0;d<n.mesh[h].blendshapes.size[0];d++){for(var u=[],f=n.mesh[h].vertices,p=n.mesh[h].blendshapes,m=e.blendshapeWeights,_=0;_<3;_++)u.push(f.data[d*f.size[1]+_]);for(var g=0;g<n.mesh[h].blendshapeIndices.length;g++)for(var v=0;v<3;v++)u[v]+=m[n.mesh[h].blendshapeIndices[g]]*Number(p.data[(d*p.size[1]+v)*p.size[2]+g]);u.push(1);for(var y=[0,0,0,0],b=n.mesh[h].jointIndex,S=n.mesh[h].jointWeight,E=0;E<n.maxJointsPerVertex;E++){var w=b[d*n.maxJointsPerVertex+E];if(w<n.skeleton.length)for(var x=mvmul(s[w],u),T=0;T<4;T++)y[T]+=S[d*n.maxJointsPerVertex+E]*x[T]}for(var A=0;A<3;A++)y[A]/=y[3];c.push([y[0],y[1],y[2]])}l.push(c)}return l}function getPCATextures(t,e){for(var n=t.char,r=[],i=0;i<n.mesh.length;i++){var s=n.mesh[i].textureModels[e.mesh[i].textureModelIndex],a=[],o=new Uint8ClampedArray(s.data.size[1]*s.data.size[2]*4),l=1;s.scalingFactor&&(l*=Number(s.scalingFactor.data[0]));for(var h=0;h<s.data.size[1];h++){for(var c=[],d=0;d<s.data.size[2];d++){for(var u=[],f=0;f<3;f++)u.push(l*sampleUniformPCATensor(s.data.data,3*(h*s.data.size[2]+d)+f));c.push(u)}a.push(c)}for(var p=1;p<s.data.size[0];p++){var m=e.mesh[i].texturePCAWeights[p-1];s.scalingFactor&&(m*=Number(s.scalingFactor.data[p]));for(var _=0;_<s.data.size[1];_++)for(var g=0;g<s.data.size[2];g++)for(var v=0;v<3;v++)a[_][g][v]+=m*sampleUniformPCATensor(s.data.data,3*((p*s.data.size[1]+_)*s.data.size[2]+g)+v)}for(var y=0;y<s.data.size[1];y++)for(var b=0;b<s.data.size[2];b++){for(var S=0;S<3;S++)o[4*(y*s.data.size[2]+b)+S]=Math.round(255*a[s.data.size[1]-1-y][b][2-S]);o[4*(y*s.data.size[2]+b)+3]=255}r.push(new ImageData(o,s.data.size[1],s.data.size[2]))}return r}function exportAsWavefrontObj(t){for(var e,n="",r="",i=1,s=0,a=_createForOfIteratorHelperLoose(t);!(e=a()).done;){for(var o,l=e.value,h=_createForOfIteratorHelperLoose(l.vertices);!(o=h()).done;){var c=o.value;n+="v "+c[0]+" "+c[1]+" "+c[2]+"\n"}for(var d,u=_createForOfIteratorHelperLoose(l.uv);!(d=u()).done;){var f=d.value;n+="vt "+f[0]+" "+f[1]+"}\n"}r+="g Obj"+s+"\n";for(var p,m=_createForOfIteratorHelperLoose(l.polygons);!(p=m()).done;)r+="f "+p.value.map(function(t){return(t+i).toString()}).map(function(t){return t+"/"+t}).join(" ")+"\n";i+=l.vertices.length,s+=1}return n+r}function getWavefrontObjFromVertices(t,e){function n(t,e){for(var n=[],r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,r));return n}function r(t,e){for(var n=[],r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(Number(t[r]));return n}for(var i=t.char,s=[],a=0;a<i.mesh.length;a++)s.push({vertices:e[a],uv:n(i.mesh[a].UVCoord.data,2),polygons:r(i.mesh[a].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});var StreamingClient=/*#__PURE__*/function(){function t(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}var e=t.prototype;return e.connect=function(){var t=this;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=function(){t.connected=!0,t.retryCount=0,console.log("[StreamingClient] 已连接"),t.send({type:"join",role:"client"})},this.ws.onmessage=function(e){var n;try{n=JSON.parse(e.data)}catch(t){return}t.handleMessage(n)},this.ws.onclose=function(){t.connected=!1,t.destroyed||(null==t.options.onDisconnect||t.options.onDisconnect(),t.scheduleRetry())},this.ws.onerror=function(){null==t.options.onError||t.options.onError("WebSocket 连接错误")}}},e.handleMessage=function(t){var e,n,r,i,s,a,o,l,h,c;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(r=(i=this.options).onOffer)||r.call(i,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=(c=this.options).onError)||h.call(c,t.message||"未知错误")}},e.send=function(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))},e.sendApiCall=function(t,e){void 0===e&&(e=[]),this.send({type:"api_call",method:t,params:e})},e.scheduleRetry=function(){var t=this;if(!this.destroyed){var e,n;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(e=(n=this.options).onError)||e.call(n,"连接重试次数已达上限"));var r=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(function(){t.connect()},r)}},e.isConnected=function(){return this.connected},e.destroy=function(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1},t}(),VideoPlayer=/*#__PURE__*/function(){function t(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()}var e=t.prototype;return e.createVideoElement=function(){var 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)},e.createCanvasElement=function(){var 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);var 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)},e.handleOffer=function(t){try{var e=this;return e.destroyPeer(),e.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"}]}),e.pc.onicecandidate=function(t){t.candidate&&e.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},e.pc.ontrack=function(t){console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),e.stream||(e.stream=new MediaStream,e.video&&(e.video.srcObject=e.stream)),e.stream.addTrack(t.track),"audio"===t.track.kind&&e.video&&(e.video.muted=!1,e.video.play().catch(function(){})),"video"===t.track.kind&&e.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),e.startAlphaRendering())},e.pc.onconnectionstatechange=function(){e.pc&&(console.log("[VideoPlayer] WebRTC 状态:",e.pc.connectionState),"connected"===e.pc.connectionState?null==e.options.onConnected||e.options.onConnected():"disconnected"!==e.pc.connectionState&&"failed"!==e.pc.connectionState||null==e.options.onDisconnected||e.options.onDisconnected())},Promise.resolve(e.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}))).then(function(){return Promise.resolve(e.pc.createAnswer()).then(function(t){return Promise.resolve(e.pc.setLocalDescription(t)).then(function(){e.options.streamingClient.send({type:"answer",sdp:t.sdp})})})})}catch(t){return Promise.reject(t)}},e.startAlphaRendering=function(){var t=this;if(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx){var e=this.video,n=this.canvas,r=this.canvasCtx,i=this.tempCanvas,s=this.tempCtx,a=0,o=0,l=0,h=null;h=setInterval(function(){t.destroyed?h&&clearInterval(h):console.log("[VideoPlayer] Alpha 渲染调试: frames="+l+", videoReadyState="+e.readyState+", videoSize="+e.videoWidth+"x"+e.videoHeight+", currentTime="+e.currentTime.toFixed(2)+"s, paused="+e.paused)},2e3);var c=function(){if(t.destroyed)h&&clearInterval(h);else{if(e.readyState>=2&&e.videoWidth>0){var d=e.videoWidth,u=e.videoHeight,f=d/2,p=u;d===a&&u===o||(n.width=f,n.height=p,i.width=d,i.height=p,a=d,o=u,console.log("[VideoPlayer] Alpha Mask: 检测到双流 "+d+"x"+u+" → 原始 "+f+"x"+p)),s.clearRect(0,0,2*f,p),s.drawImage(e,0,0),r.clearRect(0,0,f,p),r.drawImage(i,0,0,f,p,0,0,f,p);try{var m=r.getImageData(0,0,f,p),_=s.getImageData(f,0,f,p),g=m.data,v=_.data;if(0===l){for(var y=0,b=0,S=Math.min(1e3,g.length/4),E=0;E<4*S;E+=4)(g[E]>0||g[E+1]>0||g[E+2]>0)&&y++,v[E]>0&&b++;console.log("[VideoPlayer] 首帧像素检查: RGB非零="+y+"/"+S+", Alpha非零="+b+"/"+S),0===y&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(var w=0;w<g.length;w+=4)g[w+3]=v[w];r.putImageData(m,0,0),l++}catch(t){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",t),r.drawImage(e,0,0,f,p,0,0,f,p),l++}}t.animFrameId=requestAnimationFrame(c)}};this.animFrameId=requestAnimationFrame(c)}},e.addIceCandidate=function(t){try{var e=this,n=function(){if(e.pc)return Promise.resolve(e.pc.addIceCandidate(t).catch(function(t){console.warn("[VideoPlayer] addIceCandidate 失败:",t)})).then(function(){})}();return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},e.getVideoElement=function(){return this.video},e.getCanvasElement=function(){return this.canvas},e.isConnected=function(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)},e.destroyPeer=function(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)},e.destroy=function(){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},t}(),EventDispatcher=/*#__PURE__*/function(){function t(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}var e=t.prototype;return e.dispatch=function(t,e,n){var r,i,s,a,o,l,h,c,d,u,f,p,m,_,g,v,y,b,S,E,w,x,T,A,R,P;switch(t){case"state_change":null==(r=(i=this.callbacks).onStateChange)||r.call(i,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=(c=this.callbacks).onStatusChange)||h.call(c,e.status);break;case"render_change":null==(d=(u=this.callbacks).onRenderChange)||d.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)||m.call(_,e);break;case"message":case"error":null==(g=(v=this.callbacks).onMessage)||g.call(v,e);break;case"network_info":null==(y=(b=this.callbacks).onNetworkInfo)||y.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=(P=this.callbacks).onFrameDataUpdate)||R.call(P,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}},e.getSubtitleText=function(){return this.subtitleText},e.isSubtitleVisible=function(){return this.subtitleVisible},t}(),APIForwarder=/*#__PURE__*/function(){function t(t){this.client=t}var e=t.prototype;return e.speak=function(t,e,n,r){void 0===e&&(e=!0),void 0===n&&(n=!0),void 0===r&&(r={}),this.client.sendApiCall("speak",[t,e,n,r])},e.idle=function(){this.client.sendApiCall("idle",[])},e.listen=function(){this.client.sendApiCall("listen",[])},e.think=function(){this.client.sendApiCall("think",[])},e.interactiveidle=function(){this.client.sendApiCall("interactiveidle",[])},e.interrupt=function(t){this.client.sendApiCall("interrupt",[t])},e.changeLayout=function(t){this.client.sendApiCall("changeLayout",[t])},e.changeWalkConfig=function(t){this.client.sendApiCall("changeWalkConfig",[t])},e.setVolume=function(t){this.client.sendApiCall("setVolume",[t])},e.changeAvatarVisible=function(t){this.client.sendApiCall("changeAvatarVisible",[t])},e.switchInvisibleMode=function(){this.client.sendApiCall("switchInvisibleMode",[])},e.destroy=function(t){void 0===t&&(t="user"),this.client.sendApiCall("destroy",[t])},e.init=function(t){this.client.send({type:"init",config:t})},t}();function _catch$2(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var _iteratorSymbol="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function _settle(t,e,n){if(!t.s){if(n instanceof _Pact){if(!n.s)return void(n.o=_settle.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(_settle.bind(null,t,e),_settle.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}var _Pact=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){var r=new t,i=this.s;if(i){var s=1&i?e:n;if(s){try{_settle(r,1,s(this.v))}catch(t){_settle(r,2,t)}return r}return this}return this.o=function(t){try{var i=t.v;1&t.s?_settle(r,1,e?e(i):i):n?_settle(r,1,n(i)):_settle(r,2,i)}catch(t){_settle(r,2,t)}},r},t}();function _isSettledPact(t){return t instanceof _Pact&&1&t.s}function _forTo(t,e,n){var r,i,s=-1;return function a(o){try{for(;++s<t.length&&(!n||!n());)if((o=e(s))&&o.then){if(!_isSettledPact(o))return void o.then(a,i||(i=_settle.bind(null,r=new _Pact,2)));o=o.v}r?_settle(r,1,o):r=o}catch(t){_settle(r||(r=new _Pact),2,t)}}(),r}function _forOf(t,e,n){if("function"==typeof t[_iteratorSymbol]){var r,i,s,a=function(t){try{for(;!((r=o.next()).done||n&&n());)if((t=e(r.value))&&t.then){if(!_isSettledPact(t))return void t.then(a,s||(s=_settle.bind(null,i=new _Pact,2)));t=t.v}i?_settle(i,1,t):i=t}catch(t){_settle(i||(i=new _Pact),2,t)}},o=t[_iteratorSymbol]();if(a(),o.return){var l=function(t){try{r.done||o.return()}catch(t){}return t};if(i&&i.then)return i.then(l,function(t){throw l(t)});l()}return i}if(!("length"in t))throw new TypeError("Object is not iterable");for(var h=[],c=0;c<t.length;c++)h.push(t[c]);return _forTo(h,function(t){return e(h[t])},n)}function _for(t,e,n){for(var r;;){var i=t();if(_isSettledPact(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!_isSettledPact(s)){r=1;break}s=s.s}if(e){var a=e();if(a&&a.then&&!_isSettledPact(a)){r=2;break}}}var o=new _Pact,l=_settle.bind(null,o,2);return(0===r?i.then(c):1===r?s.then(h):a.then(d)).then(void 0,l),o;function h(r){s=r;do{if(e&&(a=e())&&a.then&&!_isSettledPact(a))return void a.then(d).then(void 0,l);if(!(i=t())||_isSettledPact(i)&&!i.v)return void _settle(o,1,s);if(i.then)return void i.then(c).then(void 0,l);_isSettledPact(s=n())&&(s=s.v)}while(!s||!s.then);s.then(h).then(void 0,l)}function c(t){t?(s=n())&&s.then?s.then(h).then(void 0,l):h(s):_settle(o,1,s)}function d(){(i=t())?i.then?i.then(c).then(void 0,l):c(i):_settle(o,1,s)}}function checkSecureContextSync(){var t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{var t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};var 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(){var t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,r=void 0!==window.MediaSource,i={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:r,hasMediaSource:r}};return n||r?{name:"audio",supported:!0,severity:"fatal",detail:i}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:i}}function checkWebCodecsSync(){var 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(){var t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}var checkCapability=function(t){void 0===t&&(t=!1);try{var e,n=function(t){return e?t:Promise.resolve(Promise.all([Promise.resolve(r.items.find(function(t){return"secureContext"===t.name})),Promise.resolve(r.items.find(function(t){return"webgl2"===t.name})),Promise.resolve(r.items.find(function(t){return"audio"===t.name})),checkWebCodecsDetailed(),checkWorkerDetailed()])).then(function(t){var e=t.filter(function(t){return"fatal"===t.severity&&!t.supported}).length;return{supported:0===e,fatalCount:e,warnCount:t.filter(function(t){return"warn"===t.severity&&!t.supported}).length,items:t}})},r=checkCapabilitySync(t),i=function(){if(t)return Promise.resolve(Promise.all([Promise.resolve(r.items.find(function(t){return"secureContext"===t.name})),Promise.resolve(r.items.find(function(t){return"audio"===t.name})),checkWorkerDetailed()])).then(function(t){var n=t.filter(function(t){return"fatal"===t.severity&&!t.supported}).length,r=t.filter(function(t){return"warn"===t.severity&&!t.supported}).length;return e=1,{supported:0===n,fatalCount:n,warnCount:r,items:t}})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(t){return Promise.reject(t)}},checkWorkerDetailed=function(){try{var t,e=function(e){return t?e:{name:"worker",supported:!1,severity:"warn",reason:"Web Worker 创建超时(已重试 "+WORKER_CHECK_MAX_ATTEMPTS+" 次)",detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}};if("undefined"==typeof Worker)return Promise.resolve({name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"});var n=1,r=_for(function(){return!t&&n<=WORKER_CHECK_MAX_ATTEMPTS},function(){return!!(n+=1)},function(){return Promise.resolve(probeWorkerExecution()).then(function(e){return"supported"===e.status?(t=1,{name:"worker",supported:!0,severity:"fatal",detail:{attempts:n}}):"failed"===e.status?(t=1,{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}):void 0})});return Promise.resolve(r&&r.then?r.then(e):e(r))}catch(t){return Promise.reject(t)}},checkWebCodecsDetailed=function(){try{return Promise.resolve(_catch$2(function(){function t(){var t=s||a,n=o&&!t?"warn":"fatal";return{name:"webcodecs",supported:t,severity:n,reason:t?void 0:"warn"===n?"WebCodecs 探测异常(运行时将以实际视频配置二次确认)":"浏览器不支持 H.264 解码(默认/软解配置均不可用)",detail:{hasVideoDecoder:e,isAndroid:r,hardwareAcceleration:r?"prefer-software":"default",codecSupport:i}}}var e=void 0!==window.VideoDecoder;if(!e)return{name:"webcodecs",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:e}};var n=(navigator.userAgent||"").toLowerCase(),r=/android/.test(n)||/openharmony|arkweb/.test(n),i={},s=!1,a=!1,o=!1,l=_forOf(["avc1.42E01E","avc1.4D001F","avc1.64001F"],function(t){var e=_catch$2(function(){return Promise.resolve(window.VideoDecoder.isConfigSupported({codec:t,codedWidth:2160,codedHeight:1920})).then(function(e){function n(){i[t]={default:o,software:l}}var o=!(null==e||!e.supported);o&&(a=!0);var l=null,h=function(){if(r){var e=function(){l&&(s=!0)},n=_catch$2(function(){return Promise.resolve(window.VideoDecoder.isConfigSupported({codec:t,codedWidth:2160,codedHeight:1920,hardwareAcceleration:"prefer-software"})).then(function(t){l=!(null==t||!t.supported)})},function(){l=!1});return n&&n.then?n.then(e):e()}o&&(s=!0)}();return h&&h.then?h.then(n):n()})},function(){o=!0,i[t]={default:!1,software:null,error:"probe-failed"}});if(e&&e.then)return e.then(function(){})});return l&&l.then?l.then(t):t()},function(t){return{name:"webcodecs",supported:!1,severity:"fatal",reason:"WebCodecs 探测失败",detail:t}}))}catch(t){return Promise.reject(t)}};function checkCapabilitySync(t){void 0===t&&(t=!1);var e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkWorkerSync());var n=e.filter(function(t){return"fatal"===t.severity&&!t.supported}).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(function(t){return"warn"===t.severity&&!t.supported}).length,items:e}}var WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(function(t){var e=null,n=null,r=!1,i=null,s=function(s){var a;r||(r=!0,null!==i&&clearTimeout(i),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{var a=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(a),(e=new Worker(n)).onmessage=function(t){s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=function(t){s({status:"failed",reason:"Web Worker 创建失败",detail:t})},i=setTimeout(function(){s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}function _catch$1(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var 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}}}var WebCodecOpusEncoder=/*#__PURE__*/function(){function t(t){void 0===t&&(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)}t.isSupported=function(){try{return"undefined"==typeof AudioEncoder?Promise.resolve(!1):Promise.resolve(_catch$1(function(){return Promise.resolve(AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}))).then(function(t){var e;return!0===t.supported&&(null==(e=t.config)||null==(e=e.opus)?void 0:e.frameDuration)===OPUS_FRAME_DURATION_US})},function(){return!1}))}catch(t){return Promise.reject(t)}};var e=t.prototype;return e.init=function(){try{var t=this;return t.isInitialized||(t.encoder=t.createEncoder(),t.isInitialized=!0),Promise.resolve()}catch(t){return Promise.reject(t)}},e.encode=function(t){try{var e=this;if(!e.isInitialized||!e.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(e.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));var n=new Int16Array(t),r=e.timestamp,i=Math.round(1e6*t.length/e.config.sampleRate),s=r+i,a=i/OPUS_FRAME_DURATION_US;if(!Number.isInteger(a))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));var o=new AudioData({format:"s16",sampleRate:e.config.sampleRate,numberOfFrames:n.length,numberOfChannels:e.config.channels,timestamp:r,data:n}),l=new Promise(function(t,n){var i=globalThis.setTimeout(function(){e.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);e.pendingEncode={startTimestampUs:r,endTimestampUs:s,expectedFrameCount:a,chunks:[],resolve:t,reject:n,timeoutId:i}});try{e.encoder.encode(o),e.timestamp=s}catch(t){e.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{o.close()}return Promise.resolve(l)}catch(t){return Promise.reject(t)}},e.reset=function(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}},e.destroy=function(){try{var t=function(){e.encoder=null,e.isInitialized=!1},e=this,n=e.encoder,r=function(){if(n){var t=function(){e.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{n.close()}catch(t){}},r=_catch$1(function(){return Promise.resolve(n.flush()).then(function(){})},function(){});return r&&r.then?r.then(t):t()}}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(t){return Promise.reject(t)}},e.createEncoder=function(){var t,e=this;return(t=new AudioEncoder({output:function(n){e.encoder===t&&e.handleOutput(n)},error:function(n){if(e.encoder===t){var r=n instanceof Error?n:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",r),e.failPending(r)}}})).configure(buildAudioEncoderConfig(this.config)),t},e.handleOutput=function(t){var e=this.pendingEncode;if(e)if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(!(e.chunks.length<e.expectedFrameCount)){var n=e.chunks.map(function(t,n){var r,i,s=new Uint8Array(t.byteLength);t.copyTo(s);var a=null!=(r=null==(i=e.chunks[n+1])?void 0:i.timestamp)?r:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),r=n.reduce(function(t,e){return t+e.durationMs},0);n.some(function(t){return t.durationMs!==OPUS_FRAME_DURATION_US/1e3})||r!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}},e.failPending=function(t){var e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))},t}(),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},WebMMuxer=/*#__PURE__*/function(){function t(t){void 0===t&&(t=16e3),this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}var e=t.prototype;return e.writeHeader=function(){if(!this.hasHeader){var 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}},e.feedOpusFrame=function(t,e){void 0===e&&(e=this.frameDuration),this.hasHeader||this.writeHeader();var n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e},e.flush=function(){if(0===this.chunks.length)return new ArrayBuffer(0);for(var t,e=this.chunks.reduce(function(t,e){return t+e.length},0),n=new Uint8Array(e),r=0,i=_createForOfIteratorHelperLoose(this.chunks);!(t=i()).done;){var s=t.value;n.set(s,r),r+=s.length}return this.chunks=[],n.buffer},e.reset=function(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0},e.encodeVINT=function(t,e){if(void 0!==e){for(var n=new Uint8Array(e),r=e-1;r>=0;r--)n[r]=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)},e.encodeID=function(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])},e.encodeUint=function(t){if(0===t)return new Uint8Array([0]);for(var e=[],n=t;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)},e.encodeString=function(t){return(new TextEncoder).encode(t)},e.encodeFloat32=function(t){var e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)},e.encodeElement=function(t,e){var n=this.encodeID(t),r=this.encodeVINT(e.length),i=new Uint8Array(n.length+r.length+e.length);return i.set(n,0),i.set(r,n.length),i.set(e,n.length+r.length),i},e.encodeUintElement=function(t,e){return this.encodeElement(t,this.encodeUint(e))},e.encodeStringElement=function(t,e){return this.encodeElement(t,this.encodeString(e))},e.encodeFloat32Element=function(t,e){return this.encodeElement(t,this.encodeFloat32(e))},e.concatArrays=function(t){for(var e,n=t.reduce(function(t,e){return t+e.length},0),r=new Uint8Array(n),i=0,s=_createForOfIteratorHelperLoose(t);!(e=s()).done;){var a=e.value;r.set(a,i),i+=a.length}return r},e.buildEBMLHeader=function(){var 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)},e.buildSegmentInfo=function(){var 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)},e.buildOpusTracks=function(){var 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)]),r=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,r)},e.buildCluster=function(t,e){var n=this.encodeUintElement(EBML_ID.Timecode,t),r=this.encodeVINT(1),i=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([r,i,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)},t}(),PcmWebMEncoder=/*#__PURE__*/function(){function t(){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}t.isSupported=function(){return WebCodecOpusEncoder.isSupported()};var e=t.prototype;return e.init=function(){try{return Promise.resolve(this.opusEncoder.init()).then(function(){})}catch(t){return Promise.reject(t)}},e.encode=function(t){try{var e=this;if(1600!==t.length)throw new Error("PCM 音频块必须为 1600 samples,实际为 "+t.length);if(e.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");e.pendingBlocks+=1;var n=e.generation,r=new Int16Array(t),i=e.queue.then(function(){try{return e.destroyed||n!==e.generation?Promise.resolve(new ArrayBuffer(0)):Promise.resolve(e.opusEncoder.encode(r)).then(function(t){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(var r,i=_createForOfIteratorHelperLoose(t);!(r=i()).done;){var s=r.value;e.muxer.feedOpusFrame(s.data,s.durationMs)}return e.muxer.flush()})}catch(t){return Promise.reject(t)}}).finally(function(){e.pendingBlocks-=1});return e.queue=i.then(function(){},function(){}),Promise.resolve(i)}catch(t){return Promise.reject(t)}},e.reset=function(){var t=this,e=++this.generation;this.queue=this.queue.then(function(){t.destroyed||e!==t.generation||(t.opusEncoder.reset(),t.muxer.reset())})},e.destroy=function(){try{var t=this;return t.destroyed=!0,t.generation+=1,Promise.resolve(t.opusEncoder.destroy()).then(function(){return Promise.resolve(t.queue).then(function(){t.muxer.reset()})})}catch(t){return Promise.reject(t)}},t}(),MediaRecorderEncoder=/*#__PURE__*/function(){function t(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}t.isSupported=function(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")};var e=t.prototype;return e.init=function(){try{var t=this,e=window.AudioContext||window.webkitAudioContext;t.audioCtx=new e({sampleRate:16e3});var n=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"}),r=URL.createObjectURL(n);return Promise.resolve(t.audioCtx.audioWorklet.addModule(r)).then(function(){URL.revokeObjectURL(r),t.workletNode=new AudioWorkletNode(t.audioCtx,"pcm-injector-processor"),t.destination=t.audioCtx.createMediaStreamDestination(),t.workletNode.connect(t.destination);var e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.recorder=new MediaRecorder(t.destination.stream,{mimeType:e,audioBitsPerSecond:24e3}),t.recorder.ondataavailable=function(e){e.data&&e.data.size>0&&e.data.arrayBuffer().then(function(e){if(t.nextResolve){var n=t.nextResolve;t.nextResolve=null,n(e)}else t.dataQueue.push(e)})};var n=function(){if("suspended"===t.audioCtx.state)return Promise.resolve(t.audioCtx.resume()).then(function(){})}();if(n&&n.then)return n.then(function(){})})}catch(t){return Promise.reject(t)}},e.feedPCM=function(t){try{var e=this;return e.workletNode&&e.recorder?(e.isRecording||(e.recorder.start(100),e.isRecording=!0),e.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),Promise.resolve(e.dataQueue.length>0?e.dataQueue.shift():new Promise(function(t){var n=setTimeout(function(){e.nextResolve=null,t(null)},200);e.nextResolve=function(e){clearTimeout(n),t(e)}}))):Promise.resolve(null)}catch(t){return Promise.reject(t)}},e.reset=function(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]},e.destroy=function(){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},t}();function _catch(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}var XmovAvatar=/*#__PURE__*/function(){function t(t){var e=this;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=function(){},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=function(){e.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:function(t){if(e.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!e.isInitialized)return window.avatarSDKLogger.warn(e.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void e.cleanupBeforeInitComplete("network_offline_before_init");e.status!==AvatarStatus.offline&&e.offlineHandle()},onlineCallback:function(t){var n;if(e.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!e.isInitialized)return window.avatarSDKLogger.warn(e.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void e.cleanupBeforeInitComplete("network_online_before_init");null==(n=e.ttsa)||n.clearReconnectTimer(),e.isStartRetry&&e.triggerReconnect()}})}var e=t.prototype;return e.getStatus=function(){return this.status},e.getIsInitialized=function(){return this.isInitialized},e.getUniqueSpeakId=function(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||"0-"+this.getSessionId()},e.initializeSDK=function(t){try{var e,n,r,i=this;if(!navigator.onLine)return i.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"}),Promise.resolve();var s=i,a=t,o=t.containerId,l=t.container,h=t.appId,c=t.appSecret,d=t.gatewayServer,u=t.cacheServer,f=t.config,p=(null!=(e=null==f||null==(n=f.layout)?void 0:n.avatar)?e:{}).scale;null!=f&&null!=(r=f.layout)&&null!=(r=r.avatar)&&r.scale&&(f.layout.avatar.scale=validateScaleWithDecimal(void 0===p?1:p,"initializeSDK"));var m=_extends({},f||{},{raw_audio:!isSupportMES()});if(l&&l instanceof HTMLElement)i.el=l;else{var _=document.querySelector(o);if(!_)return i.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:"containerId: "+o+" 不存在"}),Promise.resolve();i.el=_}var g=document.createElement("div");g.setAttribute("id","avatar-bg-container"),g.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),i.el.appendChild(g);var v=i.el.getAttribute("style");return i.el.setAttribute("style",v?"position:relative;overflow:hidden;"+v:"position:relative;overflow:hidden;"),i.resourceManager=new ResourceManager({sdkInstance:i,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:a.sessionRequestData,appId:h,appSecret:c,gatewayServer:d,cacheServer:u,config:m,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo:function(e){s.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:function(t){null==i.options.onStartSessionWarning||i.options.onStartSessionWarning(t)}}),i.renderScheduler=new RenderScheduler({sdkInstance:i,container:i.el,resourceManager:i.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:i.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:function(t){var e,n,r;null==i.onDownloadProgress||i.onDownloadProgress(t),null==(e=i.el)||e.setAttribute("style",(null==(n=i.el)?void 0:n.style.cssText)+"opacity:"+(100===t?"1":"0")+";"),i.isInitialized=100===t,100===t&&(i.pendingInvisibleMode||i.status===AvatarStatus.online||i.status===AvatarStatus.invisible||i.onStatusChange(AvatarStatus.online),i.resourceManager._setOfflineCache(),null==(r=i.ttsa)||r.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(function(){var t,e;null==(t=i.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.1.0",resolution:null==(e=i.resourceManager.getConfig())?void 0:e.resolution,download_speed:s.networkInfo.downlink||0}))},20),i.enableAudioPlaybackCapture())},onStateChange:function(e){i.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:function(e,n){null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&i.getStatus()!==AvatarStatus.online||!i.isInitialized||(window.avatarSDKLogger.log(i.TAG,"Status:===== 渲染中,状态: rendering",i.getSessionId()),i.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:function(e,n,r){null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,r)},onWalkStateChange:function(e){null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:function(t){var e;null==(e=i.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:function(e,n){null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:function(t){var e;null==(e=i.debugOverlay)||e.setAudioInfo(t)},setEventData:function(t){var e;null==(e=i.debugOverlay)||e.setEventData(t)},renderFrameCallback:function(t){i.renderFrameCallback(t),i.handleReplaySend(t)},reportMessage:function(t){i.onMessage(t)},sendSdkPoint:function(t,e,n){var r;null==(r=i.ttsa)||r.sendSdkPoint(t,e,n)},sendMessage:function(t,e){var n;null==(n=i.ttsa)||n.send(t,e)},onFPSUpdate:function(e){null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:function(e){null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=f&&f.walk_config&&i.changeWalkConfig(f.walk_config),null!=f&&f.layout&&i.changeLayout(f.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{},Promise.resolve()}catch(t){return Promise.reject(t)}},e.initializeClient=function(t){var e=this,n=t.containerId,r=t.container;if(r&&r instanceof HTMLElement)this.el=r;else{var i,s,a=document.querySelector(n);if(!a)return void(null==(i=(s=this.options).onMessage)||i.call(s,{code:EErrorCode.CONTAINER_NOT_FOUND,message:"containerId: "+n+" 不存在"}));this.el=a}var o=this.el.getAttribute("style");this.el.setAttribute("style",o?"position:relative;overflow:hidden;"+o:"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:function(t){null==e._clientOnDownloadProgress||e._clientOnDownloadProgress(t),t>=100&&!e.isInitialized&&(e.isInitialized=!0)},onSessionId:function(t){e._clientSessionId=t,window.avatarSDKLogger.log(e.TAG,"[client] 收到 session_id:",t)}});var l=t.streamingServer||"ws://"+location.hostname+":8080";this._streamingClient=new StreamingClient({url:l,onReady:function(){if(window.avatarSDKLogger.log(e.TAG,"[client] 双方就绪,等待 Server 推流..."),e._pendingInit){var t;e._pendingInit=!1;var n=e._pendingInitConfig;e._pendingInitConfig=null,window.avatarSDKLogger.log(e.TAG,"[client] 补发 init 命令"),null==(t=e._apiForwarder)||t.init(n)}},onOffer:function(t){var n;null==(n=e._videoPlayer)||n.handleOffer(t)},onIce:function(t){var n;null==(n=e._videoPlayer)||n.addIceCandidate(t)},onEventProxy:function(t,n,r){var i;null==(i=e._eventDispatcher)||i.dispatch(t,n,r)},onError:function(t){null==e.options.onMessage||e.options.onMessage({code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:function(){e.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:function(){window.avatarSDKLogger.log(e.TAG,"[client] WebRTC 已连接"),e.onStatusChange(AvatarStatus.online)},onDisconnected:function(){e.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)},e.renderFrameCallback=function(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()},e.init=function(t){try{var e=this;return Promise.resolve(checkCapability(e.options.audioOnlyMode)).then(function(n){if(n.supported){if(e.destroyed=!1,e.isInitialized=!1,e.incompleteInitializationCleanupPromise=null,e.startConnectTime=Date.now(),!e._isClientMode){var r=t.onDownloadProgress,i=t.initModel;return e.onDownloadProgress=function(t){15===t&&(e.sessionResTime=Date.now()),80===t&&(e.charbinResTime=Date.now()),r(t)},i===InitModel.invisible&&(e.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render),Promise.resolve(e.resourceManager.load(e.onDownloadProgress.bind(e))).then(function(t){if(e.destroyed)window.avatarSDKLogger.warn(e.TAG,"sdk destroyed during load, aborting after resourceManager load");else{if(null!=t&&t.socket_io_url&&null!=t&&t.token)return e.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),e.debugOverlay=new DebugOverlay(e,t),e.ttsa=e.connectTtsa(t),e.renderScheduler.init(),e.renderScheduler.setAvatarCanvasVisible(e.avatarCanvasVisible),window.performanceTracker.setReportFunc(e.ttsa),window.addEventListener("beforeunload",e.handleBeforeUnload),document.addEventListener("visibilitychange",e.boundVisibilityChange),t;window.avatarSDKLogger.error(e.TAG,"init error, socket_io_url or token is empty reload")}})}var s;e._clientOnDownloadProgress=t.onDownloadProgress||null;var a,o={appId:e.options.appId,appSecret:e.options.appSecret,gatewayServer:e.options.gatewayServer,cacheServer:e.options.cacheServer,headers:e.options.headers,tag:e.options.tag,gateway_type:e.options.gateway_type,env:e.options.env,config:e.options.config,hardwareAcceleration:e.options.hardwareAcceleration,enableDebugger:e.options.enableDebugger,initModel:t.initModel,scaleDownBy:e.options.scaleDownBy||1,useAlphaMask:e.options.useAlphaMask};null!=(s=e._streamingClient)&&s.isConnected()?null==(a=e._apiForwarder)||a.init(o):(e._pendingInit=!0,e._pendingInitConfig=o,window.avatarSDKLogger.log(e.TAG,"[client] WebSocket 未连接,init 命令暂存"))}else{var l="浏览器能力检查失败: "+n.items.filter(function(t){return"fatal"===t.severity&&!t.supported}).map(function(t){return t.reason}).join("; ");e.onMessage({code:EErrorCode.INIT_ERROR,message:l})}})}catch(t){return Promise.reject(t)}},e.setAudioPlaybackDataHandler=function(t){this.options.onAudioPlaybackData=t},e.restartAudioPlaybackCapture=function(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)},e.enableAudioPlaybackCapture=function(){var t,e=this;return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(function(){e.captureSetupPromise=null}):this.setupAudioCapture().finally(function(){e.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve()},e.setupAudioCapture=function(){try{var t=this,e=document.getElementById("xmov-avatar-audio");return e&&t.options.onAudioPlaybackData?t.captureAudioCtx||t.captureSource?Promise.resolve():void 0===window.AudioWorkletNode?(t.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"}),Promise.resolve()):Promise.resolve(_catch(function(){return Promise.resolve(PcmWebMEncoder.isSupported()).then(function(n){return n?(t.pcmWebMEncoder=new PcmWebMEncoder,Promise.resolve(t.pcmWebMEncoder.init()).then(function(){if(t.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==t.captureAudioCtx.sampleRate)throw new Error("浏览器无法创建 16000 Hz AudioContext: "+t.captureAudioCtx.sampleRate);t.captureSource=t.captureAudioCtx.createMediaElementSource(e),t.captureSource.connect(t.captureAudioCtx.destination);var n=!1,r=!0,i=0,s=0,a=function(e){var a=++t.captureGeneration;n=!0,r=!0,i=Date.now()-100,s=0,t.captureLastSpeechId=e,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){var e;a===t.captureGeneration&&(null==(e=t.pcmWebMEncoder)||e.reset())})};t.restartPlaybackCaptureImpl=function(){n&&a(t.renderScheduler.getSpeechId())};var o=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"}),l=URL.createObjectURL(o);return Promise.resolve(t.captureAudioCtx.audioWorklet.addModule(l)).then(function(){function e(){var e;if("running"!==t.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(e=window.avatarSDKLogger)||e.log(t.TAG,"[AudioCapture] 初始化成功,采样率:",t.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}URL.revokeObjectURL(l),t.captureWorklet=new AudioWorkletNode(t.captureAudioCtx,"audio-capture-processor"),t.captureSource.connect(t.captureWorklet),t.captureWorklet.connect(t.captureAudioCtx.destination),t.captureEncodeQueue=Promise.resolve(),t.captureWorklet.port.onmessage=function(e){if(t.options.onAudioPlaybackData){var o=e.data,l=o.hasAudio,h=o.pcmData,c=t.renderScheduler.getSpeechId();if(l&&!n||l&&n&&c!==t.captureLastSpeechId?a(c):!l&&n&&function(){var e=++t.captureGeneration;n=!1,t.captureLastSpeechId=-2,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){var n;e===t.captureGeneration&&(null==(n=t.pcmWebMEncoder)||n.reset())})}(),l&&n&&h instanceof ArrayBuffer){var d=t.captureGeneration,u=r;r=!1;var f=i+100*s;s+=1,t.captureEncodeQueue=t.captureEncodeQueue.then(function(){try{var e;return Promise.resolve(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(h))).then(function(e){e&&0!==e.byteLength&&d===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:e,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:f,speech_id:c}))})}catch(t){return Promise.reject(t)}}).catch(function(e){var n;null==(n=window.avatarSDKLogger)||n.error(t.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",e)})}}};var o=function(){if("suspended"===t.captureAudioCtx.state)return Promise.resolve(t.captureAudioCtx.resume()).then(function(){})}();return o&&o.then?o.then(e):e()})})):void t.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"})})},function(e){function n(){var n,r;t.captureAudioCtx=null,null==(n=t.pcmWebMEncoder)||n.destroy(),t.pcmWebMEncoder=null,null==(r=window.avatarSDKLogger)||r.error(t.TAG,"[AudioCapture] 初始化失败:",e)}if(t.captureGeneration++,t.restartPlaybackCaptureImpl=null,t.captureWorklet){try{t.captureWorklet.port.onmessage=null,t.captureWorklet.disconnect()}catch(t){}t.captureWorklet=null}try{var r;null==(r=t.captureSource)||r.disconnect()}catch(t){}t.captureSource=null;var i=function(){if(t.captureAudioCtx&&"closed"!==t.captureAudioCtx.state)return Promise.resolve(t.captureAudioCtx.close().catch(function(){})).then(function(){})}();return i&&i.then?i.then(n):n()})):Promise.resolve()}catch(t){return Promise.reject(t)}},e.setupPCMCapture=function(){try{var t,e=this;if(!e.options.onAudioPlaybackData)return Promise.resolve();var n,r=null==(t=e.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();return r?Promise.resolve(PcmWebMEncoder.isSupported()).then(function(t){var n,i=MediaRecorderEncoder.isSupported();if(!t&&!i)return null==(n=window.avatarSDKLogger)||n.warn(e.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void e.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});var s=_catch(function(){function n(){return e.restartPlaybackCaptureImpl=function(){var t,n;e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=e.renderScheduler.getSpeechId(),e.pcmEncodeId++,null==(t=e.pcmWebMEncoder)||t.reset(),null==(n=e.mediaRecorderEncoder)||n.reset(),r.resetCaptureBuffer()},Promise.resolve(r.attachCapture(function(t){var n=t.pcmData,i=t.hasAudio;try{var s;return Promise.resolve(_catch(function(){function t(t){if(s)return t;if(d){var n=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:d,codec:"opus",isFirstChunk:n,sampleRate:16e3,samples:1600,timestamp:a,speech_id:h})}}if(e.options.onAudioPlaybackData){var a=Date.now()-100;if(r.isPlaying){var o,l,h=e.renderScheduler.getSpeechId();if(h!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=h,e.pcmEncodeId++,null==(o=e.pcmWebMEncoder)||o.reset(),null==(l=e.mediaRecorderEncoder)||l.reset(),r.resetCaptureBuffer()),i){var c=e.pcmEncodeId,d=null,u=performance.now(),f=function(){if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){var t=new Int16Array(n);return Promise.resolve(e.pcmWebMEncoder.encode(t)).then(function(t){var n;if(d=t,c!==e.pcmEncodeId)return null==(n=window.avatarSDKLogger)||n.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"),void(s=1);if(0!==d.byteLength){var r,i=performance.now()-u;i>10&&(null==(r=window.avatarSDKLogger)||r.warn(e.TAG,"[PCMCapture] WebCodecs 编码耗时过长: "+i.toFixed(2)+"ms"))}else s=1})}return function(){if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder)return Promise.resolve(e.mediaRecorderEncoder.feedPCM(n)).then(function(t){var n;if(d=t,c!==e.pcmEncodeId)return null==(n=window.avatarSDKLogger)||n.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"),void(s=1);if(d){var r,i=performance.now()-u;i>10&&(null==(r=window.avatarSDKLogger)||r.warn(e.TAG,"[PCMCapture] MediaRecorder 编码耗时过长: "+i.toFixed(2)+"ms"))}else s=1})}()}();return f&&f.then?f.then(t):t(f)}}else r.resetCaptureBuffer()}},function(t){var n;null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}))}catch(t){return Promise.reject(t)}})).then(function(){var t;null==(t=window.avatarSDKLogger)||t.log(e.TAG,"[PCMCapture] PCM 捕获初始化成功,编码路径: "+e.pcmCaptureMode)})}var i=t?(e.pcmWebMEncoder=new PcmWebMEncoder,Promise.resolve(e.pcmWebMEncoder.init()).then(function(){e.pcmCaptureMode="webcodec"})):(e.mediaRecorderEncoder=new MediaRecorderEncoder,Promise.resolve(e.mediaRecorderEncoder.init()).then(function(){e.pcmCaptureMode="mediarecorder"}));return i&&i.then?i.then(n):n()},function(t){var n,r,i;null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(r=e.pcmWebMEncoder)||r.destroy(),e.pcmWebMEncoder=null,null==(i=e.mediaRecorderEncoder)||i.destroy(),e.mediaRecorderEncoder=null,e.pcmCaptureMode="none"});return s&&s.then?s.then(function(){}):void 0}):(null==(n=window.avatarSDKLogger)||n.error(e.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.visibilitychange=function(){if(document.hidden){var t,e,n,r=null==(t=this.renderScheduler)?void 0:t.getRenderState();r===RenderState.rendering||r===RenderState.resumed?null==(e=this.renderScheduler)||e.pauseRender():null==(n=this.renderScheduler)||n.pauseForBackground()}else{var i,s,a,o;if((null==(i=this.renderScheduler)?void 0:i.getRenderState())===RenderState.paused)null==(o=this.renderScheduler)||o.resumeRender();else if(null!=(s=this.ttsa)&&s.getStatus()){var l;null==(l=this.renderScheduler)||l.forceSyncDecoder()}null!=(a=this.ttsa)&&a.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode()),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(function(){})}},e.setReplayData=function(t){this.replayData=t},e.handleReplaySend=function(t){if(this.replayData)for(var e,n=this.replayData.filter(function(e){return Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type}),r=_createForOfIteratorHelperLoose(n);!(e=r()).done;){var i,s=e.value;"state_change"===s.event_type?null==(i=this.ttsa)||i.stateChange(s.event_data.state,s.event_data.params):"send_text"===s.event_type?this.speak(s.event_data.ssml,s.event_data.is_start,s.event_data.is_end,s.event_data.extra):window.avatarSDKLogger.log(this.TAG,"[handleReplaySend] 未知事件类型: "+s)}},e.connectTtsa=function(t){var e=this;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:function(){var n,r,i,s,a,o;null==(n=e.ttsa)||n.sendSdkPoint("connect_sdk",{timestamp:e.startConnectTime}),null==(r=e.ttsa)||r.sendSdkPoint("connect_sdk_success",{timestamp:e.connectSuccessTime}),null==(i=e.ttsa)||i.sendSdkPoint("session_processing_time",{timestamp:e.sessionResTime}),null==(s=e.ttsa)||s.sendSdkPoint("Char_bin_download_time",{timestamp:e.charbinResTime}),null==(a=e.ttsa)||a.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),e.onTtsaReady(t),null==(o=e.ttsa)||o.syncTimestamp()},handleMessage:function(t,n){var r;e.isfirstReceive&&t===EFrameDataType.BODY&&(null==(r=e.ttsa)||r.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),e.isfirstReceive=!1),e.renderScheduler.handleData(t,n)},handleAAFrame:function(t){null==e.options.onAAFrameHandle||e.options.onAAFrameHandle(t)},runStartFrameIndex:function(t){e.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:function(t){e.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:function(){e.reloadSuccess()},enterOfflineMode:function(){e.offlineHandle()},reStartSDK:function(){e.reStartSession()},sendVoiceEnd:function(){var t;null==(t=e.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:function(){var t,n;return null!=(t=null==(n=e.renderScheduler)?void 0:n.getCurrentFrameIndex())?t:0}})},e.start=function(){var t;this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online),this.renderScheduler.render(),null==(t=this.ttsa)||t.start()},e.onTtsaReady=function(t){this.start()},e._reload=function(){try{var t=this;return Promise.resolve(t.resourceManager._reload()).then(function(e){var n,r=function(){if(e&&!t.destroyed)return Promise.resolve(t.onSessionReloaded(e)).then(function(){if(t.destroyed)return n=1,null;t.ttsa=t.connectTtsa(e),t.ttsa._setResumeInfoCallback(t.resourceManager._getSessionId(),t.renderScheduler._getResumeInfo.bind(t.renderScheduler))})}();return r&&r.then?r.then(function(t){return n?t:e}):n?r:e})}catch(t){return Promise.reject(t)}},e.onSessionReloaded=function(t){return Promise.resolve()},e.onSessionReloadExhausted=function(t){},e.restartSessionForTransport=function(t){try{var e=this;return e.renderScheduler.interrupt("in_offline_mode"),Promise.resolve(e.resourceManager.stopSession(t)).then(function(){var t;e.destroyed||(null==(t=e.ttsa)||t.close(),e.status!==AvatarStatus.offline&&e.offlineHandle(),e.reStartSession())})}catch(t){return Promise.reject(t)}},e.cancelSessionRestart=function(){this.resetRetryState(),this.clearAllRetryTimers()},e.reloadSuccess=function(){var t,e=this;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(function(){window.clearInterval(e._offlineTimer)},1e3)},e.stop=function(){try{return Promise.resolve(this.renderScheduler.stop()).then(function(){})}catch(t){return Promise.reject(t)}},e.isDestroyed=function(){return this.destroyed},e.destroyClient=function(){try{var t,e,n,r=this;if(r.destroyed)return window.avatarSDKLogger.warn(r.TAG,"SDK 已销毁,忽略重复销毁请求"),Promise.resolve();if(r.destroyed=!0,r._isClientMode)return r._streamingClient&&(r._streamingClient.destroy(),r._streamingClient=null),r._videoPlayer&&(r._videoPlayer.destroy(),r._videoPlayer=null),r._eventDispatcher=null,r._apiForwarder=null,r.el=null,window.removeEventListener("beforeunload",r.handleBeforeUnload),window.avatarSDKLogger.log(r.TAG,"薄客户端 SDK 已销毁"),Promise.resolve();if(r.cancelSessionRestart(),-1!==r._offlineTimer&&(clearInterval(r._offlineTimer),r._offlineTimer=-1),r.ttsa&&(r.ttsa.close(),r.ttsa=null),r.renderScheduler&&r.renderScheduler.destroy(),r.resourceManager&&r.resourceManager.destroy(),r.debugOverlay&&(r.debugOverlay.destroy(),r.debugOverlay=null),r.networkMonitor)try{r.networkMonitor.destroy(),r.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(r.TAG,"销毁 networkMonitor 时出错",t)}if(r.pcmEncodeId++,r.captureGeneration++,r.restartPlaybackCaptureImpl=null,r.captureWorklet){try{r.captureWorklet.port.onmessage=null,r.captureWorklet.disconnect()}catch(t){}r.captureWorklet=null}if(r.captureSource){try{r.captureSource.disconnect()}catch(t){}r.captureSource=null}if(r.captureAudioCtx){try{r.captureAudioCtx.close()}catch(t){}r.captureAudioCtx=null}var i=null==(t=r.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();return i&&i.detachCapture(),null==(e=r.pcmWebMEncoder)||e.destroy(),r.pcmWebMEncoder=null,null==(n=r.mediaRecorderEncoder)||n.destroy(),r.mediaRecorderEncoder=null,r.pcmCaptureLastSpeechId=-2,r.pcmCaptureFirstChunk=!0,r.pcmCaptureMode="none",r.el=null,r.startConnectTime=0,r.connectSuccessTime=0,r.sessionResTime=0,r.charbinResTime=0,r.isfirstReceive=!0,r.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",r.handleBeforeUnload),document.removeEventListener("visibilitychange",r.boundVisibilityChange),window.avatarSDKLogger.log(r.TAG,"SDK 已销毁"),Promise.resolve()}catch(t){return Promise.reject(t)}},e.destroy=function(t){void 0===t&&(t="user");try{var e,n=function(n){var i;return e?n:(null==(i=r.ttsa)||i.sendSdkPoint("close_session",{reason:t}),Promise.resolve(r.resourceManager.stopSession(t)).then(function(t){return Promise.resolve(r.destroyClient()).then(function(){return t&&r.onStatusChange(AvatarStatus.close),t})}))},r=this;r.replayData=null;var i=function(){var n;if(r._isClientMode)return null==(n=r._apiForwarder)||n.destroy(t),Promise.resolve(r.destroyClient()).then(function(){r.onStatusChange(AvatarStatus.close),e=1})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(t){return Promise.reject(t)}},e.idle=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())},e.listen=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())},e.think=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())},e.interactiveidle=function(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())},e.speak=function(t,e,n,r){var i,s,a,o;if(void 0===e&&(e=!0),void 0===n&&(n=!0),void 0===r&&(r={client_speak_id:"",client_frame:0}),!this._isClientMode){this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),r.client_frame=null!=(i=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?i:0;var l=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,r);return this.renderScheduler.resume(),l}null==(o=this._apiForwarder)||o.speak(t,e,n,r)},e.setOffsetFrame=function(t){this.renderScheduler.setOffsetFrame(t)},e.syncTimestamp=function(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)},e.notifyEnterInvisibleMode=function(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()},e.notifyExitInvisibleMode=function(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()},e.setVolume=function(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)},e.getSessionId=function(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id},e.showDebugInfo=function(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())},e.hideDebugInfo=function(){var t;null==(t=this.debugOverlay)||t.hide()},e.changeAvatarVisible=function(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)},e.cleanupBeforeInitComplete=function(t){var e,n=this,r=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,"清理初始化未完成的资源,原因: "+t),this.isInitialized=!1;var i=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==i||i.catch(function(t){window.avatarSDKLogger.warn(r.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=function(){try{var t=_catch(function(){return Promise.resolve(i).then(function(){return Promise.resolve(n.destroyClient()).then(function(){})})},function(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(t){return Promise.reject(t)}}(),this.incompleteInitializationCleanupPromise},e.reportInitializationFailure=function(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e:e})},e.offlineHandle=function(){var t=this;this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(function(){if(t.status!==AvatarStatus.offline)return clearInterval(t._offlineTimer),void(t._offlineTimer=-1);t.renderScheduler._offlineRun()},this._offlineInterval)},e.stopSessionFromSocket=function(t){try{return Promise.resolve(this.resourceManager.stopSession(t)).then(function(){})}catch(t){return Promise.reject(t)}},e.offlineMode=function(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()},e.onlineMode=function(){NetworkMonitor.ONLINE&&this._reload()},e.onMessage=function(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(r){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",r)}var r=Errors(t);t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&this.options.onMessage(r),null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(r)},e.onStatusChange=function(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))},e.switchInvisibleMode=function(){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 未初始化,无法切换隐身模式")},e.setInvisibleMode=function(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)},e.getPendingInvisibleMode=function(){return this.pendingInvisibleMode||!1},e.getRenderState=function(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init},e.changeLayout=function(t){var e;if(this._isClientMode){var n;null==(n=this._apiForwarder)||n.changeLayout(t)}else{var r=(t.avatar||{}).scale;t.avatar.scale=validateScaleWithDecimal(void 0===r?1:r,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}},e.changeWalkConfig=function(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))},e.interrupt=function(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)},e.triggerReconnect=function(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()},e.reStartSession=function(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())},e._retryImpl=function(){try{var t=this;if(t.retryRound>t.maxRetryRound||!t.isRetrying)return Promise.resolve();var e=1e3;return t.retryCount>1&&(e=1e3*Math.pow(2,t.retryCount)),t.retryTimer=window.setTimeout(function(){try{return t.retryTimer=-1,!t.isRetrying||t.destroyed?Promise.resolve():Promise.resolve(_catch(function(){return Promise.resolve(t._reload()).then(function(e){if(t.isRetrying&&!t.destroyed)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()})},function(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()}))}catch(t){return Promise.reject(t)}},e),Promise.resolve()}catch(t){return Promise.reject(t)}},e.clearAllRetryTimers=function(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)},e.resetRetryState=function(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1},e.seekToFrame=function(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)},e.startRecoder=function(){try{var t=this;try{var e,n,r=null==(e=t.el)?void 0:e.querySelector("canvas"),i=null==(n=t.el)?void 0:n.querySelector("audio");if(!r||!i)return console.error("找不到 canvas 或 audio 元素"),Promise.resolve();var s=r.captureStream(60),a=[];if(t.captureSource&&t.captureAudioCtx){var o=t.captureAudioCtx.createMediaStreamDestination();t.captureSource.connect(o),a=o.stream.getAudioTracks()}else if("function"==typeof i.captureStream)a=i.captureStream().getAudioTracks();else{if("function"!=typeof i.mozCaptureStream)return window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频"),Promise.resolve();a=i.mozCaptureStream().getAudioTracks()}t.stream=new MediaStream([].concat(s.getVideoTracks(),a)),t.recordedChunks=[],t.mediaRecorder=new MediaRecorder(t.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),t.mediaRecorder.ondataavailable=function(e){e.data&&e.data.size>0&&t.recordedChunks.push(e.data)},t.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}return Promise.resolve()}catch(t){return Promise.reject(t)}},e.stopRecoder=function(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(function(t){return t.stop()}),window.avatarSDKLogger.log("⏹ 停止录制"))},e.exportVideo=function(){if(this.recordedChunks.length){var 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)}else window.avatarSDKLogger.error("没有录制到数据")},e.getOptions=function(){return this.options},e.simulateContextLoss=function(t,e){void 0===t&&(t=5e3),void 0===e&&(e=!1),this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")},e.getRecoveryStatus=function(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null},e.testStagedRecovery=function(){try{return this.renderScheduler?Promise.resolve(this.renderScheduler.testStagedRecovery()):(window.avatarSDKLogger.warn("[Test] renderScheduler not initialized"),Promise.resolve())}catch(t){return Promise.reject(t)}},e.restartWebGL=function(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)},_createClass(t,[{key:"businessENV",get:function(){return this._env}}])}();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,module.exports=XmovAvatar;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|