trtc-sdk-v5 5.13.0-wasm.4 → 5.13.0-wasm.5
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
|
-
`,z.push(he);var ve,fe,we=vc(Function,z).apply(null,Y);return ve=we,fe=ws.length,ws.push(ve),W=fe,Ms[B]=W,W},f:()=>{cr("")},c:Bn,t:(S,T,w)=>D.copyWithin(S,T,T+w),s:S=>{D.length,cr("OOM")},i:(S,T,w,P)=>{for(var B,W,z,Y=0,re=0;re<w;re++){var G=Se[T>>2],he=Se[T+4>>2];T+=8;for(var De=0;De<he;De++)B=S,W=D[G+De],z=void 0,z=Pc[B],W===0||W===10?((B===1?g:_)(Uo(z,0)),z.length=0):z.push(W);Y+=he}return Se[P>>2]=Y,0}},Ar=(function(){var S,T,w,P,B={a:kc};function W(z,Y){var re,G,he=z.exports;return A=(C=he).v,re=A.buffer,o.HEAP8=N=new Int8Array(re),o.HEAP16=O=new Int16Array(re),o.HEAP32=ue=new Int32Array(re),o.HEAPU8=D=new Uint8Array(re),o.HEAPU16=Z=new Uint16Array(re),o.HEAPU32=Se=new Uint32Array(re),o.HEAPF32=Ye=new Float32Array(re),o.HEAPF64=H=new Float64Array(re),Pe=C.z,G=C.w,Pn.unshift(G),function(){if(Br--,o.monitorRunDependencies&&o.monitorRunDependencies(Br),Br==0&&(bs!==null&&(clearInterval(bs),bs=null),Bi)){var De=Bi;Bi=null,De()}}(),he}if(Br++,o.monitorRunDependencies&&o.monitorRunDependencies(Br),o.instantiateWasm)try{return o.instantiateWasm(B,W)}catch(z){_("Module.instantiateWasm callback failed with error: "+z),r(z)}(S=p,T=ci,w=B,P=function(z){W(z.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ie(T)||typeof fetch!="function"?Hr(T,w,P):fetch(T,{credentials:"same-origin"}).then(z=>WebAssembly.instantiateStreaming(z,w).then(P,function(Y){return _("wasm streaming compile failed: "+Y),_("falling back to ArrayBuffer instantiation"),Hr(T,w,P)}))).catch(r)}(),S=>(Ar=C.x)(S)),Zi=S=>(Zi=C.y)(S),Os=S=>(Os=C.A)(S),Lc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=C.B)(),S=>(Lc=C.C)(S));o.dynCall_jiji=(S,T,w,P,B)=>(o.dynCall_jiji=C.D)(S,T,w,P,B);function Uc(){function S(){Vt||(Vt=!0,o.calledRun=!0,On||(ui(Pn),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(),kn.unshift(T);var T;ui(kn)}()))}Br>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),xn.unshift(T);var T;ui(xn)}(),Br>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Bi=function S(){Vt||Uc(),Vt||(Bi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Uc(),t.ready}})();var Ry="web.sdk.qcloud.com",vy=`https://${Ry}/trtc/webrtc/v5/doc`,Kx=`${vy}/zh-cn/`,lE=(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))(lE||{});var mE={"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}},eP=mE["480p_2"],tP=mE["120p_2"],Du={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"},rP=Du.MAIN,iP=Du.AUXILIARY,oP=Du.BIG,sP=Du.SMALL;var nP=Object.keys(lE);var Cy=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())})},tp=Symbol(32),rp=Symbol(16),ip=Symbol(8),Kh=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 Cy(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(tp)}readU16(){return this.read(rp)}readU8(){return this.read(ip)}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===tp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===rp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===ip){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}};Kh.U32=tp,Kh.U16=rp,Kh.U8=ip;var Ny=127,aP=~Ny,cP=Math.pow(2,31),dP=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},uP=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function aE(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:lP}=Object.prototype,hE=class pE{constructor(t){this.core=t,$r(this,"contextMap",new Map),$r(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 pE.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new by(vu(Ru({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Rn;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(vu(Ru({},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(vu(Ru({},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)}};$r(hE,"Name","TRTCVideoDecoder");var op=hE;var GE=pi(bi());function sp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Oe((r,o)=>{let s=new WeakMap;return V.on(F.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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.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 Dy="2025-08-27 15:26:30",fE=!0,gE=function(){var i;if(fE){fE=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${qr}/en/index.html`),console.info(`* Changelog: ${qr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",at),xr||$.debug("Build Time:",Dy);let t=`UA: ${navigator.userAgent}
|
|
92
|
+
`,z.push(he);var ve,fe,we=vc(Function,z).apply(null,Y);return ve=we,fe=ws.length,ws.push(ve),W=fe,Ms[B]=W,W},f:()=>{cr("")},c:Bn,t:(S,T,w)=>D.copyWithin(S,T,T+w),s:S=>{D.length,cr("OOM")},i:(S,T,w,P)=>{for(var B,W,z,Y=0,re=0;re<w;re++){var G=Se[T>>2],he=Se[T+4>>2];T+=8;for(var De=0;De<he;De++)B=S,W=D[G+De],z=void 0,z=Pc[B],W===0||W===10?((B===1?g:_)(Uo(z,0)),z.length=0):z.push(W);Y+=he}return Se[P>>2]=Y,0}},Ar=(function(){var S,T,w,P,B={a:kc};function W(z,Y){var re,G,he=z.exports;return A=(C=he).v,re=A.buffer,o.HEAP8=N=new Int8Array(re),o.HEAP16=O=new Int16Array(re),o.HEAP32=ue=new Int32Array(re),o.HEAPU8=D=new Uint8Array(re),o.HEAPU16=Z=new Uint16Array(re),o.HEAPU32=Se=new Uint32Array(re),o.HEAPF32=Ye=new Float32Array(re),o.HEAPF64=H=new Float64Array(re),Pe=C.z,G=C.w,Pn.unshift(G),function(){if(Br--,o.monitorRunDependencies&&o.monitorRunDependencies(Br),Br==0&&(bs!==null&&(clearInterval(bs),bs=null),Bi)){var De=Bi;Bi=null,De()}}(),he}if(Br++,o.monitorRunDependencies&&o.monitorRunDependencies(Br),o.instantiateWasm)try{return o.instantiateWasm(B,W)}catch(z){_("Module.instantiateWasm callback failed with error: "+z),r(z)}(S=p,T=ci,w=B,P=function(z){W(z.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ie(T)||typeof fetch!="function"?Hr(T,w,P):fetch(T,{credentials:"same-origin"}).then(z=>WebAssembly.instantiateStreaming(z,w).then(P,function(Y){return _("wasm streaming compile failed: "+Y),_("falling back to ArrayBuffer instantiation"),Hr(T,w,P)}))).catch(r)}(),S=>(Ar=C.x)(S)),Zi=S=>(Zi=C.y)(S),Os=S=>(Os=C.A)(S),Lc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=C.B)(),S=>(Lc=C.C)(S));o.dynCall_jiji=(S,T,w,P,B)=>(o.dynCall_jiji=C.D)(S,T,w,P,B);function Uc(){function S(){Vt||(Vt=!0,o.calledRun=!0,On||(ui(Pn),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(),kn.unshift(T);var T;ui(kn)}()))}Br>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),xn.unshift(T);var T;ui(xn)}(),Br>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Bi=function S(){Vt||Uc(),Vt||(Bi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Uc(),t.ready}})();var Ry="web.sdk.qcloud.com",vy=`https://${Ry}/trtc/webrtc/v5/doc`,Kx=`${vy}/zh-cn/`,lE=(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))(lE||{});var mE={"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}},eP=mE["480p_2"],tP=mE["120p_2"],Du={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"},rP=Du.MAIN,iP=Du.AUXILIARY,oP=Du.BIG,sP=Du.SMALL;var nP=Object.keys(lE);var Cy=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())})},tp=Symbol(32),rp=Symbol(16),ip=Symbol(8),Kh=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 Cy(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(tp)}readU16(){return this.read(rp)}readU8(){return this.read(ip)}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===tp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===rp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===ip){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}};Kh.U32=tp,Kh.U16=rp,Kh.U8=ip;var Ny=127,aP=~Ny,cP=Math.pow(2,31),dP=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},uP=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function aE(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:lP}=Object.prototype,hE=class pE{constructor(t){this.core=t,$r(this,"contextMap",new Map),$r(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 pE.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new by(vu(Ru({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Rn;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(vu(Ru({},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(vu(Ru({},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)}};$r(hE,"Name","TRTCVideoDecoder");var op=hE;var GE=pi(bi());function sp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Oe((r,o)=>{let s=new WeakMap;return V.on(F.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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.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 Dy="2025-08-28 10:51:13",fE=!0,gE=function(){var i;if(fE){fE=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${qr}/en/index.html`),console.info(`* Changelog: ${qr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",at),xr||$.debug("Build Time:",Dy);let t=`UA: ${navigator.userAgent}
|
|
93
93
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${dm()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),$.info(t),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Qo().then(r=>{r&&$.info(Dr)})}};var _s={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 se={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},Tr=(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.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))(Tr||{});function _E({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Tr[i];try{o=EE[s]}catch(n){o=EE.UNKNOWN_ERROR}return Ge(o)?r=o(t):Ne(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var EE=ge(X({},Yt),{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: ${ct(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: ${ct(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=Ts(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=Ts(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=Ts(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=Ts(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=Ts(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=Ts(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=Ts(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 Ts(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var np=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=_E({code:e===se.SERVER_ERROR?e:r||e,params:X({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=Tr[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"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},A=document.createElement("a");Xo?A.href=`ms-settings:privacy-${_[this.functionName]}`:Mr&&(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 de){let{stack:n}=e,a={code:se.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:a.code=se.INVALID_PARAMETER,a.message=e.message;break;case q.INVALID_OPERATION:a.code=se.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:a.code=se.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Yt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:case q.SWITCH_ROOM_FAILED:a.code=se.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:a.code=se.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=wy(e.name));break;case q.VIDEO_ENCODE_FAILED:a.extraCode=5505;case q.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=se.OPERATION_FAILED;break;case q.UNKNOWN:break;default:a.code=se.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:se.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function wy(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 oe=np;function oi(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function sc(i){return i===_s.QOS_PREFERENCE_CLEAR?"detail":i===_s.QOS_PREFERENCE_SMOOTH?"motion":""}function vn(i,t){let e=t?Nl:Qn;return Jl(i)?X(X({},e),i):vr[i]?vr[i]:e}var TE={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}}},IE={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}}},Cn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Ne(i)&&!document.getElementById(i))throw new oe({code:se.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},SE={name:"userId",required:!0,type:"string"},yE={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:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Nn(i,t){if(!i)throw new oe({code:se.INVALID_OPERATION,extraCode:5101,fnName:t})}function AE(i,t,e){if(!i)throw new oe({code:se.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function bE(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new oe({code:se.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function RE(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new oe({code:se.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var kk={type:"number",notLessThanZero:!0},My=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function vE(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!Ud()){$.warn("small stream is not supported"),delete i.option.small;return}let t=vn(i.option.profile),e=vn(i.option.small,!0);if(!My(t,e)){$.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 Oy={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 oe({code:se.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Ne(i.roomId))throw new oe({code:se.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});bE(i.roomId,e,t)}else if(i.strRoomId)RE(i.strRoomId,e,t);else throw new oe({code:se.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:Cn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:TE},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&vE(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ge(X({},Cn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:TE},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&vE(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:yE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:yE}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Cn,publish:{type:"boolean"},option:IE},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ma())throw new oe({code:se.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Cn,publish:{type:"boolean"},option:IE}},muteRemoteAudio:[SE,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[SE,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Cn,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){Nn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(AE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:se.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ge(X({},Cn),{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){Nn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(AE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:se.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!=="*"&&x(i.streamType))throw new oe({code:se.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Nn(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(!xa)throw new oe({code:se.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:se.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:se.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:se.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Nn(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 oe({code:se.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 oe({code:se.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:se.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Nn(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:se.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(Nn(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new oe({code:se.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 oe({code:se.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)bE(i.roomId,e,t);else if(i.strRoomId)RE(i.strRoomId,e,t);else throw new oe({code:se.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}}}},Ct={TRTC:Oy};var Gt=class extends Error{};function xy(i,t){let e=Wo(i);for(let r=0;r<t.length;r++)Nr(e[r],t[r]);return e}function Py(i){this._resolve=Promise.resolve(i)}function ky(i){this._reject=Promise.reject(i)}var So=class So{constructor(t,e){this.instance=t;this.group=e;l(this,"started",!1);l(this,"ops",[]);l(this,"startSame",()=>!0);l(this,"mergeUpdate",xy);let r=So.instances.get(t);r?r.set(e,this):So.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=So.instances.get(t);return r&&r.get(e)||new So(t,e)}static gets(t,e){let r=So.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 Gt("start failed")),(m=this.currentOp)==null||m.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:Py,reject:ky};try{switch(this.state){case 1:if(t===0)throw new Gt("already started");break;case 4:if(t===2)throw new Gt("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 Gt("already start");break;case 3:switch(t.type){case 2:throw new Gt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Gt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Gt("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 Gt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Gt("start not allowed after update");case 0:throw new Gt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Gt("keep start")),new Gt("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(So,"instances",new WeakMap);var Vi=So;var wu=new WeakMap,Mu=(i,t)=>{if(t instanceof Gt){let{stack:e}=t;t=new oe({code:se.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
95
95
|
`)))}throw t};function yo(i,t){return Oe((e,r)=>function(...o){let s=Vi.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(Mu.bind(null,r))):e.apply(this,o)})}function Is(i,t){let{merge:e,debounce:r}=t||{};return Oe((o,s)=>function(...n){let a=Vi.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 _=(C=wu.get(this))==null?void 0:C.get(m(...n));if(_){let{timeoutId:D,resolve:O}=_;clearTimeout(D),O()}let A=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(Mu.bind(null,s)).then(p,g)},u);wu.has(this)?(N=wu.get(this))==null||N.set(m(...n),{timeoutId:A,resolve:p}):wu.set(this,new Map([[m(...n),{timeoutId:A,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(Mu.bind(null,s))})}function Ao(i){return Oe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Vi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Vi.get(this,o);return s?s.action(3,t.bind(this),r).catch(Mu.bind(null,e)):t.apply(this,r)})}var te={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"},CE=new Set([te.ERROR,te.AUTOPLAY_FAILED,te.KICKED_OUT,te.REMOTE_USER_ENTER,te.REMOTE_USER_EXIT,te.REMOTE_AUDIO_AVAILABLE,te.REMOTE_AUDIO_UNAVAILABLE,te.REMOTE_VIDEO_AVAILABLE,te.REMOTE_VIDEO_UNAVAILABLE,te.CONNECTION_STATE_CHANGED,te.PUBLISH_STATE_CHANGED,te.SCREEN_SHARE_STOPPED,te.DEVICE_CHANGED,te.FIRST_VIDEO_FRAME,te.PERMISSION_STATE_CHANGE,te.VIDEO_SIZE_CHANGED]);var up={};hi(up,{ScheduleRequestType:()=>DE,getAbilityConfig:()=>Uy,getScheduleDomain:()=>Pu,isNeedToSchedule:()=>Ou,scheduleProxy:()=>si,sendScheduleRequest:()=>dp,setIsNeedToSchedule:()=>Ss,setScheduleProxy:()=>xu});var cp=null,Ou=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ei).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
96
96
|
`));function Ss(i){Qe(i)&&i!==Ou&&(Ou=i,$.info(`setIsNeedToSchedule ${i}`))}V.on("28",()=>Ss(!0));V.on("63",()=>Ss(!0));V.on("84",()=>Ss(!0));V.on("201",i=>{i.state==="RECONNECTING"&&Ss(!0)});V.on("202",i=>{i.state==="RECONNECTING"&&Ss(!0)});function Ly(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=bo(i,"config",M.MAIN),n=bo(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,_=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),O=Math.round(a.responseEnd-a.responseStart),Z=[A,C,N,D,O];He.uploadEvent({log:`stat-schedule-net:${m}(${p}(${g}->${_})->${Z.join("->")}) ${u}`,userId:t}),r=ge(X({},r),{totalCost:m,local:p,dns:A,tcp:N,tls:C,request:D,response:O});break}}catch(o){$.error("getScheduleDetailCost error",o)}return r}function dp(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:a,latencyLevel:u}){if(!Ou&&cp)return{isCached:!0,result:cp};let p={delta:0,count:[1,1],msg:[],detail:[]};try{let g=new FormData;g.append("userId",String(i)),g.append("sdkAppId",String(t)),g.append("isStrGroupId",String(e)),g.append("groupId",String(r)),g.append("sdkVersion",s),g.append("userSig",String(o));let _=yield Qo();_!=null&&_.model&&g.append("model",String(_==null?void 0:_.model)),a&&g.append("role",String(a)),u&&g.append("latencyLevel",String(u)),n&&g.append("frameWorkType",String(n));let A=_e(),C=yield Fy(g,p,t);C.config&&(C.config.loggerDomain&&Fo(C.config.loggerDomain),Qe(C.config.scheduleCache)&&Ss(!C.config.scheduleCache)),p.delta=_e()-A;let N=Ly(Number(t),i,A);return cp=C,{isCached:!1,result:C,detailCost:N}}catch(g){let _=st(g)?g[0]:g,A=ke(_.code)?_.code:0,C=`schedule failed${_.message?`: ${_.message}`:""}`,N=new de({code:q.SCHEDULE_FAILED,extraCode:A,message:$e({key:Fe.JOIN_ROOM_FAILED,data:{error:C,code:A}})});throw $.error(C,A),N}})}var si={main:"",backup:""};function xu(i){st(i)?(si.main=i[0],si.backup=i[1]):si.main=i}var DE=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(DE||{});function bo(i,t,e=M.MAIN,r=!1){return`https://${si[e]||Pu(i,e,r)}/api/v1/${t}`}function Uy(i,t,e){let r=bo(i,t),o=bo(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 oa([n,a])}function Pu(i,t=M.MAIN,e=!1){let r;return _i(i)?e?r=t===M.MAIN?Ei.MAIN_OVERSEA_BACKUP:Ei.BACKUP_OVERSEA:r=t===M.MAIN?Ei.MAIN_OVERSEA:Ei.BACKUP_OVERSEA:r=t===M.MAIN?Ei.MAIN:Ei.BACKUP,r}function Vy(i,t,e){return new Promise((r,o)=>{Si({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 NE=(i,t)=>so({retryFunction:Vy,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function Fy(i,t,e){return new Promise((r,o)=>{let s=null;oa([NE(n=>t.count[0]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(u>=1&&(m[0]=bo(e,"config",M.MAIN,!0)),a())})(bo(e,"config",M.MAIN),i,{get timeout(){return Go(2+t.count[0])*1e3}}),NE(n=>t.count[1]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(u>=2&&(m[0]=bo(e,"config",M.BACKUP,!0)),a())})(bo(e,"config",M.BACKUP),i,{get timeout(){return Go(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var $y=i=>i.startsWith("data:application/octet-stream;base64,"),By=i=>i.startsWith("file://"),nc=class{constructor(){l(this,"_log");this._log=$.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=zo(t);try{let o=_e(),s;if(Ge(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=_e()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:_e()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Q.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=_e(),o=null,s=null;if(Ge(WebAssembly.instantiateStreaming)&&!$y(t)&&!By(t)&&Ge(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=_e()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Q.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Q.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=_e();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${_e()-e}ms`),Q.addSuccessEvent({key:522702,cost:_e()-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)}`),Q.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([ns({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}`)}})],nc.prototype,"download",1),ee([ns({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],nc.prototype,"loadScript",1);var lp=new nc;function wE({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:gs,LocalVideoTrack:ar,LocalScreenTrack:ri,room:t,assetsPath:r,fileDownloader:lp,innerEmitter:V,INNER_EVENT:F,constants:Ol,environment:nn,utils:Jh,eventLogger:He,log:this.room.getLogger(),loggerManager:$,errorModule:e,kvStatManager:Q,rtcDectection:lo,trtc:this,rx:jh,enums:Dm,schedule:up,getDevices:pn,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>y(this,null,function*(){window.VisionTaskRegistry||(yield lp.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:We(),deviceDetector:rt,AudioPlayer:gn,AutoPlayDialog:Wd,Timer:dt,clearStarted:(o,s)=>{let n=o.getAlias(),a=Vi.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:tc,createAudioNode:Ha,getNetworkTimeOffset:qp}}var ME=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=$e({key:Fe.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return $.warn(`${s}
|
|
97
97
|
|
|
98
|
-
${o.stack}`),!1}},i};var Dn=new WeakMap;function OE(i){let t=Dn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Dn.delete(i))}function xE(i,t){return Oe((e,r)=>function(...o){let s=Dn.get(this);s||(s=new Map,Dn.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=Dn.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=Dn.get(this))==null||m.delete(n)},i);s.set(n,u)}})}var kE="trtc-sdk-v5",LE="5.13.0-wasm.4";function xt(...i){return Oe((t,e)=>function(...r){try{Lu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function mp(...i){return Oe((t,e)=>function(...r){try{Lu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function Lu(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)ku.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else ku.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function ku({rule:i,value:t,key:e,fnName:r,className:o}){function s(u){return{code:se.INVALID_PARAMETER,extraCode:u,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(x(t)){if(i.required)throw new oe(s(5001));if(x(i.defaultValue)){Ge(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),Ge(i.type[m])&&t instanceof i.type[m]&&(u=!0),Ne(i.type[m])&&ct(t)===i.type[m].toLowerCase()&&(u=!0);if(!u)throw new oe({code:se.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>jo(m)?Hs(m):Ne(m)?m:ct(m))},value:t}})}else if(!x(i.type)&&ct(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let u=ke(t)&&(t===0||Number.isNaN(t)),m=Ne(t)&&t.trim()==="";if(u||m)throw new oe(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new oe(s(5006));if(!x(i.min)&&ke(t)&&t<i.min)throw new oe(s(5007));if(!x(i.max)&&ke(t)&&t>i.max)throw new oe(s(5008));if(Ne(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Ge(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:n}=i;Bt(n)&&ir(t)&&Object.keys(n).forEach(u=>{ku.call(this,{rule:n[u],value:t&&t[u],key:`${u}`,fnName:r,className:o})});let{arrayItem:a}=i;Bt(a)&&st(t)&&t.forEach((u,m)=>{ku.call(this,{rule:a,value:u,key:`${e}[${m}]`,fnName:r,className:o})}),Ge(i.validate)&&i.validate.call(this,t,e,r,o,this)}function tt(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,O,Z){if(Z&&Z.includes(D))return"hided";if(e){let ue=e(...u);if(u[ue.argIndex]===O)return ue.value}if(O===u||D in u)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${ct(O)}`:O instanceof MediaStreamTrack?td(O):(JSON.stringify(O),O)}catch(ue){return`type:${ct(O)}`}}let p=this._log||$;if(o!=null&&o(...u))return n.apply(this,u);u.length>0?p.info(`${a}() ${JSON.stringify(u,(D,O)=>m(D,O,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let g=r?r(...u):Md[a],_=(s==null?void 0:s(...u))||!1;try{let D=n.apply(this,u),O=_e();if(io(D)){let Z=`${a.includes("Plugin")?`${((C=(A=u[0]).getName)==null?void 0:C.call(A))||""} `:" "}`;return D.then(ue=>(p.info(`${a}() success ${Z}${t.call(this,...u)}`),Q.addSuccessEvent({key:g,cost:_e()-O}),ue)).catch(ue=>{var H;ue=oe.convertFrom.call(this,ue,a,u.length===1?u[0]:u);let Se=ue.extraCode||ue.code,Ye=(H=ue.message)!=null&&H.includes(Se)?"":` code:${Se}`;throw _||p.error(`${a}() failed ${Z}${t.call(this,...u)} ${ue}${Ye} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:ue}),ue})}return Q.addSuccessEvent({key:g}),D}catch(D){D=oe.convertFrom.call(this,D,a);let O=D.extraCode||D.code,Z=(N=D.message)!=null&&N.includes(O)?"":` code:${O}`;throw _||p.error(`${a}() failed ${D}${Z} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:D}),D}})}var Uu=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 oe({code:se.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Ge(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:se.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return Lu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Vu=0,hp,Fi=class Fi{constructor(t){this.core=t;l(this,"log");l(this,"customAudioReferenceMap",new Map);l(this,"audioRefId",0);l(this,"audioContext",We());l(this,"localAudioWorkletNode");l(this,"screenAudioWorkletNode");l(this,"mixNode");l(this,"silentNode");Vu=Vu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Vu}`}),this.log.info(`created id=${this.getAlias()}${Vu}`),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 oe({code:se.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return hp||(hp=this.doPreload(t)),hp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield xi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Fi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Fi.getStartValidateRule(this.core);case"update":return Fi.updateValidateRule;case"stop":return Fi.stopValidateRule}}start(t){return y(this,null,function*(){var _,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 oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:D,status:O,timestamp:Z}=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,Z,D,O,e)}if(g&&!this.screenAudioWorkletNode){let{sign:D,status:O,timestamp:Z}=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,Z,D,O,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()),(_=this.localAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),x(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),x(u)||(C=this.localAudioWorkletNode)==null||C.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),x(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;x(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++}`})})),x(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),x(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 Wy({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${u}`),new oe({code:se.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 _=(p==null?void 0:p.value)>10?"info":"debug";this.log[_](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Ps(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":V.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(Fi,"updateValidateRule",{type:"object"}),l(Fi,"stopValidateRule",{type:"object"}),l(Fi,"Name","AudioProcessor");var Fu=Fi;function Hy(i,t=M.MAIN){return`https://${si[t]||Pu(i,t)}/api/v1/audioAiAuth`}function Wy(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${Hy(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 _=_i(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: ${_}`;break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C=`Your packages is not active. Refer to: ${_}`;break;case 5:C=`Your packages is expired. Refer to: ${_}`;break;case 6:C="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${A} Reason: ${m}. ${C}`:`${A}, ${C}`}})}var $u=0,pp=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new hn(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&&(x(t.volume)||(this.volume=t.volume),x(t.loop)||(this.loop=t.loop),x(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)}}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(t=this.publisher)==null||t.play(),(e=this.player)==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 wn(i,t){if(t&&typeof t!="function")throw new oe({code:se.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var ni=class ni{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);$u=$u+1,this.log=t.log.createChild({id:`${this.getAlias()}${$u}`}),this.log.info(`created id=${this.getAlias()}${$u}`)}getName(){return ni.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ni.startValidateRule;case"update":return ni.updateValidateRule;case"stop":return ni.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;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 pp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),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.`),Q.addEnum({key:502700,value:3}),this.kvUpload(t)})}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),x(r)||n.setOperation(r),x(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&&Q.addCount({key:502711}),r&&Q.addCount({key:502703}),o&&Q.addCount({key:502704}),s&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),a&&Q.addCount({key:502707}),typeof u!="function"&&Q.addCount({key:502709}),typeof p!="function"&&Q.addCount({key:502710}),typeof m!="function"&&Q.addCount({key:502708})}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(ni,"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 oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});wn("onTimeUpdate",t.onTimeUpdate),wn("onEnded",t.onEnded),wn("onDurationChange",t.onDurationChange)}}),l(ni,"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){wn("onTimeUpdate",t.onTimeUpdate),wn("onEnded",t.onEnded),wn("onDurationChange",t.onDurationChange)}}),l(ni,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(ni,"Name","AudioMixer");var Bu=ni;var Hu=0,fp,$i=class $i{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",We("denoiser"));l(this,"workletNode");Hu=Hu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Hu}`}),this.log.info(`created id=${this.getAlias()}${Hu}`)}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}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:se.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return fp||(fp=this.doPreload(t)),fp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield xi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return $i.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return $i.startValidateRule(this.core);case"update":return $i.updateValidateRule;case"stop":return $i.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 oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${o}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:u,message:m}=yield jy(r,ge(X({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new oe({code:se.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 _;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}(${Ps(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}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)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};l($i,"updateValidateRule",{type:"object"}),l($i,"stopValidateRule",{type:"object"}),l($i,"Name","AIDenoiser");var Wu=$i;function jy(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=_i(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="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?`${_} Reason: ${u}. ${A}`:`${_}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var VE=pi(bi(),1);var gp=class extends VE.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&&!pt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){He.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)&&$.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){He.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qy=new gp,Ep=qy;function zy([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 ms(new DataView(new Uint8Array(s).buffer),!0)}function Jy(i){return i.type==="empty"||i.data.byteLength===0}function Xy(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function Qy(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 _p({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-Qy(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(zy),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 Tp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(Jy(i)||!Xy(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 ms(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 Ip=0,ac=class ac{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Ip++,this.log=t.log.createChild({id:`${this.getAlias()}${Ip}`}),this.log.info(`[sei] created id=${this.getAlias()}${Ip}`),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 _p({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Tp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(te.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:os?this.encode:_p,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:os?this.decode:Tp,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 ac.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(ac,"autoStart",!0),l(ac,"Name","SEI");var Gu=ac;function Sp({frame:i,onDump:t}){return t==null||t(),i}function yp({frame:i,onDump:t}){return t==null||t(),i}var FE={"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 Dn=new WeakMap;function OE(i){let t=Dn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Dn.delete(i))}function xE(i,t){return Oe((e,r)=>function(...o){let s=Dn.get(this);s||(s=new Map,Dn.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=Dn.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=Dn.get(this))==null||m.delete(n)},i);s.set(n,u)}})}var kE="trtc-sdk-v5",LE="5.13.0-wasm.5";function xt(...i){return Oe((t,e)=>function(...r){try{Lu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function mp(...i){return Oe((t,e)=>function(...r){try{Lu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function Lu(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)ku.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else ku.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function ku({rule:i,value:t,key:e,fnName:r,className:o}){function s(u){return{code:se.INVALID_PARAMETER,extraCode:u,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(x(t)){if(i.required)throw new oe(s(5001));if(x(i.defaultValue)){Ge(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),Ge(i.type[m])&&t instanceof i.type[m]&&(u=!0),Ne(i.type[m])&&ct(t)===i.type[m].toLowerCase()&&(u=!0);if(!u)throw new oe({code:se.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>jo(m)?Hs(m):Ne(m)?m:ct(m))},value:t}})}else if(!x(i.type)&&ct(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let u=ke(t)&&(t===0||Number.isNaN(t)),m=Ne(t)&&t.trim()==="";if(u||m)throw new oe(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new oe(s(5006));if(!x(i.min)&&ke(t)&&t<i.min)throw new oe(s(5007));if(!x(i.max)&&ke(t)&&t>i.max)throw new oe(s(5008));if(Ne(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Ge(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:n}=i;Bt(n)&&ir(t)&&Object.keys(n).forEach(u=>{ku.call(this,{rule:n[u],value:t&&t[u],key:`${u}`,fnName:r,className:o})});let{arrayItem:a}=i;Bt(a)&&st(t)&&t.forEach((u,m)=>{ku.call(this,{rule:a,value:u,key:`${e}[${m}]`,fnName:r,className:o})}),Ge(i.validate)&&i.validate.call(this,t,e,r,o,this)}function tt(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,O,Z){if(Z&&Z.includes(D))return"hided";if(e){let ue=e(...u);if(u[ue.argIndex]===O)return ue.value}if(O===u||D in u)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${ct(O)}`:O instanceof MediaStreamTrack?td(O):(JSON.stringify(O),O)}catch(ue){return`type:${ct(O)}`}}let p=this._log||$;if(o!=null&&o(...u))return n.apply(this,u);u.length>0?p.info(`${a}() ${JSON.stringify(u,(D,O)=>m(D,O,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let g=r?r(...u):Md[a],_=(s==null?void 0:s(...u))||!1;try{let D=n.apply(this,u),O=_e();if(io(D)){let Z=`${a.includes("Plugin")?`${((C=(A=u[0]).getName)==null?void 0:C.call(A))||""} `:" "}`;return D.then(ue=>(p.info(`${a}() success ${Z}${t.call(this,...u)}`),Q.addSuccessEvent({key:g,cost:_e()-O}),ue)).catch(ue=>{var H;ue=oe.convertFrom.call(this,ue,a,u.length===1?u[0]:u);let Se=ue.extraCode||ue.code,Ye=(H=ue.message)!=null&&H.includes(Se)?"":` code:${Se}`;throw _||p.error(`${a}() failed ${Z}${t.call(this,...u)} ${ue}${Ye} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:ue}),ue})}return Q.addSuccessEvent({key:g}),D}catch(D){D=oe.convertFrom.call(this,D,a);let O=D.extraCode||D.code,Z=(N=D.message)!=null&&N.includes(O)?"":` code:${O}`;throw _||p.error(`${a}() failed ${D}${Z} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:D}),D}})}var Uu=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 oe({code:se.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Ge(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:se.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return Lu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Vu=0,hp,Fi=class Fi{constructor(t){this.core=t;l(this,"log");l(this,"customAudioReferenceMap",new Map);l(this,"audioRefId",0);l(this,"audioContext",We());l(this,"localAudioWorkletNode");l(this,"screenAudioWorkletNode");l(this,"mixNode");l(this,"silentNode");Vu=Vu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Vu}`}),this.log.info(`created id=${this.getAlias()}${Vu}`),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 oe({code:se.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return hp||(hp=this.doPreload(t)),hp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield xi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Fi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Fi.getStartValidateRule(this.core);case"update":return Fi.updateValidateRule;case"stop":return Fi.stopValidateRule}}start(t){return y(this,null,function*(){var _,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 oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:D,status:O,timestamp:Z}=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,Z,D,O,e)}if(g&&!this.screenAudioWorkletNode){let{sign:D,status:O,timestamp:Z}=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,Z,D,O,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()),(_=this.localAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),x(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),x(u)||(C=this.localAudioWorkletNode)==null||C.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),x(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;x(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++}`})})),x(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),x(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 Wy({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${u}`),new oe({code:se.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 _=(p==null?void 0:p.value)>10?"info":"debug";this.log[_](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Ps(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":V.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(Fi,"updateValidateRule",{type:"object"}),l(Fi,"stopValidateRule",{type:"object"}),l(Fi,"Name","AudioProcessor");var Fu=Fi;function Hy(i,t=M.MAIN){return`https://${si[t]||Pu(i,t)}/api/v1/audioAiAuth`}function Wy(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${Hy(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 _=_i(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: ${_}`;break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C=`Your packages is not active. Refer to: ${_}`;break;case 5:C=`Your packages is expired. Refer to: ${_}`;break;case 6:C="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${A} Reason: ${m}. ${C}`:`${A}, ${C}`}})}var $u=0,pp=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new hn(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&&(x(t.volume)||(this.volume=t.volume),x(t.loop)||(this.loop=t.loop),x(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)}}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(t=this.publisher)==null||t.play(),(e=this.player)==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 wn(i,t){if(t&&typeof t!="function")throw new oe({code:se.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var ni=class ni{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);$u=$u+1,this.log=t.log.createChild({id:`${this.getAlias()}${$u}`}),this.log.info(`created id=${this.getAlias()}${$u}`)}getName(){return ni.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ni.startValidateRule;case"update":return ni.updateValidateRule;case"stop":return ni.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;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 pp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),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.`),Q.addEnum({key:502700,value:3}),this.kvUpload(t)})}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),x(r)||n.setOperation(r),x(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&&Q.addCount({key:502711}),r&&Q.addCount({key:502703}),o&&Q.addCount({key:502704}),s&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),a&&Q.addCount({key:502707}),typeof u!="function"&&Q.addCount({key:502709}),typeof p!="function"&&Q.addCount({key:502710}),typeof m!="function"&&Q.addCount({key:502708})}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(ni,"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 oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});wn("onTimeUpdate",t.onTimeUpdate),wn("onEnded",t.onEnded),wn("onDurationChange",t.onDurationChange)}}),l(ni,"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){wn("onTimeUpdate",t.onTimeUpdate),wn("onEnded",t.onEnded),wn("onDurationChange",t.onDurationChange)}}),l(ni,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(ni,"Name","AudioMixer");var Bu=ni;var Hu=0,fp,$i=class $i{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",We("denoiser"));l(this,"workletNode");Hu=Hu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Hu}`}),this.log.info(`created id=${this.getAlias()}${Hu}`)}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}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:se.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return fp||(fp=this.doPreload(t)),fp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield xi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return $i.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return $i.startValidateRule(this.core);case"update":return $i.updateValidateRule;case"stop":return $i.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 oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${o}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:u,message:m}=yield jy(r,ge(X({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new oe({code:se.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 _;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}(${Ps(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}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)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};l($i,"updateValidateRule",{type:"object"}),l($i,"stopValidateRule",{type:"object"}),l($i,"Name","AIDenoiser");var Wu=$i;function jy(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=_i(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="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?`${_} Reason: ${u}. ${A}`:`${_}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var VE=pi(bi(),1);var gp=class extends VE.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&&!pt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){He.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)&&$.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){He.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qy=new gp,Ep=qy;function zy([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 ms(new DataView(new Uint8Array(s).buffer),!0)}function Jy(i){return i.type==="empty"||i.data.byteLength===0}function Xy(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function Qy(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 _p({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-Qy(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(zy),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 Tp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(Jy(i)||!Xy(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 ms(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 Ip=0,ac=class ac{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Ip++,this.log=t.log.createChild({id:`${this.getAlias()}${Ip}`}),this.log.info(`[sei] created id=${this.getAlias()}${Ip}`),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 _p({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Tp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(te.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:os?this.encode:_p,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:os?this.decode:Tp,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 ac.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(ac,"autoStart",!0),l(ac,"Name","SEI");var Gu=ac;function Sp({frame:i,onDump:t}){return t==null||t(),i}function yp({frame:i,onDump:t}){return t==null||t(),i}var FE={"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 ai=[i=>{i.codec="avc1.42e01f"},i=>{delete i.hardwareAcceleration}],KE=(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 oA(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var sA=0,tl=class{constructor(t){l(this,"id",sA++);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=Rt(),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,le.OFF),this.stopOB=Rt(),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,$h((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),ze(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ae(this.pipe(this.track),ze(this.stopOB),Pi());Ae(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Q.addFailedEvent({key:KE(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),Q.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`),Q.addSuccessEvent({key:KE(this.type,this.renderer)}),Q.addSuccessEvent({key:514704})})),Ae(e,Fr(1),Le(()=>{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"&&!Um()&&(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(!oA(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=_e();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":for(let u=0;u<=ai.length;u++){let{supported:m}=yield VideoDecoder.isConfigSupported(this.config);if(m)break;if(u===ai.length){e.error(3);return}ai[u](this.config)}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 St({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(St.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let u=new el(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 Dt({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 ps(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 pc=class extends e_.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",$.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",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Dt({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 or(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Dt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new St({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(),this._glVideoContext.on(St.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=dt.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(),dt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(hr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Q.addFailedEvent({key:o,error:r}):Q.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 St({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 _u(this.smallVideoContext,e,this.log),this.smallVideoContext.on(St.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;hr&&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(vt.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Ot===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof gr?(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 gr?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 Eu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(vt.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 Ku(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 Er(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 yn(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 ri)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof ar)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof To){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 gs)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 ri?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ar?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 To?e.source&&e.source.context.destroy():e instanceof gs&&(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 de({code:q.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})=>{s.drawImage(n,a,u,m,p)}),qs(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)||((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 qs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new de({code:q.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}=e;this.watermarkImageList.some(g=>g.type===u)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==u),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl}),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}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,_)=>g==="imageUrl"?void 0:_))})}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 qs(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 de({code:q.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 tl(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([$g(function(e){this.log.error("update failed",e)})],pc.prototype,"update",1);var nA=0;var rl=class extends le{constructor(e){super("room");l(this,"seq",++nA);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",$.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"videoCodec");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Qe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Qe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Qe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new QE({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new YE({room:this}),this.badCaseDetector=new ZE({room:this}),this.audioManager=new Su(this),this.videoManager=new pc(this)}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(Ne(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Bt(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?(xu([a,a]),Fo(`https://${a}`)):(s&&Fo(s),n&&xu(n))}V.once(F.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:si.main,sched_back_domain:si.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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Yt.INVALID_DESTROY),new de({code:q.INVALID_OPERATION,message:$e({key:Fe.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,V.emit(F.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,u;let o=_e();try{let{isCached:m,result:p,detailCost:g}=yield dp({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:at,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} ${mr(p,{keysToExclude:["username","credential"]})}`),m&&V.once(F.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=X(X({},this.scheduleResult),p),ke((s=p.config)==null?void 0:s.retryCount)&&wl(p.config.retryCount),Ne((n=p.config)==null?void 0:n.loggerDomain)&&Fo(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,V.emit(F.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),Q.addSuccessEvent({key:521700,cost:_e()-o})}catch(m){throw Q.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function t_(i,t=!1){let e=Object.defineProperties(Rt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Be,i.onmessageerror=Be,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 Dp=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=Be,e(r)}},LH=Te(Dp,"takeUntilComplete");var Pt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},r_="__INLINE__WORKER__",i_="__INLINE__WASM__",{debug:o_}=console;Pt.debug||(console.debug=()=>{});var aA=!r_.startsWith("__"),cA=!i_.startsWith("__");function il(){let i=zo(`${Pt.assetsPath?`${Pt.assetsPath}/`:""}worker.js`);return aA?URL.createObjectURL(new Blob([atob(r_)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var fc;function ol(){return y(this,null,function*(){let i=Pt.assetsPath?`${Pt.assetsPath}/`:"";return fc||(cA?fc=new TextEncoder().encode(atob(i_)).buffer:fc=yield fetch(zo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),fc)})}var wp=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=We("player"),e=il();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),$.info("global audio player worklet addModule success",e)}catch(r){throw $.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield ol(),flag:Pt},numberOfInputs:2}),$.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*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},sl=new wp;var Mp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),GH=Mp?Promise.resolve().then(function(){return mA}):Promise.resolve().then(function(){return _A});var jH=Mp?Promise.resolve().then(function(){return pA}):Promise.resolve().then(function(){return IA});var dA=Mp?Promise.resolve().then(function(){return gA}):Promise.resolve().then(function(){return yA});function Op(...i){return y(this,null,function*(){return(yield dA).default(...i)})}var uA=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),lA=(...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(uA));return i[0].multiple?o:o[0]}),mA={__proto__:null,default:lA};function nl(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 nl=function(e){this.s=e,this.n=e.next},nl.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 nl(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 _,A=function(C){var N,D,O,Z=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,O=Symbol.iterator);Z--;){if(D&&(N=C[D])!=null)return N.call(C);if(O&&(N=C[O])!=null)return new nl(N.call(C));D="@@asyncIterator",O="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(_=yield A.next()).done;p=!1){let C=_.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)]}),hA=(...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)}),pA={__proto__:null,default:hA},fA=(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,_)=>{a[_]={description:g.description||"Files",accept:{}},g.mimeTypes?(_===0&&u&&g.mimeTypes.push(u),g.mimeTypes.map(A=>{a[_].accept[A]=g.extensions||[]})):u?a[_].accept[u]=g.extensions||[]:a[_].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)}),gA={__proto__:null,default:fA},EA=(...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()})}),_A={__proto__:null,default:EA},TA=(...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()})}),IA={__proto__:null,default:TA},SA=(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:O})=>{if(!D)return C.enqueue(O),N();C.close()})})}()}),_=new Response(g),A=yield _.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}),yA={__proto__:null,default:SA};var xp=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=il(),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(Zc(),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 ol(),flag:Pt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Pp=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()}},kp=class i extends xp{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 Ft(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ro=new kp,As,AA=-1;function n_(i){return console.log(i),As.push(i.slice()),As.length>1e3&&As.shift(),i}function a_(i){return y(this,null,function*(){switch(AA){case 0:this.edpl.willDecodeAudio=n_;break;case 2:this.edpl.didEncodeAudio=n_;break}yield Ro.create(),V.emit(F.JOIN_SEND_CMD,{room:this});let t=new Pp(Ro,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(V.emit(F.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new de({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:$e({key:Fe.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Lp},useWt:{set:bA},enableDebug:{set(i){console.debug=i?o_:()=>{},Ro.setSwitchValue("enableDebug",i)}},useV2:{set:Up},dump:{value(){if(As||(console.warn("dump audio will be activated at next time join room"),As=[]),!As.length){console.warn("no audio data to dump,try it later");return}let i=[];return As.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Op(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;Ro.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,Ro.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Op(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Pt.useHardDecoder="prefer-hardware";break;case!1:Pt.useHardDecoder="prefer-software";break;default:Pt.useHardDecoder="no-preference"}}}});function Lp(i){return y(this,null,function*(){Ro.setSwitchValue("useAINS",i)})}function Up(i){return y(this,null,function*(){Ro.setSwitchValue("useV2",i)})}function bA(i){return y(this,null,function*(){Ro.setSwitchValue("useWt",i)})}function c_(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 d_(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(t_(r.port2),ze(be(i,le.INIT)),Le(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 al=[];function l_(i){var u;let t=Rt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=al.length;m++)if(!al[m]){al[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:X({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(X({},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=We("player").createMediaStreamSource(s),n.connect(sl.worklet,0,this.index)};Ae(be(i,"output-media-track-changed"),ze(be(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),al[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ae(t,Ya(m=>i.volume=m),ki(gu(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var R4=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Vp=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});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});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&&V.emit(F.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({},e),e})}configure(t,e){return y(this,null,function*(){var r;if(Object.assign(this.config,t),e.frameEncoded===0)for(let o=0;o<=ai.length;o++){let{supported:s}=yield VideoDecoder.isConfigSupported(this.config);if(s)break;if(o===ai.length)return;ai[o](this.config),e.selectConfigIndex=o}else e.selectConfigIndex+e.recreateCount<=ai.length&&e.recreateCount>0?ai[e.selectConfigIndex+e.recreateCount-1](this.config):ai[e.selectConfigIndex](this.config);(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function cl(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.640028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Pt.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 Vp(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:u}=a.data;ia({configureBr:[a.data.bitrate,u]}),n.session&&n.configure({bitrate:u},n.session)}},this._log.info("start push",r,t),n})}function m_(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 cl.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:_,height:A,displaySurface:C}=g.getSettings();_&&(a.config.width=_),A&&(a.config.height=A);let N=sr.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 Z;D=new ReadableStream({start(ue){i.on("render",Se=>{if(i.player.mode!==0)try{ue.enqueue(new VideoFrame(Se,{timestamp:performance.now()*1e3}))}catch(Ye){console.warn(Ye)}})},pull(ue){return y(this,null,function*(){if(i.player.mode===0&&Mi()&&i.player.element)return new Promise(Se=>{i.player.element.requestVideoFrameCallback((Ye,H)=>{try{let Pe=new VideoFrame(i.player.element);ue.enqueue(Pe)}catch(Pe){console.warn(Pe)}Se()})})})}})}let O="small"in i&&i.small;return O?(this.smallEncoder||(this.smallEncoder=yield cl.call(this,i,{profile:O,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"),ze(be(i,"ready")),Le(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 vo=class vo extends le{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(vo.INTERVALCHANGED,this.interval)}),Ae(be(this,vo.INTERVALCHANGED),Eo(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ae(eE(s),go(()=>[]))),Le(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==le.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(vo.INTERVALCHANGED,this.interval)}stop(){}};l(vo,"INTERVALCHANGED","intervalChanged"),ee([Ze([le.INIT,le.OFF],le.ON)],vo.prototype,"start",1),ee([Ze([],le.OFF)],vo.prototype,"stop",1);var dl=vo;var Co=class Co extends rl{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 dl(this));l(this,"enableAIVoice",Lp);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:lm(),uint32_device_type:0,str_os_verion:mm(),uint32_link_type:1,str_client_version:at,uint32_net_type:$o[Xr.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Up(!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=Xr.getEnv(),n=Pd(),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:sn(),browserInfo:Pd(),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:at,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),sl.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())})}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=ze(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,Le(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(ge(X({},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 F.RECEIVED_PUBLISHED_USER_LIST:V.emit(e,X({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 Xu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let g=r,_=this.remotePublishedUserMap.get(g);_&&(_.remoteVideoTrack.close(),_.remoteAuxiliaryTrack.close(),_.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(g),this.emit("remote-unpublished",_))}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:_,flag:A}=r,C=this.remotePublishedUserMap.get(_.userId);if(!C){this.emit("remote-publish-state-changed",r);return}C.flag=A}V.emit(F.REMOTE_PUBLISH_STATE_CHANGED,X({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=X({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:u,msg_down_stream_info:m}=r,p={str_sdk_version:at,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:$o[ra()]},msg_event_msg:iE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:m};V.emit(F.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),V.emit(F.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:u}),delete r.downlinkInfo;break;case"signal-connection-state-changed":V.emit(F.SIGNAL_CONNECTION_STATE_CHANGED,X({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*(){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),bt(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:l_.call(this,a);break;default:yield m_.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(ut)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((g,_)=>_.mediaType|g,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),u=X({},a.subscribeState),m=Object.assign(new Aa,u);m.mediaType|=r,V.emit(F.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 c_.call(this,g);default:return d_.call(this,g)}})),V.emit(F.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();V.emit(F.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 cl.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(Co.prototype.afterJoin),Ze(["left",le.INIT],"joined"),jE()],Co.prototype,"join",1),ee([Ze("joined","left",{ignoreError:!0}),qE()],Co.prototype,"leave",1),ee([eu((...e)=>0),zE()],Co.prototype,"publish",1),ee([eu((...e)=>0),JE()],Co.prototype,"unpublish",1),ee([eu((...e)=>e[0].userId),XE()],Co.prototype,"subscribe",1);var ul=Co;Mn.frameWorkType=37;Mn.create=function(i){let t=Mn._create.call(this,ul,i);return t._use(op,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Pt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",at,"created",Pt),t};Object.assign(Mn.prototype,{_setCurrentSpeaker(i){let t=We("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(op.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{Ae(be(i,"decode-downgrade-state-changed"),Jt(o=>o.state==="STARTED"),Fr(1),Gh(1e4),ze(be(i,le.INIT)),Le(e,r))})})}});Hm(37);var YW=Mn;export{YW 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 ai=[i=>{i.codec="avc1.42e01f"},i=>{delete i.hardwareAcceleration}],KE=(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 oA(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var sA=0,tl=class{constructor(t){l(this,"id",sA++);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=Rt(),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,le.OFF),this.stopOB=Rt(),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,$h((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),ze(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ae(this.pipe(this.track),ze(this.stopOB),Pi());Ae(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Q.addFailedEvent({key:KE(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),Q.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`),Q.addSuccessEvent({key:KE(this.type,this.renderer)}),Q.addSuccessEvent({key:514704})})),Ae(e,Fr(1),Le(()=>{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"&&!Um()&&(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(!oA(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=_e();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":for(let u=0;u<=ai.length;u++){let{supported:m}=yield VideoDecoder.isConfigSupported(this.config);if(m)break;if(u===ai.length){e.error(3);return}ai[u](this.config)}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 St({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(St.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let u=new el(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 Dt({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 ps(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 pc=class extends e_.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",$.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",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Dt({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 or(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Dt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new St({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(),this._glVideoContext.on(St.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=dt.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(),dt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(hr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Q.addFailedEvent({key:o,error:r}):Q.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 St({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 _u(this.smallVideoContext,e,this.log),this.smallVideoContext.on(St.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;hr&&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(vt.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Ot===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof gr?(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 gr?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 Eu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(vt.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 Ku(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 Er(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 yn(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 ri)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof ar)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof To){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 gs)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 ri?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ar?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 To?e.source&&e.source.context.destroy():e instanceof gs&&(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 de({code:q.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})=>{s.drawImage(n,a,u,m,p)}),qs(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)||((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 qs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new de({code:q.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}=e;this.watermarkImageList.some(g=>g.type===u)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==u),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl}),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}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,_)=>g==="imageUrl"?void 0:_))})}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 qs(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 de({code:q.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 tl(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([$g(function(e){this.log.error("update failed",e)})],pc.prototype,"update",1);var nA=0;var rl=class extends le{constructor(e){super("room");l(this,"seq",++nA);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",$.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"videoCodec");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Qe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Qe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Qe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new QE({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new YE({room:this}),this.badCaseDetector=new ZE({room:this}),this.audioManager=new Su(this),this.videoManager=new pc(this)}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(Ne(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Bt(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?(xu([a,a]),Fo(`https://${a}`)):(s&&Fo(s),n&&xu(n))}V.once(F.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:si.main,sched_back_domain:si.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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Yt.INVALID_DESTROY),new de({code:q.INVALID_OPERATION,message:$e({key:Fe.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,V.emit(F.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,u;let o=_e();try{let{isCached:m,result:p,detailCost:g}=yield dp({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:at,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} ${mr(p,{keysToExclude:["username","credential"]})}`),m&&V.once(F.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=X(X({},this.scheduleResult),p),ke((s=p.config)==null?void 0:s.retryCount)&&wl(p.config.retryCount),Ne((n=p.config)==null?void 0:n.loggerDomain)&&Fo(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,V.emit(F.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),Q.addSuccessEvent({key:521700,cost:_e()-o})}catch(m){throw Q.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function t_(i,t=!1){let e=Object.defineProperties(Rt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Be,i.onmessageerror=Be,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 Dp=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=Be,e(r)}},LH=Te(Dp,"takeUntilComplete");var Pt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},r_="__INLINE__WORKER__",i_="__INLINE__WASM__",{debug:o_}=console;Pt.debug||(console.debug=()=>{});var aA=!r_.startsWith("__"),cA=!i_.startsWith("__");function il(){let i=zo(`${Pt.assetsPath?`${Pt.assetsPath}/`:""}worker.js`);return aA?URL.createObjectURL(new Blob([atob(r_)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var fc;function ol(){return y(this,null,function*(){let i=Pt.assetsPath?`${Pt.assetsPath}/`:"";return fc||(cA?fc=new TextEncoder().encode(atob(i_)).buffer:fc=yield fetch(zo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),fc)})}var wp=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=We("player"),e=il();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),$.info("global audio player worklet addModule success",e)}catch(r){throw $.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield ol(),flag:Pt},numberOfInputs:2}),$.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*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},sl=new wp;var Mp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),GH=Mp?Promise.resolve().then(function(){return mA}):Promise.resolve().then(function(){return _A});var jH=Mp?Promise.resolve().then(function(){return pA}):Promise.resolve().then(function(){return IA});var dA=Mp?Promise.resolve().then(function(){return gA}):Promise.resolve().then(function(){return yA});function Op(...i){return y(this,null,function*(){return(yield dA).default(...i)})}var uA=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),lA=(...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(uA));return i[0].multiple?o:o[0]}),mA={__proto__:null,default:lA};function nl(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 nl=function(e){this.s=e,this.n=e.next},nl.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 nl(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 _,A=function(C){var N,D,O,Z=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,O=Symbol.iterator);Z--;){if(D&&(N=C[D])!=null)return N.call(C);if(O&&(N=C[O])!=null)return new nl(N.call(C));D="@@asyncIterator",O="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(_=yield A.next()).done;p=!1){let C=_.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)]}),hA=(...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)}),pA={__proto__:null,default:hA},fA=(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,_)=>{a[_]={description:g.description||"Files",accept:{}},g.mimeTypes?(_===0&&u&&g.mimeTypes.push(u),g.mimeTypes.map(A=>{a[_].accept[A]=g.extensions||[]})):u?a[_].accept[u]=g.extensions||[]:a[_].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)}),gA={__proto__:null,default:fA},EA=(...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()})}),_A={__proto__:null,default:EA},TA=(...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()})}),IA={__proto__:null,default:TA},SA=(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:O})=>{if(!D)return C.enqueue(O),N();C.close()})})}()}),_=new Response(g),A=yield _.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}),yA={__proto__:null,default:SA};var xp=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=il(),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(Zc(),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 ol(),flag:Pt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Pp=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()}},kp=class i extends xp{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 Ft(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ro=new kp,As,AA=-1;function n_(i){return console.log(i),As.push(i.slice()),As.length>1e3&&As.shift(),i}function a_(i){return y(this,null,function*(){switch(AA){case 0:this.edpl.willDecodeAudio=n_;break;case 2:this.edpl.didEncodeAudio=n_;break}yield Ro.create(),V.emit(F.JOIN_SEND_CMD,{room:this});let t=new Pp(Ro,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(V.emit(F.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new de({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:$e({key:Fe.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Lp},useWt:{set:bA},enableDebug:{set(i){console.debug=i?o_:()=>{},Ro.setSwitchValue("enableDebug",i)}},useV2:{set:Up},dump:{value(){if(As||(console.warn("dump audio will be activated at next time join room"),As=[]),!As.length){console.warn("no audio data to dump,try it later");return}let i=[];return As.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Op(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;Ro.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,Ro.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Op(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Pt.useHardDecoder="prefer-hardware";break;case!1:Pt.useHardDecoder="prefer-software";break;default:Pt.useHardDecoder="no-preference"}}}});function Lp(i){return y(this,null,function*(){Ro.setSwitchValue("useAINS",i)})}function Up(i){return y(this,null,function*(){Ro.setSwitchValue("useV2",i)})}function bA(i){return y(this,null,function*(){Ro.setSwitchValue("useWt",i)})}function c_(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 d_(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(t_(r.port2),ze(be(i,le.INIT)),Le(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 al=[];function l_(i){var u;let t=Rt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=al.length;m++)if(!al[m]){al[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:X({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(X({},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=We("player").createMediaStreamSource(s),n.connect(sl.worklet,0,this.index)};Ae(be(i,"output-media-track-changed"),ze(be(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),al[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ae(t,Ya(m=>i.volume=m),ki(gu(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var R4=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Vp=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&&V.emit(F.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;if(t)Object.assign(this.config,t);else if(e.frameEncoded===0)for(let o=0;o<=ai.length;o++){let{supported:s}=yield VideoDecoder.isConfigSupported(this.config);if(s)break;if(o===ai.length)return;ai[o](this.config),e.selectConfigIndex=o}else e.selectConfigIndex+e.recreateCount<=ai.length&&e.recreateCount>0?ai[e.selectConfigIndex+e.recreateCount-1](this.config):ai[e.selectConfigIndex](this.config);(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function cl(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.640028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Pt.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 Vp(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:u}=a.data;ia({configureBr:[a.data.bitrate,u]}),n.session&&n.configure({bitrate:u},n.session)}},this._log.info("start push",r,t),n})}function m_(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 cl.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:_,height:A,displaySurface:C}=g.getSettings();_&&(a.config.width=_),A&&(a.config.height=A);let N=sr.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 Z;D=new ReadableStream({start(ue){i.on("render",Se=>{if(i.player.mode!==0)try{ue.enqueue(new VideoFrame(Se,{timestamp:performance.now()*1e3}))}catch(Ye){console.warn(Ye)}})},pull(ue){return y(this,null,function*(){if(i.player.mode===0&&Mi()&&i.player.element)return new Promise(Se=>{i.player.element.requestVideoFrameCallback((Ye,H)=>{try{let Pe=new VideoFrame(i.player.element);ue.enqueue(Pe)}catch(Pe){console.warn(Pe)}Se()})})})}})}let O="small"in i&&i.small;return O?(this.smallEncoder||(this.smallEncoder=yield cl.call(this,i,{profile:O,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"),ze(be(i,"ready")),Le(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 vo=class vo extends le{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(vo.INTERVALCHANGED,this.interval)}),Ae(be(this,vo.INTERVALCHANGED),Eo(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ae(eE(s),go(()=>[]))),Le(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==le.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(vo.INTERVALCHANGED,this.interval)}stop(){}};l(vo,"INTERVALCHANGED","intervalChanged"),ee([Ze([le.INIT,le.OFF],le.ON)],vo.prototype,"start",1),ee([Ze([],le.OFF)],vo.prototype,"stop",1);var dl=vo;var Co=class Co extends rl{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 dl(this));l(this,"enableAIVoice",Lp);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:lm(),uint32_device_type:0,str_os_verion:mm(),uint32_link_type:1,str_client_version:at,uint32_net_type:$o[Xr.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Up(!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=Xr.getEnv(),n=Pd(),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:sn(),browserInfo:Pd(),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:at,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),sl.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())})}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=ze(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,Le(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(ge(X({},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 F.RECEIVED_PUBLISHED_USER_LIST:V.emit(e,X({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 Xu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let g=r,_=this.remotePublishedUserMap.get(g);_&&(_.remoteVideoTrack.close(),_.remoteAuxiliaryTrack.close(),_.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(g),this.emit("remote-unpublished",_))}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:_,flag:A}=r,C=this.remotePublishedUserMap.get(_.userId);if(!C){this.emit("remote-publish-state-changed",r);return}C.flag=A}V.emit(F.REMOTE_PUBLISH_STATE_CHANGED,X({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=X({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:u,msg_down_stream_info:m}=r,p={str_sdk_version:at,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:$o[ra()]},msg_event_msg:iE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:m};V.emit(F.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),V.emit(F.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:u}),delete r.downlinkInfo;break;case"signal-connection-state-changed":V.emit(F.SIGNAL_CONNECTION_STATE_CHANGED,X({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*(){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),bt(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:l_.call(this,a);break;default:yield m_.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(ut)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((g,_)=>_.mediaType|g,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),u=X({},a.subscribeState),m=Object.assign(new Aa,u);m.mediaType|=r,V.emit(F.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 c_.call(this,g);default:return d_.call(this,g)}})),V.emit(F.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();V.emit(F.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 cl.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(Co.prototype.afterJoin),Ze(["left",le.INIT],"joined"),jE()],Co.prototype,"join",1),ee([Ze("joined","left",{ignoreError:!0}),qE()],Co.prototype,"leave",1),ee([eu((...e)=>0),zE()],Co.prototype,"publish",1),ee([eu((...e)=>0),JE()],Co.prototype,"unpublish",1),ee([eu((...e)=>e[0].userId),XE()],Co.prototype,"subscribe",1);var ul=Co;Mn.frameWorkType=37;Mn.create=function(i){let t=Mn._create.call(this,ul,i);return t._use(op,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Pt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",at,"created",Pt),t};Object.assign(Mn.prototype,{_setCurrentSpeaker(i){let t=We("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(op.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{Ae(be(i,"decode-downgrade-state-changed"),Jt(o=>o.state==="STARTED"),Fr(1),Gh(1e4),ze(be(i,le.INIT)),Le(e,r))})})}});Hm(37);var YW=Mn;export{YW as default};
|