trtc-sdk-v5 5.14.0-wasm.2 → 5.14.0-wasm.4
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/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -89,13 +89,13 @@ return ret;
|
|
|
89
89
|
`,G=0;G<S-1;++G)w[G+1].deleteObject&&(he+=" argType"+G+".deleteObject(arg"+G+`);
|
|
90
90
|
`);P.isVoid||(he+=` return retType.toWireType(destructors, rv);
|
|
91
91
|
`),he+=`};
|
|
92
|
-
`,q.push(he);var Ce,fe,Me=Oc(Function,q).apply(null,Q);return Ce=Me,fe=ks.length,ks.push(Ce),W=fe,Ls[B]=W,W},f:()=>{fr("")},c:qn,t:(S,T,w)=>D.copyWithin(S,T,T+w),s:S=>{D.length,fr("OOM")},i:(S,T,w,P)=>{for(var B,W,q,Q=0,te=0;te<w;te++){var G=Se[T>>2],he=Se[T+4>>2];T+=8;for(var we=0;we<he;we++)B=S,W=D[G+we],q=void 0,q=$c[B],W===0||W===10?((B===1?g:E)(Vo(q,0)),q.length=0):q.push(W);Q+=he}return Se[P>>2]=Q,0}},wr=(function(){var S,T,w,P,B={a:Bc};function W(q,Q){var te,G,he=q.exports;return A=(C=he).v,te=A.buffer,o.HEAP8=N=new Int8Array(te),o.HEAP16=x=new Int16Array(te),o.HEAP32=de=new Int32Array(te),o.HEAPU8=D=new Uint8Array(te),o.HEAPU16=Y=new Uint16Array(te),o.HEAPU32=Se=new Uint32Array(te),o.HEAPF32=Ze=new Float32Array(te),o.HEAPF64=H=new Float64Array(te),ke=C.z,G=C.w,Fn.unshift(G),function(){if(qr--,o.monitorRunDependencies&&o.monitorRunDependencies(qr),qr==0&&(Ds!==null&&(clearInterval(Ds),Ds=null),Hi)){var we=Hi;Hi=null,we()}}(),he}if(qr++,o.monitorRunDependencies&&o.monitorRunDependencies(qr),o.instantiateWasm)try{return o.instantiateWasm(B,W)}catch(q){E("Module.instantiateWasm callback failed with error: "+q),r(q)}(S=p,T=li,w=B,P=function(q){W(q.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||re(T)||typeof fetch!="function"?zr(T,w,P):fetch(T,{credentials:"same-origin"}).then(q=>WebAssembly.instantiateStreaming(q,w).then(P,function(Q){return E("wasm streaming compile failed: "+Q),E("falling back to ArrayBuffer instantiation"),zr(T,w,P)}))).catch(r)}(),S=>(wr=C.x)(S)),Zi=S=>(Zi=C.y)(S),Us=S=>(Us=C.A)(S),Hc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=C.B)(),S=>(Hc=C.C)(S));o.dynCall_jiji=(S,T,w,P,B)=>(o.dynCall_jiji=C.D)(S,T,w,P,B);function Wc(){function S(){Gt||(Gt=!0,o.calledRun=!0,Un||(hi(Fn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),$n.unshift(T);var T;hi($n)}()))}qr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),Vn.unshift(T);var T;hi(Vn)}(),qr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Hi=function S(){Gt||Wc(),Gt||(Hi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Wc(),t.ready}})();var Gy="web.sdk.qcloud.com",jy=`https://${Gy}/trtc/webrtc/v5/doc`,RP=`${jy}/zh-cn/`,CE=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(CE||{});var NE={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},vP=NE["480p_2"],CP=NE["120p_2"],Vu={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},NP=Vu.MAIN,DP=Vu.AUXILIARY,wP=Vu.BIG,MP=Vu.SMALL;var OP=Object.keys(CE);var qy=function(i,t,e,r){return new(e||(e=Promise))(function(o,s){function n(m){try{u(r.next(m))}catch(p){s(p)}}function a(m){try{u(r.throw(m))}catch(p){s(p)}}function u(m){var p;m.done?o(m.value):(p=m.value,p instanceof e?p:new e(function(g){g(p)})).then(n,a)}u((r=r.apply(i,t||[])).next())})},hp=Symbol(32),pp=Symbol(16),fp=Symbol(8),lp=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,t){return t&&this.consume(),this.need=i,this.flush()}read(i){return qy(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,e)=>{var r;this.reject=e,this.resolve=o=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(o)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(hp)}readU16(){return this.read(pp)}readU8(){return this.read(fp)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,t=this.buffer.subarray(this.consumed),e=0,r=o=>t.length<(e=o);if(typeof this.need=="number"){if(r(this.need))return;i=t.subarray(0,e)}else if(this.need===hp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===pp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===fp){if(r(1))return;i=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,e)),i=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,e)),i=this.need}return this.consumed+=e,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,255&i]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,255&i]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let t=this.buffer.length,e=t+i;if(e<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,e);else{let r=new Uint8Array(e);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,e)}return this.buffer=new Uint8Array(i),this.buffer}};lp.U32=hp,lp.U16=pp,lp.U8=fp;var zy=127,xP=~zy,PP=Math.pow(2,31),kP=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},LP=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function AE(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:UP}=Object.prototype,DE=class wE{constructor(t){this.core=t,jr(this,"contextMap",new Map),jr(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return wE.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new Wy(ku(Pu({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new wn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(ku(Pu({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=AE()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(ku(Pu({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:a,endTime:u})=>{a>e.startPerformanceTime&&(s+=u===0?AE()-a:u-a)});let n=0;return o&&o.durationItemList.forEach(a=>{a.startTime>e.startPerformanceTime&&(n+=a.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};jr(DE,"Name","TRTCVideoDecoder");var gp=DE;var s_=Ei(vi());function Ep({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Oe((r,o)=>{let s=new WeakMap;return U.on($.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new ce({code:j.INVALID_OPERATION,message:Be({key:$e.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var Jy="2025-10-29 16:47:28",ME=!0,OE=function(){var i;if(ME){ME=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Yr}/en/index.html`),console.info(`* Changelog: ${Yr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",lt),Fr||F.debug("Build Time:",Jy);let t=`UA: ${navigator.userAgent}
|
|
92
|
+
`,q.push(he);var Ce,fe,Me=Oc(Function,q).apply(null,Q);return Ce=Me,fe=ks.length,ks.push(Ce),W=fe,Ls[B]=W,W},f:()=>{fr("")},c:qn,t:(S,T,w)=>D.copyWithin(S,T,T+w),s:S=>{D.length,fr("OOM")},i:(S,T,w,P)=>{for(var B,W,q,Q=0,te=0;te<w;te++){var G=Se[T>>2],he=Se[T+4>>2];T+=8;for(var we=0;we<he;we++)B=S,W=D[G+we],q=void 0,q=$c[B],W===0||W===10?((B===1?g:E)(Vo(q,0)),q.length=0):q.push(W);Q+=he}return Se[P>>2]=Q,0}},wr=(function(){var S,T,w,P,B={a:Bc};function W(q,Q){var te,G,he=q.exports;return A=(C=he).v,te=A.buffer,o.HEAP8=N=new Int8Array(te),o.HEAP16=x=new Int16Array(te),o.HEAP32=de=new Int32Array(te),o.HEAPU8=D=new Uint8Array(te),o.HEAPU16=Y=new Uint16Array(te),o.HEAPU32=Se=new Uint32Array(te),o.HEAPF32=Ze=new Float32Array(te),o.HEAPF64=H=new Float64Array(te),ke=C.z,G=C.w,Fn.unshift(G),function(){if(qr--,o.monitorRunDependencies&&o.monitorRunDependencies(qr),qr==0&&(Ds!==null&&(clearInterval(Ds),Ds=null),Hi)){var we=Hi;Hi=null,we()}}(),he}if(qr++,o.monitorRunDependencies&&o.monitorRunDependencies(qr),o.instantiateWasm)try{return o.instantiateWasm(B,W)}catch(q){E("Module.instantiateWasm callback failed with error: "+q),r(q)}(S=p,T=li,w=B,P=function(q){W(q.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||re(T)||typeof fetch!="function"?zr(T,w,P):fetch(T,{credentials:"same-origin"}).then(q=>WebAssembly.instantiateStreaming(q,w).then(P,function(Q){return E("wasm streaming compile failed: "+Q),E("falling back to ArrayBuffer instantiation"),zr(T,w,P)}))).catch(r)}(),S=>(wr=C.x)(S)),Zi=S=>(Zi=C.y)(S),Us=S=>(Us=C.A)(S),Hc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=C.B)(),S=>(Hc=C.C)(S));o.dynCall_jiji=(S,T,w,P,B)=>(o.dynCall_jiji=C.D)(S,T,w,P,B);function Wc(){function S(){Gt||(Gt=!0,o.calledRun=!0,Un||(hi(Fn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),$n.unshift(T);var T;hi($n)}()))}qr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),Vn.unshift(T);var T;hi(Vn)}(),qr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Hi=function S(){Gt||Wc(),Gt||(Hi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Wc(),t.ready}})();var Gy="web.sdk.qcloud.com",jy=`https://${Gy}/trtc/webrtc/v5/doc`,RP=`${jy}/zh-cn/`,CE=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(CE||{});var NE={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},vP=NE["480p_2"],CP=NE["120p_2"],Vu={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},NP=Vu.MAIN,DP=Vu.AUXILIARY,wP=Vu.BIG,MP=Vu.SMALL;var OP=Object.keys(CE);var qy=function(i,t,e,r){return new(e||(e=Promise))(function(o,s){function n(m){try{u(r.next(m))}catch(p){s(p)}}function a(m){try{u(r.throw(m))}catch(p){s(p)}}function u(m){var p;m.done?o(m.value):(p=m.value,p instanceof e?p:new e(function(g){g(p)})).then(n,a)}u((r=r.apply(i,t||[])).next())})},hp=Symbol(32),pp=Symbol(16),fp=Symbol(8),lp=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,t){return t&&this.consume(),this.need=i,this.flush()}read(i){return qy(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,e)=>{var r;this.reject=e,this.resolve=o=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(o)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(hp)}readU16(){return this.read(pp)}readU8(){return this.read(fp)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,t=this.buffer.subarray(this.consumed),e=0,r=o=>t.length<(e=o);if(typeof this.need=="number"){if(r(this.need))return;i=t.subarray(0,e)}else if(this.need===hp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===pp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===fp){if(r(1))return;i=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,e)),i=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,e)),i=this.need}return this.consumed+=e,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,255&i]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,255&i]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let t=this.buffer.length,e=t+i;if(e<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,e);else{let r=new Uint8Array(e);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,e)}return this.buffer=new Uint8Array(i),this.buffer}};lp.U32=hp,lp.U16=pp,lp.U8=fp;var zy=127,xP=~zy,PP=Math.pow(2,31),kP=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},LP=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function AE(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:UP}=Object.prototype,DE=class wE{constructor(t){this.core=t,jr(this,"contextMap",new Map),jr(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return wE.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new Wy(ku(Pu({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new wn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(ku(Pu({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=AE()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(ku(Pu({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:a,endTime:u})=>{a>e.startPerformanceTime&&(s+=u===0?AE()-a:u-a)});let n=0;return o&&o.durationItemList.forEach(a=>{a.startTime>e.startPerformanceTime&&(n+=a.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};jr(DE,"Name","TRTCVideoDecoder");var gp=DE;var s_=Ei(vi());function Ep({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Oe((r,o)=>{let s=new WeakMap;return U.on($.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new ce({code:j.INVALID_OPERATION,message:Be({key:$e.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var Jy="2025-10-29 17:36:02",ME=!0,OE=function(){var i;if(ME){ME=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Yr}/en/index.html`),console.info(`* Changelog: ${Yr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",lt),Fr||F.debug("Build Time:",Jy);let t=`UA: ${navigator.userAgent}
|
|
93
93
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Em()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),F.info(t),F.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Zo().then(r=>{r&&F.info(Lr)})}};var As={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var oe={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},pr=(k=>(k[k.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",k[k.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",k[k.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",k[k.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",k[k.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",k[k.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",k[k.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",k[k.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",k[k.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",k[k.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",k[k.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",k[k.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",k[k.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",k[k.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",k[k.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",k[k.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",k[k.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",k[k.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",k[k.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",k[k.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",k[k.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",k[k.INVALID_OPERATION=5100]="INVALID_OPERATION",k[k.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",k[k.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",k[k.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",k[k.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",k[k.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",k[k.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",k[k.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",k[k.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",k[k.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",k[k.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",k[k.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",k[k.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",k[k.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",k[k.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",k[k.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",k[k.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",k[k.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",k[k.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",k[k.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",k[k.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",k[k.DEVICE_ERROR=5300]="DEVICE_ERROR",k[k.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",k[k.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",k[k.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",k[k.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",k[k.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",k[k.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",k[k.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",k[k.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",k[k.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",k[k.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",k[k.SERVER_ERROR=5400]="SERVER_ERROR",k[k.NEED_TO_BUY=5401]="NEED_TO_BUY",k[k.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",k[k.OPERATION_FAILED=5500]="OPERATION_FAILED",k[k.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",k[k.REJOIN_FAILED=5502]="REJOIN_FAILED",k[k.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",k[k.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",k[k.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",k[k.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",k[k.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",k[k.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",k[k.OPERATION_ABORT=5998]="OPERATION_ABORT",k[k.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",k))(pr||{});function PE({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=pr[i];try{o=xE[s]}catch(n){o=xE.UNKNOWN_ERROR}return qe(o)?r=o(t):De(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var xE=ge(J({},rr),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${mt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:i}){return`The type of target roomId must match the current roomId. Current room is using '${i}', but received '${i==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:i}){return`the target '${i}' must not be the same as the current '${i}'.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=bs(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function bs(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var _p=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:a,data:u}){var p;let m;o?m=o:m=PE({code:e===oe.SERVER_ERROR?e:r||e,params:J({fnName:n,error:a},s)});super(m);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"data");l(this,"handler");l(this,"originError");this.name=pr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=a,this.message=m,this.data=u,this.extraCode===5302&&((p=this.originError)!=null&&p.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},E={startLocalVideo:"webcam",startLocalAudio:"microphone"},A=document.createElement("a");Yo?A.href=`ms-settings:privacy-${E[this.functionName]}`:Vr&&(A.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),A.href.length>0&&A.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ce){let{stack:n}=e,a={code:oe.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case j.INVALID_PARAMETER:a.code=oe.INVALID_PARAMETER,a.message=e.message;break;case j.INVALID_OPERATION:a.code=oe.INVALID_OPERATION;break;case j.NOT_SUPPORTED:case j.NOT_SUPPORTED_H264:a.code=oe.ENV_NOT_SUPPORTED,e.getCode()===j.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(rr.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case j.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case j.SERVER_TIMEOUT:case j.SWITCH_ROLE_FAILED:case j.SWITCH_ROOM_FAILED:a.code=oe.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case j.API_CALL_ABORTED:a.code=oe.OPERATION_ABORT;break;case j.DEVICE_NOT_FOUND:case j.DEVICE_AUTO_RECOVER_FAILED:case j.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=Xy(e.name));break;case j.VIDEO_ENCODE_FAILED:a.extraCode=5505;case j.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=oe.OPERATION_FAILED;break;case j.UNKNOWN:break;default:a.code=oe.OPERATION_FAILED}s=new i(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
94
94
|
`)))}else{if(e instanceof i)return e;s=new i({code:oe.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function Xy(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var ie=_p;function ci(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function uc(i){return i===As.QOS_PREFERENCE_CLEAR?"detail":i===As.QOS_PREFERENCE_SMOOTH?"motion":""}function Mn(i,t){let e=t?Ul:ta;return om(i)?J(J({},e),i):xr[i]?xr[i]:e}var kE={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},LE={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},On={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(De(i)&&!document.getElementById(i))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},UE={name:"userId",required:!0,type:"string"},VE={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function xn(i,t){if(!i)throw new ie({code:oe.INVALID_OPERATION,extraCode:5101,fnName:t})}function FE(i,t,e){if(!i)throw new ie({code:oe.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function $E(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function BE(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var aL={type:"number",notLessThanZero:!0},Qy=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function HE(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!Xd()){F.warn("small stream is not supported"),delete i.option.small;return}let t=Mn(i.option.profile),e=Mn(i.option.small,!0);if(!Qy(t,e)){F.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(t)}, Small: ${JSON.stringify(e)}`),delete i.option.small;return}}var Yy={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new ie({code:oe.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(De(i.roomId))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});$E(i.roomId,e,t)}else if(i.strRoomId)BE(i.strRoomId,e,t);else throw new ie({code:oe.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:On,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:kE},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Oi())throw new ie({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&HE(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ge(J({},On),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:kE},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&HE(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:VE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Oi())throw new ie({code:oe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:VE}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:On,publish:{type:"boolean"},option:LE},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(Oi())throw new ie({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});if(!Pa())throw new ie({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:On,publish:{type:"boolean"},option:LE}},muteRemoteAudio:[UE,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[UE,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:On,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){xn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(FE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ie({code:oe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ge(J({},On),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){xn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(FE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ie({code:oe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&O(i.streamType))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){xn(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!La)throw new ie({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ie({code:oe.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});xn(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new ie({code:oe.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(xn(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ie({code:oe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(xn(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new ie({code:oe.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId&&this._room.useStringRoomId||!i.roomId&&i.strRoomId&&!this._room.useStringRoomId)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)$E(i.roomId,e,t);else if(i.strRoomId)BE(i.strRoomId,e,t);else throw new ie({code:oe.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Nt={TRTC:Yy};var Jt=class extends Error{};function Zy(i,t){let e=Go(i);for(let r=0;r<t.length;r++)kr(e[r],t[r]);return e}function Ky(i){this._resolve=Promise.resolve(i)}function eA(i){this._reject=Promise.reject(i)}var yo=class yo{constructor(t,e){this.instance=t;this.group=e;l(this,"started",!1);l(this,"ops",[]);l(this,"startSame",()=>!0);l(this,"mergeUpdate",Zy);let r=yo.instances.get(t);r?r.set(e,this):yo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=yo.instances.get(t);return r&&r.get(e)||new yo(t,e)}static gets(t,e){let r=yo.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=a=>{var u;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(u=this.currentOp)==null||u.action(),a},s=a=>{var u,m;throw this.ops.shift(),t===0&&((u=this.currentOp)==null?void 0:u.type)===2&&this.ops.shift().reject(new Jt("start failed")),(m=this.currentOp)==null||m.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:Ky,reject:eA};try{switch(this.state){case 1:if(t===0)throw new Jt("already started");break;case 4:if(t===2)throw new Jt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Jt("already start");break;case 3:switch(t.type){case 2:throw new Jt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Jt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Jt("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Jt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Jt("start not allowed after update");case 0:throw new Jt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Jt("keep start")),new Jt("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};l(yo,"instances",new WeakMap);var Fi=yo;var $u=new WeakMap,Bu=(i,t)=>{if(t instanceof Jt){let{stack:e}=t;t=new ie({code:oe.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
95
95
|
`)))}throw t};function Ao(i,t){return Oe((e,r)=>function(...o){let s=Fi.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Bu.bind(null,r))):e.apply(this,o)})}function Rs(i,t){let{merge:e,debounce:r}=t||{};return Oe((o,s)=>function(...n){let a=Fi.get(this,typeof i=="string"?i:i.call(this,...n));if(!a)return o.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:u,getKey:m}=r;return new Promise((p,g)=>{var C,N;let E=(C=$u.get(this))==null?void 0:C.get(m(...n));if(E){let{timeoutId:D,resolve:x}=E;clearTimeout(D),x()}let A=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(Bu.bind(null,s)).then(p,g)},u);$u.has(this)?(N=$u.get(this))==null||N.set(m(...n),{timeoutId:A,resolve:p}):$u.set(this,new Map([[m(...n),{timeoutId:A,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(Bu.bind(null,s))})}function bo(i){return Oe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Fi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Fi.get(this,o);return s?s.action(3,t.bind(this),r).catch(Bu.bind(null,e)):t.apply(this,r)})}var Z={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},WE=new Set([Z.ERROR,Z.AUTOPLAY_FAILED,Z.KICKED_OUT,Z.REMOTE_USER_ENTER,Z.REMOTE_USER_EXIT,Z.REMOTE_AUDIO_AVAILABLE,Z.REMOTE_AUDIO_UNAVAILABLE,Z.REMOTE_VIDEO_AVAILABLE,Z.REMOTE_VIDEO_UNAVAILABLE,Z.CONNECTION_STATE_CHANGED,Z.PUBLISH_STATE_CHANGED,Z.SCREEN_SHARE_STOPPED,Z.DEVICE_CHANGED,Z.FIRST_VIDEO_FRAME,Z.PERMISSION_STATE_CHANGE,Z.VIDEO_SIZE_CHANGED]);var Sp={};gi(Sp,{ScheduleRequestType:()=>jE,getAbilityConfig:()=>rA,getScheduleDomain:()=>Gu,isNeedToSchedule:()=>Hu,scheduleProxy:()=>di,sendScheduleRequest:()=>Ip,setIsNeedToSchedule:()=>vs,setScheduleProxy:()=>Wu});var Tp=null,Hu=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ii).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
96
96
|
`));function vs(i){Ye(i)&&i!==Hu&&(Hu=i,F.info(`setIsNeedToSchedule ${i}`))}U.on("28",()=>vs(!0));U.on("63",()=>vs(!0));U.on("84",()=>vs(!0));U.on("201",i=>{i.state==="RECONNECTING"&&vs(!0)});U.on("202",i=>{i.state==="RECONNECTING"&&vs(!0)});function tA(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=Ro(i,"config",M.MAIN),n=Ro(i,"config",M.BACKUP);for(let a of o)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let u=a.name===s?M.MAIN:M.BACKUP,m=Math.round(a.duration),p=Math.round(a.domainLookupStart-a.startTime),g=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,E=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,A=Math.round(a.domainLookupEnd-a.domainLookupStart),C=Math.round(a.requestStart-a.secureConnectionStart),N=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),x=Math.round(a.responseEnd-a.responseStart),Y=[A,C,N,D,x];Ge.uploadEvent({log:`stat-schedule-net:${m}(${p}(${g}->${E})->${Y.join("->")}) ${u}`,userId:t}),r=ge(J({},r),{totalCost:m,local:p,dns:A,tcp:N,tls:C,request:D,response:x});break}}catch(o){F.error("getScheduleDetailCost error",o)}return r}function Ip(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:a,latencyLevel:u}){var g;if(!Hu&&Tp)return{isCached:!0,result:Tp};let p={delta:0,count:[1,1],msg:[],detail:[]};try{let E=new FormData;E.append("userId",String(i)),E.append("sdkAppId",String(t)),E.append("isStrGroupId",String(e)),E.append("groupId",String(r)),E.append("sdkVersion",s),E.append("userSig",String(o));let A=((g=yield Zo())==null?void 0:g.model)||Od();A&&E.append("model",A),a&&E.append("role",String(a)),u&&E.append("latencyLevel",String(u)),n&&E.append("frameWorkType",String(n));let C=Ee(),N=yield oA(E,p,t);N.config&&(N.config.loggerDomain&&$o(N.config.loggerDomain),Ye(N.config.scheduleCache)&&vs(!N.config.scheduleCache)),p.delta=Ee()-C;let D=tA(Number(t),i,C);return Tp=N,{isCached:!1,result:N,detailCost:D}}catch(E){let A=ct(E)?E[0]:E,C=Le(A.code)?A.code:0,N=`schedule failed${A.message?`: ${A.message}`:""}`,D=new ce({code:j.SCHEDULE_FAILED,extraCode:C,message:Be({key:$e.JOIN_ROOM_FAILED,data:{error:N,code:C}})});throw F.error(N,C),D}})}var di={main:"",backup:""};function Wu(i){ct(i)?(di.main=i[0],di.backup=i[1]):di.main=i}var jE=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(jE||{});function Ro(i,t,e=M.MAIN,r=!1){return`https://${di[e]||Gu(i,e,r)}/api/v1/${t}`}function rA(i,t,e){let r=Ro(i,t),o=Ro(i,t,M.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(u=>u.json()),a=fetch(`${o}?${s}`).then(u=>u.json());return ca([n,a])}function Gu(i,t=M.MAIN,e=!1){let r;return Ir(i)?e?r=t===M.MAIN?Ii.MAIN_OVERSEA_BACKUP:Ii.BACKUP_OVERSEA:r=t===M.MAIN?Ii.MAIN_OVERSEA:Ii.BACKUP_OVERSEA:r=t===M.MAIN?Ii.MAIN:Ii.BACKUP,r}function iA(i,t,e){return new Promise((r,o)=>{Ai({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var GE=(i,t)=>so({retryFunction:iA,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function oA(i,t,e){return new Promise((r,o)=>{let s=null;ca([GE(n=>t.count[0]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(u>=1&&(m[0]=Ro(e,"config",M.MAIN,!0)),a())})(Ro(e,"config",M.MAIN),i,{get timeout(){return jo(2+t.count[0])*1e3}}),GE(n=>t.count[1]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(u>=2&&(m[0]=Ro(e,"config",M.BACKUP,!0)),a())})(Ro(e,"config",M.BACKUP),i,{get timeout(){return jo(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var sA=i=>i.startsWith("data:application/octet-stream;base64,"),nA=i=>i.startsWith("file://"),lc=class{constructor(){l(this,"_log");this._log=F.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=Xo(t);try{let o=Ee(),s;if(qe(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Ee()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),X.addSuccessEvent({key:522700,cost:Ee()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),X.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return y(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok){let s=new Error(`network response was not ok: ${r.status}`);throw s.status=r.status,s}let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)r({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,o(n)}},s.onerror=o,s.send(null)})}loadWasm(t,e){return y(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Ee(),o=null,s=null;if(qe(WebAssembly.instantiateStreaming)&&!sA(t)&&!nA(t)&&qe(fetch))try{let n=fetch(t);o=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!o)try{let n=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(o){let n=Ee()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),X.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),X.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=Ee();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Ee()-e}ms`),X.addSuccessEvent({key:522702,cost:Ee()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),X.addFailedEvent({key:522702}),o(n)},s.crossOrigin="anonymous",s.src=t,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};ee([ds({settings:{timeout:0,retries:3},onError(t,e,r){var o;(t==null?void 0:t.status)===404||(o=t==null?void 0:t.message)!=null&&o.includes("404")?(this._log.warn("download 404, stop retry"),r(t)):e()},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],lc.prototype,"download",1),ee([ds({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],lc.prototype,"loadScript",1);var mc=new lc;function qE({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:Ss,LocalVideoTrack:hr,LocalScreenTrack:ni,room:t,assetsPath:r,fileDownloader:mc,innerEmitter:U,INNER_EVENT:$,constants:Bl,environment:mn,utils:np,eventLogger:Ge,log:this.room.getLogger(),loggerManager:F,errorModule:e,kvStatManager:X,rtcDectection:lo,trtc:this,rx:ip,enums:Um,schedule:Sp,getDevices:In,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>y(this,null,function*(){window.VisionTaskRegistry||(yield mc.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:je(),deviceDetector:st,AudioPlayer:yn,AutoPlayDialog:En,Timer:ht,clearStarted:(o,s)=>{let n=o.getAlias(),a=Fi.instances.get(this);if(a)if(s){let u=a.get(n+s);if(!u)return;u.started=!1}else a.forEach((u,m)=>{m.startsWith(n)&&(u.started=!1)})},startGetPCM:nc,createAudioNode:za,getNetworkTimeOffset:sf,validateSourceNode:()=>{var o;if(dt&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new ie({code:oe.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var zE=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=Be({key:$e.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return F.warn(`${s}
|
|
97
97
|
|
|
98
|
-
${o.stack}`),!1}},i};var Pn=new WeakMap;function JE(i){let t=Pn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Pn.delete(i))}function XE(i,t){return Oe((e,r)=>function(...o){let s=Pn.get(this);s||(s=new Map,Pn.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let u=setTimeout(()=>{var m;(m=Pn.get(this))==null||m.delete(n)},i);s.set(n,u)}else{clearTimeout(a);let u=window.setTimeout(()=>{var m;e.apply(this,o),(m=Pn.get(this))==null||m.delete(n)},i);s.set(n,u)}})}var YE="trtc-sdk-v5",yp="5.14.0-wasm.2";function Ft(...i){return Oe((t,e)=>function(...r){try{qu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Ap(...i){return Oe((t,e)=>function(...r){try{qu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function qu(i,t,e,r){if(ct(i))for(let o=0;o<i.length;o++)ju.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else ju.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function ju({rule:i,value:t,key:e,fnName:r,className:o}){function s(u){return{code:oe.INVALID_PARAMETER,extraCode:u,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new ie(s(5001));if(O(i.defaultValue)){qe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let u=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(u=!0),qe(i.type[m])&&t instanceof i.type[m]&&(u=!0),De(i.type[m])&&mt(t)===i.type[m].toLowerCase()&&(u=!0);if(!u)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>qo(m)?zs(m):De(m)?m:mt(m))},value:t}})}else if(!O(i.type)&&mt(t)!==i.type)throw new ie(s(5002));if(i.allowEmpty===!1){let u=Le(t)&&(t===0||Number.isNaN(t)),m=De(t)&&t.trim()==="";if(u||m)throw new ie(s(5003))}if(i.notLessThanZero&&Le(t)&&t<0)throw new ie(s(5006));if(!O(i.min)&&Le(t)&&t<i.min)throw new ie(s(5007));if(!O(i.max)&&Le(t)&&t>i.max)throw new ie(s(5008));if(De(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ie(s(5004))}else if(qe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ie(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ie(s(5005));let{properties:n}=i;qt(n)&&cr(t)&&Object.keys(n).forEach(u=>{ju.call(this,{rule:n[u],value:t&&t[u],key:`${u}`,fnName:r,className:o})});let{arrayItem:a}=i;qt(a)&&ct(t)&&t.forEach((u,m)=>{ju.call(this,{rule:a,value:u,key:`${e}[${m}]`,fnName:r,className:o})}),qe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function it(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Oe((n,a)=>function(...u){var A,C,N;function m(D,x,Y){if(Y&&Y.includes(D))return"hided";if(e){let de=e(...u);if(u[de.argIndex]===x)return de.value}if(x===u||D in u)return x;try{return x instanceof HTMLElement?`id: ${x.id} type:${mt(x)}`:x instanceof MediaStreamTrack?dd(x):(JSON.stringify(x),x)}catch(de){return`type:${mt(x)}`}}let p=this._log||F;if(o!=null&&o(...u))return n.apply(this,u);u.length>0?p.info(`${a}() ${JSON.stringify(u,(D,x)=>m(D,x,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let g=r?r(...u):Wd[a],E=(s==null?void 0:s(...u))||!1;try{let D=n.apply(this,u),x=Ee();if(io(D)){let Y=`${a.includes("Plugin")?`${((C=(A=u[0]).getName)==null?void 0:C.call(A))||""} `:" "}`;return D.then(de=>(p.info(`${a}() success ${Y}${t.call(this,...u)}`),X.addSuccessEvent({key:g,cost:Ee()-x}),de)).catch(de=>{var H;de=ie.convertFrom.call(this,de,a,u.length===1?u[0]:u);let Se=de.extraCode||de.code,Ze=(H=de.message)!=null&&H.includes(Se)?"":` code:${Se}`;throw E||p.error(`${a}() failed ${Y}${t.call(this,...u)} ${de}${Ze} params: ${JSON.stringify(u,m)}`),X.addFailedEvent({key:g,error:de}),de})}return X.addSuccessEvent({key:g}),D}catch(D){D=ie.convertFrom.call(this,D,a);let x=D.extraCode||D.code,Y=(N=D.message)!=null&&N.includes(x)?"":` code:${x}`;throw E||p.error(`${a}() failed ${D}${Y} params: ${JSON.stringify(u,m)}`),X.addFailedEvent({key:g,error:D}),D}})}var zu=i=>Oe((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ie({code:oe.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(qe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ie({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return qu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Ju=0,bp,$i=class $i{constructor(t){this.core=t;l(this,"log");l(this,"customAudioReferenceMap",new Map);l(this,"audioRefId",0);l(this,"audioContext",je());l(this,"localAudioWorkletNode");l(this,"screenAudioWorkletNode");l(this,"mixNode");l(this,"silentNode");Ju=Ju+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ju}`}),this.log.info(`created id=${this.getAlias()}${Ju}`),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new ie({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return bp||(bp=this.doPreload(t)),bp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Pi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return $i.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return $i.getStartValidateRule(this.core);case"update":return $i.updateValidateRule;case"stop":return $i.stopValidateRule}}start(t){return y(this,null,function*(){var E,A,C,N;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:u,enableDump:m,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:g=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=g,!n)throw new ie({code:oe.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:D,status:x,timestamp:Y}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,Y,D,x,e)}if(g&&!this.screenAudioWorkletNode){let{sign:D,status:x,timestamp:Y}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,Y,D,x,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),O(u)||(C=this.localAudioWorkletNode)==null||C.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),O(m)||(N=this.localAudioWorkletNode)==null||N.port.postMessage({type:"dump",data:{enable:m}})})}update(t){return y(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;O(e)||(this.customAudioReferenceMap.forEach((u,m)=>{this.customAudioReferenceMap.delete(m),this.core.room.audioManager.updateAudioReference({type:"remove",refId:u})}),e.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})})),O(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),O(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return y(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:u}=yield cA({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${u}`),new ie({code:oe.INVALID_PARAMETER,message:u});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,u){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=m=>{var g;let{data:p}=m;switch(p.type){case"cost":let E=(p==null?void 0:p.value)>10?"info":"debug";this.log[E](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Fs(new Date(p==null?void 0:p.maxCostTimestamp))}) hist: ${(g=p==null?void 0:p.hist)==null?void 0:g.join(" ")}`);return;case"log":this.log[p.logLevel](`${e==="localAudio"?"":`[${e}] `}${p.value}`);return;case"dump":U.emit("265",{room:u,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return y(this,null,function*(){var e;if(!(!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return y(this,null,function*(){var e;!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};l($i,"updateValidateRule",{type:"object"}),l($i,"stopValidateRule",{type:"object"}),l($i,"Name","AudioProcessor");var Xu=$i;function aA(i,t=M.MAIN){return`https://${di[t]||Gu(i,t)}/api/v1/audioAiAuth`}function cA(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${aA(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,a=yield fetch(n),{data:{errCode:u,errMsg:m,sign:p,status:g}}=yield a.json();if(g==="1")return{auth:!0,sign:p,status:g,message:m};let E=Ir(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",C="";switch(u){case 1:C="Please check your params.";break;case 2:C=`You need to buy packages. Refer to: ${E}`;break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C=`Your packages is not active. Refer to: ${E}`;break;case 5:C=`Your packages is expired. Refer to: ${E}`;break;case 6:C="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${A} Reason: ${m}. ${C}`:`${A}, ${C}`}})}var Qu=0,Rp=class{constructor(t,e){l(this,"audioObjectURL");l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Tn(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(O(t.volume)||(this.volume=t.volume),O(t.loop)||(this.loop=t.loop),O(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reload(t){return y(this,null,function*(){if(t.url){let e=yield mc.download(t.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function kn(i,t){if(t&&typeof t!="function")throw new ie({code:oe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var ui=class ui{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Qu=Qu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qu}`}),this.log.info(`created id=${this.getAlias()}${Qu}`)}getName(){return ui.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ui.startValidateRule;case"update":return ui.updateValidateRule;case"stop":return ui.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Rp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return y(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{U.off("154",o,this)})};U.on("154",o,this),new En}else this.core.trtc.emit(Z.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>y(this,null,function*(){return t.play()})});else throw r})}update(t){return y(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),O(r)||n.setOperation(r),O(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:u,onDurationChange:m,onEnded:p}=t;e&&X.addCount({key:502009}),r&&X.addCount({key:502001}),o&&X.addCount({key:502002}),s&&X.addCount({key:502003}),n&&X.addCount({key:502004}),a&&X.addCount({key:502005}),typeof u!="function"&&X.addCount({key:502007}),typeof p!="function"&&X.addCount({key:502008}),typeof m!="function"&&X.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};l(ui,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),a=s.indexOf(n)>=0,u=o.startsWith("blob"),m=o.startsWith("data");if(!(a||u||m))throw new ie({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ie({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});kn("onTimeUpdate",t.onTimeUpdate),kn("onEnded",t.onEnded),kn("onDurationChange",t.onDurationChange)}}),l(ui,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){kn("onTimeUpdate",t.onTimeUpdate),kn("onEnded",t.onEnded),kn("onDurationChange",t.onDurationChange)}}),l(ui,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(ui,"Name","AudioMixer");var Yu=ui;var Zu=0,vp,Bi=class Bi{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",je("denoiser"));l(this,"workletNode");l(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Zu=Zu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Zu}`}),this.log.info(`created id=${this.getAlias()}${Zu}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ie({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return vp||(vp=this.doPreload(t)),vp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Pi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Bi.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Bi.startValidateRule(this.core);case"update":return Bi.updateValidateRule;case"stop":return Bi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ie({code:oe.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${o}/denoiser-wasm${Qm()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:u,message:m}=yield uA(r,ge(J({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new ie({code:oe.INVALID_PARAMETER,message:m});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:a,status:u}}),this.workletNode.port.onmessage=p=>{var E;let{data:g}=p;if(g.type==="cost"){let A=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[A](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${Fs(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(E=g==null?void 0:g.hist)==null?void 0:E.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return y(this,null,function*(){this.updateConfig(t)})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let e=!1;O(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),O(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};l(Bi,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),l(Bi,"stopValidateRule",{type:"object"}),l(Bi,"Name","AIDenoiser");var Ku=Bi;function uA(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:u,sign:m,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:m,status:p,message:u};let g=Ir(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",E="Init RTCAIDenoiser failed.",A="";switch(a){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${g}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${g}`;break;case 5:A=`Your packages is expired. Refer to: ${g}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:p,message:u?`${E} Reason: ${u}. ${A}`:`${E}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var KE=Ei(vi(),1);var Cp=class extends KE.EventEmitter{constructor(){super();l(this,"observer");l(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ot&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Ge.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&F.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Ge.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},lA=new Cp,Np=lA;function mA([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new _s(new DataView(new Uint8Array(s).buffer),!0)}function hA(i){return i.type==="empty"||i.data.byteLength===0}function pA(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function fA(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function Dp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-fA(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(mA),s=o.reduce((p,g)=>p+g.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),u=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let g=0;g<o[p].dataView.byteLength;g++)a.setInt8(m++,o[p].dataView.getInt8(g));for(let p=0;p<i.data.byteLength;p++)a.setInt8(m++,u.getInt8(p));return i.data=n,i}function wp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(hA(i)||!pA(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let u=e.getUint8(a);if(u===0)o++;else if(u===1){if(o===2||o===3){let m=a-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new _s(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var Mp=0,hc=class hc{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Mp++,this.log=t.log.createChild({id:`${this.getAlias()}${Mp}`}),this.log.info(`[sei] created id=${this.getAlias()}${Mp}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Dp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return wp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(Z.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:as?this.encode:Dp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:as?this.decode:wp,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return hc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(hc,"autoStart",!0),l(hc,"Name","SEI");var el=hc;function Op({frame:i,onDump:t}){return t==null||t(),i}function xp({frame:i,onDump:t}){return t==null||t(),i}var e_={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
98
|
+
${o.stack}`),!1}},i};var Pn=new WeakMap;function JE(i){let t=Pn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Pn.delete(i))}function XE(i,t){return Oe((e,r)=>function(...o){let s=Pn.get(this);s||(s=new Map,Pn.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let u=setTimeout(()=>{var m;(m=Pn.get(this))==null||m.delete(n)},i);s.set(n,u)}else{clearTimeout(a);let u=window.setTimeout(()=>{var m;e.apply(this,o),(m=Pn.get(this))==null||m.delete(n)},i);s.set(n,u)}})}var YE="trtc-sdk-v5",yp="5.14.0-wasm.4";function Ft(...i){return Oe((t,e)=>function(...r){try{qu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Ap(...i){return Oe((t,e)=>function(...r){try{qu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function qu(i,t,e,r){if(ct(i))for(let o=0;o<i.length;o++)ju.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else ju.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function ju({rule:i,value:t,key:e,fnName:r,className:o}){function s(u){return{code:oe.INVALID_PARAMETER,extraCode:u,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new ie(s(5001));if(O(i.defaultValue)){qe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let u=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(u=!0),qe(i.type[m])&&t instanceof i.type[m]&&(u=!0),De(i.type[m])&&mt(t)===i.type[m].toLowerCase()&&(u=!0);if(!u)throw new ie({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>qo(m)?zs(m):De(m)?m:mt(m))},value:t}})}else if(!O(i.type)&&mt(t)!==i.type)throw new ie(s(5002));if(i.allowEmpty===!1){let u=Le(t)&&(t===0||Number.isNaN(t)),m=De(t)&&t.trim()==="";if(u||m)throw new ie(s(5003))}if(i.notLessThanZero&&Le(t)&&t<0)throw new ie(s(5006));if(!O(i.min)&&Le(t)&&t<i.min)throw new ie(s(5007));if(!O(i.max)&&Le(t)&&t>i.max)throw new ie(s(5008));if(De(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ie(s(5004))}else if(qe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ie(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ie(s(5005));let{properties:n}=i;qt(n)&&cr(t)&&Object.keys(n).forEach(u=>{ju.call(this,{rule:n[u],value:t&&t[u],key:`${u}`,fnName:r,className:o})});let{arrayItem:a}=i;qt(a)&&ct(t)&&t.forEach((u,m)=>{ju.call(this,{rule:a,value:u,key:`${e}[${m}]`,fnName:r,className:o})}),qe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function it(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Oe((n,a)=>function(...u){var A,C,N;function m(D,x,Y){if(Y&&Y.includes(D))return"hided";if(e){let de=e(...u);if(u[de.argIndex]===x)return de.value}if(x===u||D in u)return x;try{return x instanceof HTMLElement?`id: ${x.id} type:${mt(x)}`:x instanceof MediaStreamTrack?dd(x):(JSON.stringify(x),x)}catch(de){return`type:${mt(x)}`}}let p=this._log||F;if(o!=null&&o(...u))return n.apply(this,u);u.length>0?p.info(`${a}() ${JSON.stringify(u,(D,x)=>m(D,x,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let g=r?r(...u):Wd[a],E=(s==null?void 0:s(...u))||!1;try{let D=n.apply(this,u),x=Ee();if(io(D)){let Y=`${a.includes("Plugin")?`${((C=(A=u[0]).getName)==null?void 0:C.call(A))||""} `:" "}`;return D.then(de=>(p.info(`${a}() success ${Y}${t.call(this,...u)}`),X.addSuccessEvent({key:g,cost:Ee()-x}),de)).catch(de=>{var H;de=ie.convertFrom.call(this,de,a,u.length===1?u[0]:u);let Se=de.extraCode||de.code,Ze=(H=de.message)!=null&&H.includes(Se)?"":` code:${Se}`;throw E||p.error(`${a}() failed ${Y}${t.call(this,...u)} ${de}${Ze} params: ${JSON.stringify(u,m)}`),X.addFailedEvent({key:g,error:de}),de})}return X.addSuccessEvent({key:g}),D}catch(D){D=ie.convertFrom.call(this,D,a);let x=D.extraCode||D.code,Y=(N=D.message)!=null&&N.includes(x)?"":` code:${x}`;throw E||p.error(`${a}() failed ${D}${Y} params: ${JSON.stringify(u,m)}`),X.addFailedEvent({key:g,error:D}),D}})}var zu=i=>Oe((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ie({code:oe.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(qe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ie({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return qu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Ju=0,bp,$i=class $i{constructor(t){this.core=t;l(this,"log");l(this,"customAudioReferenceMap",new Map);l(this,"audioRefId",0);l(this,"audioContext",je());l(this,"localAudioWorkletNode");l(this,"screenAudioWorkletNode");l(this,"mixNode");l(this,"silentNode");Ju=Ju+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ju}`}),this.log.info(`created id=${this.getAlias()}${Ju}`),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new ie({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return bp||(bp=this.doPreload(t)),bp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Pi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return $i.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return $i.getStartValidateRule(this.core);case"update":return $i.updateValidateRule;case"stop":return $i.stopValidateRule}}start(t){return y(this,null,function*(){var E,A,C,N;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:u,enableDump:m,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:g=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=g,!n)throw new ie({code:oe.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:D,status:x,timestamp:Y}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,Y,D,x,e)}if(g&&!this.screenAudioWorkletNode){let{sign:D,status:x,timestamp:Y}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,Y,D,x,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),O(u)||(C=this.localAudioWorkletNode)==null||C.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),O(m)||(N=this.localAudioWorkletNode)==null||N.port.postMessage({type:"dump",data:{enable:m}})})}update(t){return y(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;O(e)||(this.customAudioReferenceMap.forEach((u,m)=>{this.customAudioReferenceMap.delete(m),this.core.room.audioManager.updateAudioReference({type:"remove",refId:u})}),e.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})})),O(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),O(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return y(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:u}=yield cA({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${u}`),new ie({code:oe.INVALID_PARAMETER,message:u});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,u){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=m=>{var g;let{data:p}=m;switch(p.type){case"cost":let E=(p==null?void 0:p.value)>10?"info":"debug";this.log[E](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Fs(new Date(p==null?void 0:p.maxCostTimestamp))}) hist: ${(g=p==null?void 0:p.hist)==null?void 0:g.join(" ")}`);return;case"log":this.log[p.logLevel](`${e==="localAudio"?"":`[${e}] `}${p.value}`);return;case"dump":U.emit("265",{room:u,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return y(this,null,function*(){var e;if(!(!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return y(this,null,function*(){var e;!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};l($i,"updateValidateRule",{type:"object"}),l($i,"stopValidateRule",{type:"object"}),l($i,"Name","AudioProcessor");var Xu=$i;function aA(i,t=M.MAIN){return`https://${di[t]||Gu(i,t)}/api/v1/audioAiAuth`}function cA(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${aA(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,a=yield fetch(n),{data:{errCode:u,errMsg:m,sign:p,status:g}}=yield a.json();if(g==="1")return{auth:!0,sign:p,status:g,message:m};let E=Ir(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",C="";switch(u){case 1:C="Please check your params.";break;case 2:C=`You need to buy packages. Refer to: ${E}`;break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C=`Your packages is not active. Refer to: ${E}`;break;case 5:C=`Your packages is expired. Refer to: ${E}`;break;case 6:C="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${A} Reason: ${m}. ${C}`:`${A}, ${C}`}})}var Qu=0,Rp=class{constructor(t,e){l(this,"audioObjectURL");l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Tn(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(O(t.volume)||(this.volume=t.volume),O(t.loop)||(this.loop=t.loop),O(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reload(t){return y(this,null,function*(){if(t.url){let e=yield mc.download(t.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function kn(i,t){if(t&&typeof t!="function")throw new ie({code:oe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var ui=class ui{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Qu=Qu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qu}`}),this.log.info(`created id=${this.getAlias()}${Qu}`)}getName(){return ui.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ui.startValidateRule;case"update":return ui.updateValidateRule;case"stop":return ui.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Rp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return y(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{U.off("154",o,this)})};U.on("154",o,this),new En}else this.core.trtc.emit(Z.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>y(this,null,function*(){return t.play()})});else throw r})}update(t){return y(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),O(r)||n.setOperation(r),O(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:u,onDurationChange:m,onEnded:p}=t;e&&X.addCount({key:502009}),r&&X.addCount({key:502001}),o&&X.addCount({key:502002}),s&&X.addCount({key:502003}),n&&X.addCount({key:502004}),a&&X.addCount({key:502005}),typeof u!="function"&&X.addCount({key:502007}),typeof p!="function"&&X.addCount({key:502008}),typeof m!="function"&&X.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};l(ui,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),a=s.indexOf(n)>=0,u=o.startsWith("blob"),m=o.startsWith("data");if(!(a||u||m))throw new ie({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ie({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});kn("onTimeUpdate",t.onTimeUpdate),kn("onEnded",t.onEnded),kn("onDurationChange",t.onDurationChange)}}),l(ui,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){kn("onTimeUpdate",t.onTimeUpdate),kn("onEnded",t.onEnded),kn("onDurationChange",t.onDurationChange)}}),l(ui,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(ui,"Name","AudioMixer");var Yu=ui;var Zu=0,vp,Bi=class Bi{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",je("denoiser"));l(this,"workletNode");l(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Zu=Zu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Zu}`}),this.log.info(`created id=${this.getAlias()}${Zu}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ie({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return vp||(vp=this.doPreload(t)),vp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Pi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Bi.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Bi.startValidateRule(this.core);case"update":return Bi.updateValidateRule;case"stop":return Bi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ie({code:oe.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${o}/denoiser-wasm${Qm()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:u,message:m}=yield uA(r,ge(J({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new ie({code:oe.INVALID_PARAMETER,message:m});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:a,status:u}}),this.workletNode.port.onmessage=p=>{var E;let{data:g}=p;if(g.type==="cost"){let A=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[A](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${Fs(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(E=g==null?void 0:g.hist)==null?void 0:E.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return y(this,null,function*(){this.updateConfig(t)})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let e=!1;O(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),O(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};l(Bi,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),l(Bi,"stopValidateRule",{type:"object"}),l(Bi,"Name","AIDenoiser");var Ku=Bi;function uA(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:u,sign:m,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:m,status:p,message:u};let g=Ir(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",E="Init RTCAIDenoiser failed.",A="";switch(a){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${g}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${g}`;break;case 5:A=`Your packages is expired. Refer to: ${g}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:p,message:u?`${E} Reason: ${u}. ${A}`:`${E}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var KE=Ei(vi(),1);var Cp=class extends KE.EventEmitter{constructor(){super();l(this,"observer");l(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ot&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Ge.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&F.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Ge.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},lA=new Cp,Np=lA;function mA([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new _s(new DataView(new Uint8Array(s).buffer),!0)}function hA(i){return i.type==="empty"||i.data.byteLength===0}function pA(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function fA(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function Dp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-fA(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(mA),s=o.reduce((p,g)=>p+g.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),u=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let g=0;g<o[p].dataView.byteLength;g++)a.setInt8(m++,o[p].dataView.getInt8(g));for(let p=0;p<i.data.byteLength;p++)a.setInt8(m++,u.getInt8(p));return i.data=n,i}function wp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(hA(i)||!pA(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let u=e.getUint8(a);if(u===0)o++;else if(u===1){if(o===2||o===3){let m=a-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new _s(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var Mp=0,hc=class hc{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Mp++,this.log=t.log.createChild({id:`${this.getAlias()}${Mp}`}),this.log.info(`[sei] created id=${this.getAlias()}${Mp}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Dp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return wp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(Z.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:as?this.encode:Dp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:as?this.decode:wp,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return hc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(hc,"autoStart",!0),l(hc,"Name","SEI");var el=hc;function Op({frame:i,onDump:t}){return t==null||t(),i}function xp({frame:i,onDump:t}){return t==null||t(),i}var e_={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
99
99
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
100
100
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
101
101
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
@@ -140,4 +140,4 @@ void main() {
|
|
|
140
140
|
void main() {
|
|
141
141
|
gl_Position = vertexPos;
|
|
142
142
|
textureCoord = texturePos;
|
|
143
|
-
}`});l(this,"yTextureRef");l(this,"uTextureRef");l(this,"vTextureRef");l(this,"Y");l(this,"U");l(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var p_=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function AA(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var bA=0,ll=class{constructor(t){l(this,"id",bA++);l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"decoder");l(this,"videoContext");l(this,"gop",0);l(this,"gop_helper",0);l(this,"waitFirstKeyFrame",!0);l(this,"startTimestamp",0);l(this,"startTime",0);l(this,"startPerformanceTime",0);l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"decodeFrameCount",0);l(this,"downgradeLevel",0);l(this,"lastDowngradeTime",0);l(this,"lastFrameDiff",0);l(this,"lastDecodeFrameTimestamp",0);l(this,"config");l(this,"gop_before_configure",[]);l(this,"videoElement");l(this,"type","wasm");l(this,"goodType");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");l(this,"isReported",!1);l(this,"track");l(this,"stateChangeOB");l(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=vt(),this.track=e,this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=be(e.availableState,ue.OFF),this.stopOB=vt(),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),Ae(this.stateChangeOB,Zh((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Je(this.stopOB),Ue()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ae(this.pipe(this.track),Je(this.stopOB),ki());Ae(e,Ue(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),X.addFailedEvent({key:p_(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),X.addFailedEvent({key:514704});else{if(this.goodType){this.start(t);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),X.addSuccessEvent({key:p_(this.type,this.renderer)}),X.addSuccessEvent({key:514704})})),Ae(e,Gr(1),Ue(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.start()}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!jm()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,u;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!AA(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(m=>this.decode(m,!0)),this.gop_before_configure=[]);let{timestamp:n}=t;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=Ee();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(u=t.getMetadata)==null?void 0:u.call(t).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:t.data,type:t.type,timestamp:this.lastDecodeFrameTimestamp});return}return t}checkDowngradeByFrameDiff(){let t=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug(`downgrade level ${t} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(t){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-t>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(t){return e=>y(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",u=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${u.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(u.timestamp)),e.next(u)}),r.on("error",u=>{t.log.error(u),e.error(n==="webCodecs"?4:8)}),yield r.initialize(this.videoElement),!this._decodeSink)return;if(r.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new At({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(At.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let u=new ul(this.videoContext);r.on("videoCodecInfo",m=>u.resize(m.width,m.height)),r.on("videoFrame",m=>{({y:u.Y,u:u.U,v:u.V}=m),this.downgradeLevel===1?this.decodedFrameCount%2===0&&u.render(this.decodedFrameCount):u.render(this.decodedFrameCount)}),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let u=new MediaStreamTrackGenerator({kind:"video"}),m=u.writable.getWriter();t.setInputMediaStreamTrack(u),r.on("videoFrame",p=>m.write(p))}else{this.videoContext=new Mt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let u=this.videoContext.createVideoImageSource();r.on("videoFrame",p=>{try{u.image=p,u.update()}catch(g){delete this.goodType,t.log.error(g),e.error(11)}});let m=new Ts(this.videoContext,{name:"remotePlayer",logger:t.log});u.connect(m),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var f_=Promise.resolve(),Ic=class extends g_.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"_rotation",0);l(this,"cameraTrack");l(this,"cameraNode");l(this,"transformNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"_enableFaceCentering",!1);l(this,"_enableEffectOptimization",!1);l(this,"onAbort");l(this,"_color");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"mixTrack");l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",F.createLogger({id:"vm"}));l(this,"_mat4");l(this,"_postProcessing");l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);l(this,"updated",f_);l(this,"_updateFlag",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Mt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return dr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Mt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new At({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(lm<=22),this._glVideoContext.on(At.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,r,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=ht.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),ht.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Sr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new At({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Cu(this.smallVideoContext,e,this.log),this.smallVideoContext.on(At.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;Sr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ct.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),kt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof br?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof br?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new vu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ct.RENDER,m=>{var p;(p=this.cameraTrack)==null||p.emit("render",m)}));let{width:n,height:a}=this.cameraResolution,u=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:u.width,height:u.height,image:u},this.cameraNode=new dl(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=o.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Rr(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Cn(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:u,height:m}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(u,m),u&&m&&this.waterMarkNode.resize(u,m)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var r,o,s,n,a;if(e instanceof ni)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof hr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Io){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let u=e.mediaTrack;return e.setOutputMediaStreamTrack(u)}if(e instanceof Ss)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof ni?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hr?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Io?e.source&&e.source.context.destroy():e instanceof Ss&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return y(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,r){return y(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new ce({code:j.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:u,width:m,height:p,fillVideo:g})=>{let E=g&&e||m,A=g&&r||p,C=g?0:a,N=g?0:u;s.drawImage(n,C,N,E,A)}),Ys(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return y(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return y(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return y(this,null,function*(){let r;try{r=yield Ys((e==null?void 0:e.imageElement)||e.imageUrl)}catch(E){throw new ce({code:j.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:u="watermark",zIndex:m=2,fillVideo:p=!1}=e;this.watermarkImageList.some(E=>E.type===u)?(this.watermarkImageList=this.watermarkImageList.filter(E=>E.type!==u),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl,fillVideo:p}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl,fillVideo:p}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(E,A)=>E==="imageUrl"?void 0:A))})}deleteWatermark(e="watermark"){return y(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return y(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return y(this,null,function*(){var r,o,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Ys(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new ce({code:j.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return y(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new ll(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};ee([tE(function(e){this.log.error("update failed",e)}),Oe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield f_,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:j.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Ic.prototype,"update",1);var RA=0;var ml=class extends ue{constructor(e){super("room");l(this,"seq",++RA);l(this,"sdkAppId");l(this,"userId");l(this,"userSig");l(this,"privateMapKey");l(this,"latencyLevel");l(this,"tinyId");l(this,"scene");l(this,"roomId");l(this,"useStringRoomId");l(this,"role","anchor");l(this,"joinParams",null);l(this,"localPublishFlag",0);l(this,"localTracks",new Set);l(this,"enableAutoPlayDialog",!0);l(this,"autoReceiveAudio",!0);l(this,"autoReceiveVideo",!0);l(this,"proxy_ws");l(this,"proxy_wt");l(this,"proxy_unified");l(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});l(this,"keyPointManager");l(this,"audioManager");l(this,"videoManager");l(this,"callDurationCalculator");l(this,"badCaseDetector");l(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});l(this,"videoDecodeFallbackType");l(this,"smallMode","canvas");l(this,"enableChorus",!1);l(this,"_isUsingCachedSchedule",!1);l(this,"_log",F.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Ye(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ye(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ye(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new l_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new m_({room:this}),this.badCaseDetector=new h_({room:this}),this.audioManager=new wu(this),this.videoManager=new Ic(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return y(this,null,function*(){return this.publish(e)})}removeTrack(e){return y(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return y(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(De(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(qt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Wu([a,a]),$o(`https://${a}`)):(s&&$o(s),n&&Wu(n))}U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:di.main,sched_back_domain:di.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return y(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return y(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return y(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new ce({code:j.INVALID_OPERATION,message:Be({key:$e.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(rr.INVALID_DESTROY),new ce({code:j.INVALID_OPERATION,message:Be({key:$e.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,U.emit($.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,u;let o=Ee();try{let{isCached:m,result:p,detailCost:g}=yield Ip({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:lt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=m,this._log.info(`schedule cache:${+m} ${Tr(p,{keysToExclude:["username","credential"]})}`),m&&U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),p),Le((s=p.config)==null?void 0:s.retryCount)&&Fl(p.config.retryCount),De((n=p.config)==null?void 0:n.loggerDomain)&&$o(p.config.loggerDomain),this.videoDecodeFallbackType=((a=p.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((u=p.config)==null?void 0:u.smallMode)||this.smallMode,U.emit($.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),X.addSuccessEvent({key:521700,cost:Ee()-o})}catch(m){throw X.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function E_(i,t=!1){let e=Object.defineProperties(vt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=He,i.onmessageerror=He,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var Bp=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=He,e(r)}},A4=_e(Bp,"takeUntilComplete");var $t={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},__="__INLINE__WORKER__",T_="__INLINE__WASM__",{debug:I_}=console;$t.debug||(console.debug=()=>{});var vA=!__.startsWith("__"),CA=!T_.startsWith("__");function hl(){let i=Xo(`${$t.assetsPath?`${$t.assetsPath}/`:""}worker.js`);return vA?URL.createObjectURL(new Blob([atob(__)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Sc;function pl(){return y(this,null,function*(){let i=$t.assetsPath?`${$t.assetsPath}/`:"";return Sc||(CA?Sc=new TextEncoder().encode(atob(T_)).buffer:Sc=yield fetch(Xo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Sc)})}var Hp=class{constructor(){l(this,"playPort");l(this,"playPortSent",!1);l(this,"worklet");l(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=je("player"),e=hl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield pl(),flag:$t},numberOfInputs:2}),F.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},fl=new Hp;var Wp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),M4=Wp?Promise.resolve().then(function(){return MA}):Promise.resolve().then(function(){return UA});var O4=Wp?Promise.resolve().then(function(){return xA}):Promise.resolve().then(function(){return FA});var NA=Wp?Promise.resolve().then(function(){return kA}):Promise.resolve().then(function(){return BA});function Gp(...i){return y(this,null,function*(){return(yield NA).default(...i)})}var DA=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),wA=(...t)=>y(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,n)=>{e[n]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(a=>{e[n].accept[a]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(DA));return i[0].multiple?o:o[0]}),MA={__proto__:null,default:wA};function gl(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return gl=function(e){this.s=e,this.n=e.next},gl.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new gl(i)}var S_=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],u=[];var m,p=!1,g=!1;try{for(var E,A=function(C){var N,D,x,Y=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,x=Symbol.iterator);Y--;){if(D&&(N=C[D])!=null)return N.call(C);if(x&&(N=C[x])!=null)return new gl(N.call(C));D="@@asyncIterator",x="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(E=yield A.next()).done;p=!1){let C=E.value,N=`${e}/${C.name}`;C.kind==="file"?u.push(C.getFile().then(D=>(D.directoryHandle=i,D.handle=C,Object.defineProperty(D,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>N})))):C.kind!=="directory"||!t||r&&r(C)||a.push(S_(C,t,N,r))}}catch(C){g=!0,m=C}finally{try{p&&A.return!=null&&(yield A.return())}finally{if(g)throw m}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(u)]}),OA=(...t)=>y(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return S_(e,i.recursive,void 0,i.skipDirectory)}),xA={__proto__:null,default:OA},PA=(s,...n)=>y(void 0,[s,...n],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let a=[],u=null;if(i instanceof Blob&&i.type?u=i.type:i.headers&&i.headers.get("content-type")&&(u=i.headers.get("content-type")),t.forEach((g,E)=>{a[E]={description:g.description||"Files",accept:{}},g.mimeTypes?(E===0&&u&&g.mimeTypes.push(u),g.mimeTypes.map(A=>{a[E].accept[A]=g.extensions||[]})):u?a[E].accept[u]=g.extensions||[]:a[E].accept["*/*"]=g.extensions||[]}),e)try{yield e.getFile()}catch(g){if(e=null,r)throw g}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let p=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(p),m):"body"in i?(yield i.body.pipeTo(p),m):(yield p.write(yield i),yield p.close(),m)}),kA={__proto__:null,default:PA},LA=(...t)=>y(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(m=>m.mimeTypes||[]),...i.map(m=>m.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=m=>{typeof a=="function"&&a(),e(m)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),u=()=>{window.removeEventListener("focus",u),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",u)}),o.addEventListener("change",()=>{window.removeEventListener("focus",u),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),UA={__proto__:null,default:LA},VA=(...t)=>y(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(u=>u.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):a=a.filter(u=>u.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),FA={__proto__:null,default:VA},$A=(e,...r)=>y(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(u,m){return y(this,null,function*(){let p=u.getReader(),g=new ReadableStream({start:C=>function N(){return y(this,null,function*(){return p.read().then(({done:D,value:x})=>{if(!D)return C.enqueue(x),N();C.close()})})}()}),E=new Response(g),A=yield E.blob();return p.releaseLock(),new Blob([A],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),BA={__proto__:null,default:$A};var jp=class{constructor(t){this.name=t;l(this,"ready");l(this,"worker");l(this,"ports");l(this,"ids",1);l(this,"transactions",new Map);l(this,"log");l(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return y(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=hl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>y(this,null,function*(){r.onmessage=({data:{id:n,type:a,payload:u}})=>{var m;if(n)(m=this.transactions.get(n))==null||m(u),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",u),s(u);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(u.value){let p=typeof u.old=="string"?u.old:`${u.old.action}ing`,g=typeof u.value=="string"?u.value:`${u.value.action}ing`;console.log(nd(),u.group,u.name,p,"\u{1F449}",g)}break;case"log":console.log(u);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:u}));break}},r.postMessage({wasm:yield pl(),flag:$t},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},qp=class{constructor(t,e,r){this.worker=t;l(this,"channel",new MessageChannel);l(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},zp=class i extends jp{constructor(){super("main");l(this,"switchValue",new Map);l(this,"extendChannel");l(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return y(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Pt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},vo=new zp,Ns,HA=-1;function y_(i){return console.log(i),Ns.push(i.slice()),Ns.length>1e3&&Ns.shift(),i}function A_(i){return y(this,null,function*(){switch(HA){case 0:this.edpl.willDecodeAudio=y_;break;case 2:this.edpl.didEncodeAudio=y_;break}yield vo.create(),U.emit($.JOIN_SEND_CMD,{room:this});let t=new qp(vo,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(U.emit($.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ce({code:j.JOIN_ROOM_FAILED,extraCode:Number(e),message:Be({key:$e.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Jp},useWt:{set:WA},enableDebug:{set(i){console.debug=i?I_:()=>{},vo.setSwitchValue("enableDebug",i)}},useV2:{set:Xp},dump:{value(){if(Ns||(console.warn("dump audio will be activated at next time join room"),Ns=[]),!Ns.length){console.warn("no audio data to dump,try it later");return}let i=[];return Ns.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Gp(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;vo.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:n})=>{console.log(n),e.push(n),e.length>t&&(s.port2.onmessage=null,vo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Gp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:$t.useHardDecoder="prefer-hardware";break;case!1:$t.useHardDecoder="prefer-software";break;default:$t.useHardDecoder="no-preference"}}}});function Jp(i){return y(this,null,function*(){vo.setSwitchValue("useAINS",i)})}function Xp(i){return y(this,null,function*(){vo.setSwitchValue("useV2",i)})}function WA(i){return y(this,null,function*(){vo.setSwitchValue("useWt",i)})}function b_(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),i.player.setVolume(0),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function R_(i){return y(this,null,function*(){var o;this._log.info("pull video",i);let t=Date.now(),e=0,r=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[r.port1]),(o=i.stat).framesReceived||(o.framesReceived=0),Ae(E_(r.port2),Je(be(i,ue.INIT)),Ue(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let u=n[4]&31;if(e<=10){let p=Array.from(n.slice(0,10)).map(g=>g.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${u}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${p}`)}let m;switch(u){case 5:case 7:m="key";break;default:m="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:m,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var El=[];function C_(i){var u;let t=vt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=El.length;m++)if(!El[m]){El[m]=this,this.index=m;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(u=this.session)==null||u.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(ge(J({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,a=m=>{let p=s.getAudioTracks()[0];p&&(n.disconnect(),s.removeTrack(p)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=je("player").createMediaStreamSource(s),n.connect(fl.worklet,0,this.index)};Ae(be(i,"output-media-track-changed"),Je(be(i,"ready")),Ue(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),El[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ae(t,rc(m=>i.volume=m),Li(Ru(1e3)),Ue(()=>{i.volume=0})),a(i.outMediaTrack)}var mW=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Qp=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;l(this,"track");l(this,"label");l(this,"insertKeyFrame",!0);l(this,"session");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){return y(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e.recreateCount===0&&U.emit($.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let u=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(u.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return y(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function _l(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.6400ef",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:$t.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Qp(i,t.type,o,s.port2);return s.port2.onmessage=a=>{a.data===260&&(n.insertKeyFrame=!0)},this._log.info("start push",r,t),n})}function N_(i){return y(this,null,function*(){var p;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((p=i.manager)!=null&&p.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let a=yield _l.call(this,i,r);this._log.info("VideoEncoder created",r);let u,m=g=>y(this,null,function*(){if(u==null||u.abort("track changed"),!g)return;u=new AbortController;let{width:E,height:A,displaySurface:C}=g.getSettings();E&&(a.config.width=E),A&&(a.config.height=A);let N=er.match(/Chrome\/(\d+)/);(N==null?void 0:N[1])==="114"&&C==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",g.readyState,g.getSettings());let D;if(typeof MediaStreamTrackProcessor!="undefined"&&!(g instanceof CanvasCaptureMediaStreamTrack))D=new MediaStreamTrackProcessor({track:g}).readable;else{let Y;D=new ReadableStream({start(de){i.on("render",Se=>{if(i.player.mode!==0)try{de.enqueue(new VideoFrame(Se,{timestamp:performance.now()*1e3}))}catch(Ze){console.warn(Ze)}})},pull(de){return y(this,null,function*(){if(i.player.mode===0&&Br()&&i.player.element)return new Promise(Se=>{i.player.element.requestVideoFrameCallback((Ze,H)=>{try{let ke=new VideoFrame(i.player.element);de.enqueue(ke)}catch(ke){console.warn(ke)}Se()})})})}})}let x="small"in i&&i.small;return x?(this.smallEncoder||(this.smallEncoder=yield _l.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=g,this.smallEncoder.label="small",D=yield this.smallEncoder.trans(D,u,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=g,a.label=e,a.start(D,u,this)});return Ae(be(i,"output-media-track-changed"),Je(be(i,"ready")),Ue(m,console.error,()=>{var g;this._log.info("stop push",e,r),u.abort("unpublish"),a.close(),(g=this.smallEncoder)==null||g.close()})),m(i.outMediaTrack)})}var Co=class Co extends ue{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;l(this,"enableInBackground",!1);l(this,"interval",400);e.on("joined",()=>{this.emit(Co.INTERVALCHANGED,this.interval)}),Ae(be(this,Co.INTERVALCHANGED),Eo(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ae(gE(s),go(()=>[]))),Ue(s=>{s.forEach(n=>{this.room.remotePublishedUserMap.has(n.userId)&&(this.room.remotePublishedUserMap.get(n.userId).remoteAudioTrack.volume=n.volume)}),(!document.hidden||this.enableInBackground)&&this.state==ue.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Co.INTERVALCHANGED,this.interval)}stop(){}};l(Co,"INTERVALCHANGED","intervalChanged"),ee([Ke([ue.INIT,ue.OFF],ue.ON)],Co.prototype,"start",1),ee([Ke([],ue.OFF)],Co.prototype,"stop",1);var Tl=Co;var No=class No extends ml{constructor(e){super(e);l(this,"index",0);l(this,"session");l(this,"tinyid");l(this,"roomid");l(this,"openid");l(this,"socketid");l(this,"relayip");l(this,"clientip");l(this,"remotePublishedUserMap",new Map);l(this,"bussinessInfo");l(this,"token");l(this,"audioVolumeEvalution",new Tl(this));l(this,"enableAIVoice",Jp);l(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Tm(),uint32_device_type:0,str_os_verion:Im(),uint32_link_type:1,str_client_version:lt,uint32_net_type:Bo[ei.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Xp(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return y(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){this.session&&(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let n=new MessageChannel;this.postMessage({cmd:e,payload:r},[n.port1]),n.port2.onmessageerror=s,n.port2.onmessage=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return y(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return y(this,null,function*(){var u,m,p;let s=ei.getEnv(),n=qd(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(u=this.proxy_wt)==null?void 0:u.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(p=this.scheduleResult.iceServers)!=null&&p.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:ln(),browserInfo:qd(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:lt,browserVersion:n.browserName+n.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield A_.call(this,a),console.log(this),fl.playAudio(g=>this.postMessage({cmd:"setAudioWorkletPort"},[g])),this.checkDestroy()})}leave(){return y(this,null,function*(){this.remotePublishedUserMap.forEach(e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((e,r)=>r.unpublish()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return y(this,null,function*(){let e=Je(be(this,"left"));Ae(r=>y(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,Ue(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(ge(J({},r),{data:new Uint8Array(s.data)}),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case $.RECEIVED_PUBLISHED_USER_LIST:U.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new sl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let g=r,E=this.remotePublishedUserMap.get(g);E&&(E.remoteVideoTrack.close(),E.remoteAuxiliaryTrack.close(),E.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(g),this.emit("remote-unpublished",E))}return;case"banned":switch(r){case 8:this.emit("banned",{reason:"kick",message:""});return;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});return;case 7:case 5:this.emit("banned",{reason:"room_disband",message:""});return}break;case"6":{let{prevMuteState:g,muteState:E,flag:A}=r,C=this.remotePublishedUserMap.get(E.userId);if(!C){this.emit("remote-publish-state-changed",r);return}C.flag=A}U.emit($.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:u,msg_down_stream_info:m}=r,p={str_sdk_version:lt,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Bo[aa()]},msg_event_msg:TE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:m};U.emit($.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),U.emit($.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:u}),delete r.downlinkInfo;break;case"signal-connection-state-changed":U.emit($.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return y(this,null,function*(){e.forEach(a=>this.localTracks.add(a));let r=e.reduce((a,u)=>u.mediaType|a,0),o=this.sendMessage("publish",r).then(a=>a.err!==0?Promise.reject(a.err):a),s=0,n=a=>y(this,null,function*(){switch(yield o,a.muted&&(s|=a.mediaType),Lt(a,a).add("mute",()=>{this.postMessage("mute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),a.mediaType){case 1:C_.call(this,a);break;default:yield N_.call(this,a)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return y(this,null,function*(){e.forEach(Tt),e.forEach(r=>this.localTracks.delete(r))})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((g,E)=>E.mediaType|g,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),u=J({},a.subscribeState),m=Object.assign(new va,u);m.mediaType|=r,U.emit($.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:m});let p=yield this.sendMessage("subscribe",{mediaType:m.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(g=>m.mediaType&g).map(g=>({mediaType:g,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",p),yield Promise.all(e.filter(g=>!g.isSubscribed).map(g=>{switch(g.mediaType){case 1:return b_.call(this,g);default:return R_.call(this,g)}})),U.emit($.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let a of e)a.unsubscribe();U.emit($.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return y(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield _l.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(a=>s&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};ee([po(No.prototype.afterJoin),Ke(["left",ue.INIT],"joined"),n_()],No.prototype,"join",1),ee([Ke("joined","left",{ignoreError:!0}),a_()],No.prototype,"leave",1),ee([ls(),c_()],No.prototype,"publish",1),ee([ls(),d_()],No.prototype,"unpublish",1),ee([sE((...e)=>e[0].userId),u_()],No.prototype,"subscribe",1);var Il=No;Ln.frameWorkType=37;Ln.create=function(i){let t=Ln._create.call(this,Il,i);return t._use(gp,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&($t.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",lt,"created",$t),t};Object.assign(Ln.prototype,{_setCurrentSpeaker(i){let t=je("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(gp.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{Ae(be(i,"decode-downgrade-state-changed"),Yt(o=>o.state==="STARTED"),Gr(1),rp(1e4),Je(be(i,ue.INIT)),Ue(e,r))})})}});Ym(37);var VG=Ln;export{VG as default};
|
|
143
|
+
}`});l(this,"yTextureRef");l(this,"uTextureRef");l(this,"vTextureRef");l(this,"Y");l(this,"U");l(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var p_=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function AA(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var bA=0,ll=class{constructor(t){l(this,"id",bA++);l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"decoder");l(this,"videoContext");l(this,"gop",0);l(this,"gop_helper",0);l(this,"waitFirstKeyFrame",!0);l(this,"startTimestamp",0);l(this,"startTime",0);l(this,"startPerformanceTime",0);l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"decodeFrameCount",0);l(this,"downgradeLevel",0);l(this,"lastDowngradeTime",0);l(this,"lastFrameDiff",0);l(this,"lastDecodeFrameTimestamp",0);l(this,"config");l(this,"gop_before_configure",[]);l(this,"videoElement");l(this,"type","wasm");l(this,"goodType");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");l(this,"isReported",!1);l(this,"track");l(this,"stateChangeOB");l(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=vt(),this.track=e,this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=be(e.availableState,ue.OFF),this.stopOB=vt(),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),Ae(this.stateChangeOB,Zh((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Je(this.stopOB),Ue()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ae(this.pipe(this.track),Je(this.stopOB),ki());Ae(e,Ue(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),X.addFailedEvent({key:p_(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),X.addFailedEvent({key:514704});else{if(this.goodType){this.start(t);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),X.addSuccessEvent({key:p_(this.type,this.renderer)}),X.addSuccessEvent({key:514704})})),Ae(e,Gr(1),Ue(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.start()}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!jm()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,u;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!AA(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(m=>this.decode(m,!0)),this.gop_before_configure=[]);let{timestamp:n}=t;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=Ee();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(u=t.getMetadata)==null?void 0:u.call(t).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:t.data,type:t.type,timestamp:this.lastDecodeFrameTimestamp});return}return t}checkDowngradeByFrameDiff(){let t=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug(`downgrade level ${t} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(t){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-t>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(t){return e=>y(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",u=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${u.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(u.timestamp)),e.next(u)}),r.on("error",u=>{t.log.error(u),e.error(n==="webCodecs"?4:8)}),yield r.initialize(this.videoElement),!this._decodeSink)return;if(r.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new At({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(At.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let u=new ul(this.videoContext);r.on("videoCodecInfo",m=>u.resize(m.width,m.height)),r.on("videoFrame",m=>{({y:u.Y,u:u.U,v:u.V}=m),this.downgradeLevel===1?this.decodedFrameCount%2===0&&u.render(this.decodedFrameCount):u.render(this.decodedFrameCount)}),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let u=new MediaStreamTrackGenerator({kind:"video"}),m=u.writable.getWriter();t.setInputMediaStreamTrack(u),r.on("videoFrame",p=>m.write(p))}else{this.videoContext=new Mt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let u=this.videoContext.createVideoImageSource();r.on("videoFrame",p=>{try{u.image=p,u.update()}catch(g){delete this.goodType,t.log.error(g),e.error(11)}});let m=new Ts(this.videoContext,{name:"remotePlayer",logger:t.log});u.connect(m),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var f_=Promise.resolve(),Ic=class extends g_.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"_rotation",0);l(this,"cameraTrack");l(this,"cameraNode");l(this,"transformNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"_enableFaceCentering",!1);l(this,"_enableEffectOptimization",!1);l(this,"onAbort");l(this,"_color");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"mixTrack");l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",F.createLogger({id:"vm"}));l(this,"_mat4");l(this,"_postProcessing");l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);l(this,"updated",f_);l(this,"_updateFlag",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Mt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return dr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Mt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new At({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(lm<=22),this._glVideoContext.on(At.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,r,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=ht.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),ht.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Sr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new At({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Cu(this.smallVideoContext,e,this.log),this.smallVideoContext.on(At.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;Sr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ct.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),kt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof br?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof br?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new vu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ct.RENDER,m=>{var p;(p=this.cameraTrack)==null||p.emit("render",m)}));let{width:n,height:a}=this.cameraResolution,u=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:u.width,height:u.height,image:u},this.cameraNode=new dl(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=o.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Rr(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Cn(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:u,height:m}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(u,m),u&&m&&this.waterMarkNode.resize(u,m)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var r,o,s,n,a;if(e instanceof ni)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof hr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Io){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let u=e.mediaTrack;return e.setOutputMediaStreamTrack(u)}if(e instanceof Ss)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof ni?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hr?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Io?e.source&&e.source.context.destroy():e instanceof Ss&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return y(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,r){return y(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new ce({code:j.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:u,width:m,height:p,fillVideo:g})=>{let E=g&&e||m,A=g&&r||p,C=g?0:a,N=g?0:u;s.drawImage(n,C,N,E,A)}),Ys(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return y(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return y(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return y(this,null,function*(){let r;try{r=yield Ys((e==null?void 0:e.imageElement)||e.imageUrl)}catch(E){throw new ce({code:j.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:u="watermark",zIndex:m=2,fillVideo:p=!1}=e;this.watermarkImageList.some(E=>E.type===u)?(this.watermarkImageList=this.watermarkImageList.filter(E=>E.type!==u),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl,fillVideo:p}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl,fillVideo:p}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(E,A)=>E==="imageUrl"?void 0:A))})}deleteWatermark(e="watermark"){return y(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return y(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return y(this,null,function*(){var r,o,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Ys(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new ce({code:j.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return y(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new ll(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};ee([tE(function(e){this.log.error("update failed",e)}),Oe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield f_,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:j.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Ic.prototype,"update",1);var RA=0;var ml=class extends ue{constructor(e){super("room");l(this,"seq",++RA);l(this,"sdkAppId");l(this,"userId");l(this,"userSig");l(this,"privateMapKey");l(this,"latencyLevel");l(this,"tinyId");l(this,"scene");l(this,"roomId");l(this,"useStringRoomId");l(this,"role","anchor");l(this,"joinParams",null);l(this,"localPublishFlag",0);l(this,"localTracks",new Set);l(this,"enableAutoPlayDialog",!0);l(this,"autoReceiveAudio",!0);l(this,"autoReceiveVideo",!0);l(this,"proxy_ws");l(this,"proxy_wt");l(this,"proxy_unified");l(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});l(this,"keyPointManager");l(this,"audioManager");l(this,"videoManager");l(this,"callDurationCalculator");l(this,"badCaseDetector");l(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});l(this,"videoDecodeFallbackType");l(this,"smallMode","canvas");l(this,"enableChorus",!1);l(this,"_isUsingCachedSchedule",!1);l(this,"_log",F.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Ye(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ye(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ye(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new l_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new m_({room:this}),this.badCaseDetector=new h_({room:this}),this.audioManager=new wu(this),this.videoManager=new Ic(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return y(this,null,function*(){return this.publish(e)})}removeTrack(e){return y(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return y(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(De(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(qt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Wu([a,a]),$o(`https://${a}`)):(s&&$o(s),n&&Wu(n))}U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:di.main,sched_back_domain:di.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return y(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return y(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return y(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new ce({code:j.INVALID_OPERATION,message:Be({key:$e.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(rr.INVALID_DESTROY),new ce({code:j.INVALID_OPERATION,message:Be({key:$e.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,U.emit($.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,u;let o=Ee();try{let{isCached:m,result:p,detailCost:g}=yield Ip({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:lt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=m,this._log.info(`schedule cache:${+m} ${Tr(p,{keysToExclude:["username","credential"]})}`),m&&U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),p),Le((s=p.config)==null?void 0:s.retryCount)&&Fl(p.config.retryCount),De((n=p.config)==null?void 0:n.loggerDomain)&&$o(p.config.loggerDomain),this.videoDecodeFallbackType=((a=p.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((u=p.config)==null?void 0:u.smallMode)||this.smallMode,U.emit($.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),X.addSuccessEvent({key:521700,cost:Ee()-o})}catch(m){throw X.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function E_(i,t=!1){let e=Object.defineProperties(vt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=He,i.onmessageerror=He,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var Bp=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=He,e(r)}},A4=_e(Bp,"takeUntilComplete");var $t={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},__="__INLINE__WORKER__",T_="__INLINE__WASM__",{debug:I_}=console;$t.debug||(console.debug=()=>{});var vA=!__.startsWith("__"),CA=!T_.startsWith("__");function hl(){let i=Xo(`${$t.assetsPath?`${$t.assetsPath}/`:""}worker.js`);return vA?URL.createObjectURL(new Blob([atob(__)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Sc;function pl(){return y(this,null,function*(){let i=$t.assetsPath?`${$t.assetsPath}/`:"";return Sc||(CA?Sc=new TextEncoder().encode(atob(T_)).buffer:Sc=yield fetch(Xo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Sc)})}var Hp=class{constructor(){l(this,"playPort");l(this,"playPortSent",!1);l(this,"worklet");l(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=je("player"),e=hl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield pl(),flag:$t},numberOfInputs:2}),F.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},fl=new Hp;var Wp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),M4=Wp?Promise.resolve().then(function(){return MA}):Promise.resolve().then(function(){return UA});var O4=Wp?Promise.resolve().then(function(){return xA}):Promise.resolve().then(function(){return FA});var NA=Wp?Promise.resolve().then(function(){return kA}):Promise.resolve().then(function(){return BA});function Gp(...i){return y(this,null,function*(){return(yield NA).default(...i)})}var DA=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),wA=(...t)=>y(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,n)=>{e[n]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(a=>{e[n].accept[a]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(DA));return i[0].multiple?o:o[0]}),MA={__proto__:null,default:wA};function gl(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return gl=function(e){this.s=e,this.n=e.next},gl.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new gl(i)}var S_=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],u=[];var m,p=!1,g=!1;try{for(var E,A=function(C){var N,D,x,Y=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,x=Symbol.iterator);Y--;){if(D&&(N=C[D])!=null)return N.call(C);if(x&&(N=C[x])!=null)return new gl(N.call(C));D="@@asyncIterator",x="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(E=yield A.next()).done;p=!1){let C=E.value,N=`${e}/${C.name}`;C.kind==="file"?u.push(C.getFile().then(D=>(D.directoryHandle=i,D.handle=C,Object.defineProperty(D,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>N})))):C.kind!=="directory"||!t||r&&r(C)||a.push(S_(C,t,N,r))}}catch(C){g=!0,m=C}finally{try{p&&A.return!=null&&(yield A.return())}finally{if(g)throw m}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(u)]}),OA=(...t)=>y(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return S_(e,i.recursive,void 0,i.skipDirectory)}),xA={__proto__:null,default:OA},PA=(s,...n)=>y(void 0,[s,...n],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let a=[],u=null;if(i instanceof Blob&&i.type?u=i.type:i.headers&&i.headers.get("content-type")&&(u=i.headers.get("content-type")),t.forEach((g,E)=>{a[E]={description:g.description||"Files",accept:{}},g.mimeTypes?(E===0&&u&&g.mimeTypes.push(u),g.mimeTypes.map(A=>{a[E].accept[A]=g.extensions||[]})):u?a[E].accept[u]=g.extensions||[]:a[E].accept["*/*"]=g.extensions||[]}),e)try{yield e.getFile()}catch(g){if(e=null,r)throw g}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let p=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(p),m):"body"in i?(yield i.body.pipeTo(p),m):(yield p.write(yield i),yield p.close(),m)}),kA={__proto__:null,default:PA},LA=(...t)=>y(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(m=>m.mimeTypes||[]),...i.map(m=>m.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=m=>{typeof a=="function"&&a(),e(m)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),u=()=>{window.removeEventListener("focus",u),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",u)}),o.addEventListener("change",()=>{window.removeEventListener("focus",u),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),UA={__proto__:null,default:LA},VA=(...t)=>y(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(u=>u.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):a=a.filter(u=>u.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),FA={__proto__:null,default:VA},$A=(e,...r)=>y(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(u,m){return y(this,null,function*(){let p=u.getReader(),g=new ReadableStream({start:C=>function N(){return y(this,null,function*(){return p.read().then(({done:D,value:x})=>{if(!D)return C.enqueue(x),N();C.close()})})}()}),E=new Response(g),A=yield E.blob();return p.releaseLock(),new Blob([A],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),BA={__proto__:null,default:$A};var jp=class{constructor(t){this.name=t;l(this,"ready");l(this,"worker");l(this,"ports");l(this,"ids",1);l(this,"transactions",new Map);l(this,"log");l(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return y(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=hl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>y(this,null,function*(){r.onmessage=({data:{id:n,type:a,payload:u}})=>{var m;if(n)(m=this.transactions.get(n))==null||m(u),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",u),s(u);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(u.value){let p=typeof u.old=="string"?u.old:`${u.old.action}ing`,g=typeof u.value=="string"?u.value:`${u.value.action}ing`;console.log(nd(),u.group,u.name,p,"\u{1F449}",g)}break;case"log":console.log(u);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:u}));break}},r.postMessage({wasm:yield pl(),flag:$t},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},qp=class{constructor(t,e,r){this.worker=t;l(this,"channel",new MessageChannel);l(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},zp=class i extends jp{constructor(){super("main");l(this,"switchValue",new Map);l(this,"extendChannel");l(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return y(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Pt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},vo=new zp,Ns,HA=-1;function y_(i){return console.log(i),Ns.push(i.slice()),Ns.length>1e3&&Ns.shift(),i}function A_(i){return y(this,null,function*(){switch(HA){case 0:this.edpl.willDecodeAudio=y_;break;case 2:this.edpl.didEncodeAudio=y_;break}yield vo.create(),U.emit($.JOIN_SEND_CMD,{room:this});let t=new qp(vo,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(U.emit($.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ce({code:j.JOIN_ROOM_FAILED,extraCode:Number(e),message:Be({key:$e.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Jp},useWt:{set:WA},enableDebug:{set(i){console.debug=i?I_:()=>{},vo.setSwitchValue("enableDebug",i)}},useV2:{set:Xp},dump:{value(){if(Ns||(console.warn("dump audio will be activated at next time join room"),Ns=[]),!Ns.length){console.warn("no audio data to dump,try it later");return}let i=[];return Ns.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Gp(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;vo.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:n})=>{console.log(n),e.push(n),e.length>t&&(s.port2.onmessage=null,vo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Gp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:$t.useHardDecoder="prefer-hardware";break;case!1:$t.useHardDecoder="prefer-software";break;default:$t.useHardDecoder="no-preference"}}}});function Jp(i){return y(this,null,function*(){vo.setSwitchValue("useAINS",i)})}function Xp(i){return y(this,null,function*(){vo.setSwitchValue("useV2",i)})}function WA(i){return y(this,null,function*(){vo.setSwitchValue("useWt",i)})}function b_(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),i.player.setVolume(0),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function R_(i){return y(this,null,function*(){var o;this._log.info("pull video",i);let t=Date.now(),e=0,r=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[r.port1]),(o=i.stat).framesReceived||(o.framesReceived=0),Ae(E_(r.port2),Je(be(i,ue.INIT)),Ue(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let u=n[4]&31;if(e<=10){let p=Array.from(n.slice(0,10)).map(g=>g.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${u}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${p}`)}let m;switch(u){case 5:case 7:m="key";break;default:m="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:m,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var El=[];function C_(i){var u;let t=vt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=El.length;m++)if(!El[m]){El[m]=this,this.index=m;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(u=this.session)==null||u.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(ge(J({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,a=m=>{let p=s.getAudioTracks()[0];p&&(n.disconnect(),s.removeTrack(p)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=je("player").createMediaStreamSource(s),n.connect(fl.worklet,0,this.index)};Ae(be(i,"output-media-track-changed"),Je(be(i,"ready")),Ue(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),El[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ae(t,rc(m=>i.volume=m),Li(Ru(1e3)),Ue(()=>{i.volume=0})),a(i.outMediaTrack)}var mW=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Qp=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;l(this,"track");l(this,"label");l(this,"insertKeyFrame",!0);l(this,"session");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){return y(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e.recreateCount===0&&U.emit($.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let u=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(u.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return y(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function _l(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.640028",avc:{format:"annexb"},hardwareAcceleration:$t.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Qp(i,t.type,o,s.port2);return s.port2.onmessage=a=>{a.data===260&&(n.insertKeyFrame=!0)},this._log.info("start push",r,t),n})}function N_(i){return y(this,null,function*(){var p;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((p=i.manager)!=null&&p.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let a=yield _l.call(this,i,r);this._log.info("VideoEncoder created",r);let u,m=g=>y(this,null,function*(){if(u==null||u.abort("track changed"),!g)return;u=new AbortController;let{width:E,height:A,displaySurface:C}=g.getSettings();E&&(a.config.width=E),A&&(a.config.height=A);let N=er.match(/Chrome\/(\d+)/);(N==null?void 0:N[1])==="114"&&C==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",g.readyState,g.getSettings());let D;if(typeof MediaStreamTrackProcessor!="undefined"&&!(g instanceof CanvasCaptureMediaStreamTrack))D=new MediaStreamTrackProcessor({track:g}).readable;else{let Y;D=new ReadableStream({start(de){i.on("render",Se=>{if(i.player.mode!==0)try{de.enqueue(new VideoFrame(Se,{timestamp:performance.now()*1e3}))}catch(Ze){console.warn(Ze)}})},pull(de){return y(this,null,function*(){if(i.player.mode===0&&Br()&&i.player.element)return new Promise(Se=>{i.player.element.requestVideoFrameCallback((Ze,H)=>{try{let ke=new VideoFrame(i.player.element);de.enqueue(ke)}catch(ke){console.warn(ke)}Se()})})})}})}let x="small"in i&&i.small;return x?(this.smallEncoder||(this.smallEncoder=yield _l.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=g,this.smallEncoder.label="small",D=yield this.smallEncoder.trans(D,u,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=g,a.label=e,a.start(D,u,this)});return Ae(be(i,"output-media-track-changed"),Je(be(i,"ready")),Ue(m,console.error,()=>{var g;this._log.info("stop push",e,r),u.abort("unpublish"),a.close(),(g=this.smallEncoder)==null||g.close()})),m(i.outMediaTrack)})}var Co=class Co extends ue{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;l(this,"enableInBackground",!1);l(this,"interval",400);e.on("joined",()=>{this.emit(Co.INTERVALCHANGED,this.interval)}),Ae(be(this,Co.INTERVALCHANGED),Eo(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ae(gE(s),go(()=>[]))),Ue(s=>{s.forEach(n=>{this.room.remotePublishedUserMap.has(n.userId)&&(this.room.remotePublishedUserMap.get(n.userId).remoteAudioTrack.volume=n.volume)}),(!document.hidden||this.enableInBackground)&&this.state==ue.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Co.INTERVALCHANGED,this.interval)}stop(){}};l(Co,"INTERVALCHANGED","intervalChanged"),ee([Ke([ue.INIT,ue.OFF],ue.ON)],Co.prototype,"start",1),ee([Ke([],ue.OFF)],Co.prototype,"stop",1);var Tl=Co;var No=class No extends ml{constructor(e){super(e);l(this,"index",0);l(this,"session");l(this,"tinyid");l(this,"roomid");l(this,"openid");l(this,"socketid");l(this,"relayip");l(this,"clientip");l(this,"remotePublishedUserMap",new Map);l(this,"bussinessInfo");l(this,"token");l(this,"audioVolumeEvalution",new Tl(this));l(this,"enableAIVoice",Jp);l(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Tm(),uint32_device_type:0,str_os_verion:Im(),uint32_link_type:1,str_client_version:lt,uint32_net_type:Bo[ei.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Xp(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return y(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){this.session&&(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let n=new MessageChannel;this.postMessage({cmd:e,payload:r},[n.port1]),n.port2.onmessageerror=s,n.port2.onmessage=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return y(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return y(this,null,function*(){var u,m,p;let s=ei.getEnv(),n=qd(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(u=this.proxy_wt)==null?void 0:u.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(p=this.scheduleResult.iceServers)!=null&&p.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:ln(),browserInfo:qd(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:lt,browserVersion:n.browserName+n.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield A_.call(this,a),console.log(this),fl.playAudio(g=>this.postMessage({cmd:"setAudioWorkletPort"},[g])),this.checkDestroy()})}leave(){return y(this,null,function*(){this.remotePublishedUserMap.forEach(e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((e,r)=>r.unpublish()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return y(this,null,function*(){let e=Je(be(this,"left"));Ae(r=>y(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,Ue(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(ge(J({},r),{data:new Uint8Array(s.data)}),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case $.RECEIVED_PUBLISHED_USER_LIST:U.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new sl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let g=r,E=this.remotePublishedUserMap.get(g);E&&(E.remoteVideoTrack.close(),E.remoteAuxiliaryTrack.close(),E.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(g),this.emit("remote-unpublished",E))}return;case"banned":switch(r){case 8:this.emit("banned",{reason:"kick",message:""});return;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});return;case 7:case 5:this.emit("banned",{reason:"room_disband",message:""});return}break;case"6":{let{prevMuteState:g,muteState:E,flag:A}=r,C=this.remotePublishedUserMap.get(E.userId);if(!C){this.emit("remote-publish-state-changed",r);return}C.flag=A}U.emit($.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:u,msg_down_stream_info:m}=r,p={str_sdk_version:lt,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Bo[aa()]},msg_event_msg:TE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:m};U.emit($.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),U.emit($.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:u}),delete r.downlinkInfo;break;case"signal-connection-state-changed":U.emit($.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return y(this,null,function*(){e.forEach(a=>this.localTracks.add(a));let r=e.reduce((a,u)=>u.mediaType|a,0),o=this.sendMessage("publish",r).then(a=>a.err!==0?Promise.reject(a.err):a),s=0,n=a=>y(this,null,function*(){switch(yield o,a.muted&&(s|=a.mediaType),Lt(a,a).add("mute",()=>{this.postMessage("mute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),a.mediaType){case 1:C_.call(this,a);break;default:yield N_.call(this,a)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return y(this,null,function*(){e.forEach(Tt),e.forEach(r=>this.localTracks.delete(r))})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((g,E)=>E.mediaType|g,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),u=J({},a.subscribeState),m=Object.assign(new va,u);m.mediaType|=r,U.emit($.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:m});let p=yield this.sendMessage("subscribe",{mediaType:m.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(g=>m.mediaType&g).map(g=>({mediaType:g,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",p),yield Promise.all(e.filter(g=>!g.isSubscribed).map(g=>{switch(g.mediaType){case 1:return b_.call(this,g);default:return R_.call(this,g)}})),U.emit($.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let a of e)a.unsubscribe();U.emit($.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return y(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield _l.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(a=>s&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};ee([po(No.prototype.afterJoin),Ke(["left",ue.INIT],"joined"),n_()],No.prototype,"join",1),ee([Ke("joined","left",{ignoreError:!0}),a_()],No.prototype,"leave",1),ee([ls(),c_()],No.prototype,"publish",1),ee([ls(),d_()],No.prototype,"unpublish",1),ee([sE((...e)=>e[0].userId),u_()],No.prototype,"subscribe",1);var Il=No;Ln.frameWorkType=37;Ln.create=function(i){let t=Ln._create.call(this,Il,i);return t._use(gp,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&($t.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",lt,"created",$t),t};Object.assign(Ln.prototype,{_setCurrentSpeaker(i){let t=je("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(gp.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{Ae(be(i,"decode-downgrade-state-changed"),Yt(o=>o.state==="STARTED"),Gr(1),rp(1e4),Je(be(i,ue.INIT)),Ue(e,r))})})}});Ym(37);var VG=Ln;export{VG as default};
|