trtc-sdk-v5 5.9.0-wasm.12 → 5.9.0-wasm.13
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/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/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/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +4 -4
package/package.json
CHANGED
package/trtc.esm.js
CHANGED
|
@@ -86,16 +86,16 @@ return ret;
|
|
|
86
86
|
`;for(var $=0;$<f-1;++$)S[$+1].deleteObject&&(Ie+=" argType"+$+".deleteObject(arg"+$+`);
|
|
87
87
|
`);C.isVoid||(Ie+=` return retType.toWireType(destructors, rv);
|
|
88
88
|
`),Ie+=`};
|
|
89
|
-
`,W.push(Ie);var Ue=ac(Function,W).apply(null,V);return B=El(Ue),Ic[O]=B,B}var Il=()=>{yi("")},Sc;Sc=()=>performance.now();var Sl=(f,_,S)=>Le.copyWithin(f,_,_+S),yl=f=>{yi("OOM")},Al=f=>{var _=Le.length;f>>>=0,yl(f)},bl=[null,[],[]],Rl=(f,_)=>{var S=bl[f];_===0||_===10?((f===1?Pe:Xe)(Qr(S,0)),S.length=0):S.push(_)},In={varargs:void 0,get(){In.varargs+=4;var f=qt[In.varargs-4>>2];return f},getStr(f){var _=pc(f);return _}},vl=(f,_,S,C)=>{for(var O=0,B=0;B<S;B++){var W=x[_>>2],V=x[_+4>>2];_+=8;for(var ee=0;ee<V;ee++)Rl(f,Le[W+ee]);O+=V}return x[C>>2]=O,0};Ju(),yt=e.BindingError=class extends Error{constructor(_){super(_),this.name="BindingError"}},qr=e.InternalError=class extends Error{constructor(_){super(_),this.name="InternalError"}},eo(),dn(),ro(),sc=e.UnboundTypeError=tl(Error,"UnboundTypeError"),ol(),nl();var Cl={o:sn,r:qu,m:zu,q:rl,p:fn,d:cc,u:al,k:dl,b:ul,a:ll,j:hc,g:fl,n:_l,e:Tc,l:uc,h:Tn,f:Il,c:Sc,t:Sl,s:Al,i:vl},Rh=ja(),Dl=()=>(Dl=je.w)(),mr=f=>(mr=je.x)(f),Sn=f=>(Sn=je.y)(f),yc=f=>(yc=je.A)(f),Nl=e.__embind_initialize_bindings=()=>(Nl=e.__embind_initialize_bindings=je.B)(),wl=()=>(wl=je.__errno_location)(),Ac=f=>(Ac=je.C)(f),yn=e.dynCall_jiji=(f,_,S,C,O)=>(yn=e.dynCall_jiji=je.D)(f,_,S,C,O),is;Gr=function f(){is||bc(),is||(Gr=f)};function bc(){if(Wr>0||(Bu(),Wr>0))return;function f(){is||(is=!0,e.calledRun=!0,!Qs&&($u(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),q()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),f()},1)):f()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return bc(),t.ready}})(),B_=ES;var nu=class extends Br{constructor(t){super(B_,t!=null&&t.wasmPath?fetch(t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var au=class au{constructor(t){this.core=t;l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.createDecoder=this.createDecoder.bind(this)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return au.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return this.core.rtcDectection.isSIMDSupported()?new nu(pe(J({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec_simd.wasm`})):new su(pe(J({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Ti;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:a})=>{if(a!==t.track||s.type==="empty")return s;if(this.contextMap.has(a))return this.contextMap.get(a).decode(s);let d=this.core.room.videoManager.createDecodeContext(pe(J({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:a})})),this.contextMap.set(a,d),d.decode(s)}}stop(t){if(!(t!=null&&t.track))this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});else{let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.contextMap.delete(t.track))}this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST);return}e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(pe(J({},t),{createDecoder:this.createDecoder})))}}};l(au,"Name","TRTCVideoDecoder");var wa=au;var cg=Ci(ki());function Hp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Ae((r,o)=>{let s=new WeakMap;return F.on(P.ROOM_DESTROY,({room:a})=>s.delete(a)),function(...a){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...a)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...a)}})}var TS="2025-02-18 19:08:36",$_=!0,H_=function(){var i;$_&&($_=!1,U.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Nr}/en/index.html`),console.info(`* Changelog: ${Nr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),U.info("TRTC Web SDK Version:",Ke),Tr||U.debug("Build Time:",TS),U.info("UA:",navigator.userAgent),U.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Kn().then(t=>{t&&U.info(fr)}))};var nr={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 ae={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},yr=(w=>(w[w.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",w[w.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",w[w.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",w[w.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",w[w.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",w[w.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",w[w.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",w[w.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",w[w.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",w[w.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",w[w.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",w[w.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",w[w.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",w[w.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",w[w.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",w[w.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",w[w.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",w[w.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",w[w.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",w[w.INVALID_OPERATION=5100]="INVALID_OPERATION",w[w.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",w[w.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",w[w.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",w[w.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",w[w.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",w[w.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",w[w.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",w[w.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",w[w.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",w[w.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",w[w.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",w[w.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",w[w.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",w[w.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",w[w.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",w[w.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",w[w.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",w[w.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",w[w.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",w[w.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",w[w.DEVICE_ERROR=5300]="DEVICE_ERROR",w[w.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",w[w.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",w[w.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",w[w.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",w[w.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",w[w.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",w[w.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",w[w.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",w[w.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",w[w.SERVER_ERROR=5400]="SERVER_ERROR",w[w.NEED_TO_BUY=5401]="NEED_TO_BUY",w[w.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",w[w.OPERATION_FAILED=5500]="OPERATION_FAILED",w[w.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",w[w.REJOIN_FAILED=5502]="REJOIN_FAILED",w[w.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",w[w.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",w[w.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",w[w.OPERATION_ABORT=5998]="OPERATION_ABORT",w[w.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",w))(yr||{});function G_({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=yr[i];try{o=W_[s]}catch(a){o=W_.UNKNOWN_ERROR}return Fe(o)?r=o(t):Se(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var W_=pe(J({},Wt),{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: ${ut(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: ${ut(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_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},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 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=$o(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=$o(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=$o(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=$o(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=$o(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=$o(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=$o(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 $o(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Wp=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:a="",originError:d}){var m;let h;o?h=o:h=G_({code:e===ae.SERVER_ERROR?e:r||e,params:J({fnName:a,error:d},s)});super(h);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=yr[e],this.code=e,this.extraCode=r,this.functionName=a,this.originError=d,this.message=h,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let T={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},I={startLocalVideo:"webcam",startLocalAudio:"microphone"},v=document.createElement("a");ho?v.href=`ms-settings:privacy-${I[this.functionName]}`:Er&&(v.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${T[this.functionName]}`),v.href.length>0&&v.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ue){let{stack:a}=e,d={code:ae.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case Y.INVALID_PARAMETER:d.code=ae.INVALID_PARAMETER,d.message=e.message;break;case Y.INVALID_OPERATION:d.code=ae.INVALID_OPERATION;break;case Y.NOT_SUPPORTED:case Y.NOT_SUPPORTED_H264:d.code=ae.ENV_NOT_SUPPORTED,e.getCode()===Y.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(Wt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Y.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case Y.SERVER_TIMEOUT:case Y.SWITCH_ROLE_FAILED:d.code=ae.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case Y.API_CALL_ABORTED:d.code=ae.OPERATION_ABORT;break;case Y.DEVICE_NOT_FOUND:case Y.DEVICE_AUTO_RECOVER_FAILED:case Y.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=IS(e.name));break;case Y.UNKNOWN:break;default:d.code=ae.OPERATION_FAILED}s=new i(d),a&&(s.stack+=a.substr(a.indexOf(`
|
|
89
|
+
`,W.push(Ie);var Ue=ac(Function,W).apply(null,V);return B=El(Ue),Ic[O]=B,B}var Il=()=>{yi("")},Sc;Sc=()=>performance.now();var Sl=(f,_,S)=>Le.copyWithin(f,_,_+S),yl=f=>{yi("OOM")},Al=f=>{var _=Le.length;f>>>=0,yl(f)},bl=[null,[],[]],Rl=(f,_)=>{var S=bl[f];_===0||_===10?((f===1?Pe:Xe)(Qr(S,0)),S.length=0):S.push(_)},In={varargs:void 0,get(){In.varargs+=4;var f=qt[In.varargs-4>>2];return f},getStr(f){var _=pc(f);return _}},vl=(f,_,S,C)=>{for(var O=0,B=0;B<S;B++){var W=x[_>>2],V=x[_+4>>2];_+=8;for(var ee=0;ee<V;ee++)Rl(f,Le[W+ee]);O+=V}return x[C>>2]=O,0};Ju(),yt=e.BindingError=class extends Error{constructor(_){super(_),this.name="BindingError"}},qr=e.InternalError=class extends Error{constructor(_){super(_),this.name="InternalError"}},eo(),dn(),ro(),sc=e.UnboundTypeError=tl(Error,"UnboundTypeError"),ol(),nl();var Cl={o:sn,r:qu,m:zu,q:rl,p:fn,d:cc,u:al,k:dl,b:ul,a:ll,j:hc,g:fl,n:_l,e:Tc,l:uc,h:Tn,f:Il,c:Sc,t:Sl,s:Al,i:vl},Rh=ja(),Dl=()=>(Dl=je.w)(),mr=f=>(mr=je.x)(f),Sn=f=>(Sn=je.y)(f),yc=f=>(yc=je.A)(f),Nl=e.__embind_initialize_bindings=()=>(Nl=e.__embind_initialize_bindings=je.B)(),wl=()=>(wl=je.__errno_location)(),Ac=f=>(Ac=je.C)(f),yn=e.dynCall_jiji=(f,_,S,C,O)=>(yn=e.dynCall_jiji=je.D)(f,_,S,C,O),is;Gr=function f(){is||bc(),is||(Gr=f)};function bc(){if(Wr>0||(Bu(),Wr>0))return;function f(){is||(is=!0,e.calledRun=!0,!Qs&&($u(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),q()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),f()},1)):f()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return bc(),t.ready}})(),B_=ES;var nu=class extends Br{constructor(t){super(B_,t!=null&&t.wasmPath?fetch(t.wasmPath).then(e=>e.arrayBuffer()):void 0,t==null?void 0:t.workerMode,t==null?void 0:t.canvas,t==null?void 0:t.yuvMode)}};var au=class au{constructor(t){this.core=t;l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.createDecoder=this.createDecoder.bind(this)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return au.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return this.core.rtcDectection.isSIMDSupported()?new nu(pe(J({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec_simd.wasm`})):new su(pe(J({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Ti;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:a})=>{if(a!==t.track||s.type==="empty")return s;if(this.contextMap.has(a))return this.contextMap.get(a).decode(s);let d=this.core.room.videoManager.createDecodeContext(pe(J({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:a})})),this.contextMap.set(a,d),d.decode(s)}}stop(t){if(!(t!=null&&t.track))this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});else{let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.contextMap.delete(t.track))}this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST);return}e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(pe(J({},t),{createDecoder:this.createDecoder})))}}};l(au,"Name","TRTCVideoDecoder");var wa=au;var cg=Ci(ki());function Hp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Ae((r,o)=>{let s=new WeakMap;return F.on(P.ROOM_DESTROY,({room:a})=>s.delete(a)),function(...a){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...a)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...a)}})}var TS="2025-02-19 13:15:02",$_=!0,H_=function(){var i;$_&&($_=!1,U.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Nr}/en/index.html`),console.info(`* Changelog: ${Nr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),U.info("TRTC Web SDK Version:",Ke),Tr||U.debug("Build Time:",TS),U.info("UA:",navigator.userAgent),U.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Kn().then(t=>{t&&U.info(fr)}))};var nr={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 ae={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},yr=(w=>(w[w.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",w[w.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",w[w.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",w[w.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",w[w.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",w[w.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",w[w.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",w[w.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",w[w.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",w[w.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",w[w.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",w[w.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",w[w.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",w[w.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",w[w.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",w[w.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",w[w.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",w[w.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",w[w.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",w[w.INVALID_OPERATION=5100]="INVALID_OPERATION",w[w.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",w[w.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",w[w.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",w[w.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",w[w.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",w[w.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",w[w.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",w[w.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",w[w.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",w[w.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",w[w.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",w[w.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",w[w.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",w[w.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",w[w.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",w[w.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",w[w.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",w[w.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",w[w.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",w[w.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",w[w.DEVICE_ERROR=5300]="DEVICE_ERROR",w[w.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",w[w.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",w[w.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",w[w.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",w[w.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",w[w.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",w[w.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",w[w.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",w[w.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",w[w.SERVER_ERROR=5400]="SERVER_ERROR",w[w.NEED_TO_BUY=5401]="NEED_TO_BUY",w[w.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",w[w.OPERATION_FAILED=5500]="OPERATION_FAILED",w[w.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",w[w.REJOIN_FAILED=5502]="REJOIN_FAILED",w[w.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",w[w.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",w[w.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",w[w.OPERATION_ABORT=5998]="OPERATION_ABORT",w[w.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",w))(yr||{});function G_({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=yr[i];try{o=W_[s]}catch(a){o=W_.UNKNOWN_ERROR}return Fe(o)?r=o(t):Se(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var W_=pe(J({},Wt),{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: ${ut(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: ${ut(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_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},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 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=$o(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=$o(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=$o(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=$o(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=$o(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=$o(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=$o(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 $o(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Wp=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:a="",originError:d}){var m;let h;o?h=o:h=G_({code:e===ae.SERVER_ERROR?e:r||e,params:J({fnName:a,error:d},s)});super(h);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=yr[e],this.code=e,this.extraCode=r,this.functionName=a,this.originError=d,this.message=h,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let T={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},I={startLocalVideo:"webcam",startLocalAudio:"microphone"},v=document.createElement("a");ho?v.href=`ms-settings:privacy-${I[this.functionName]}`:Er&&(v.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${T[this.functionName]}`),v.href.length>0&&v.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ue){let{stack:a}=e,d={code:ae.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case Y.INVALID_PARAMETER:d.code=ae.INVALID_PARAMETER,d.message=e.message;break;case Y.INVALID_OPERATION:d.code=ae.INVALID_OPERATION;break;case Y.NOT_SUPPORTED:case Y.NOT_SUPPORTED_H264:d.code=ae.ENV_NOT_SUPPORTED,e.getCode()===Y.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(Wt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Y.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case Y.SERVER_TIMEOUT:case Y.SWITCH_ROLE_FAILED:d.code=ae.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case Y.API_CALL_ABORTED:d.code=ae.OPERATION_ABORT;break;case Y.DEVICE_NOT_FOUND:case Y.DEVICE_AUTO_RECOVER_FAILED:case Y.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=IS(e.name));break;case Y.UNKNOWN:break;default:d.code=ae.OPERATION_FAILED}s=new i(d),a&&(s.stack+=a.substr(a.indexOf(`
|
|
90
90
|
`)))}else{if(e instanceof i)return e;s=new i({code:ae.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function IS(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=Wp;var j_={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:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},q_={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}}},Hs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Se(i)&&!document.getElementById(i))throw new oe({code:ae.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},J_={name:"userId",required:!0,type:"string"},z_={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[nr.AUDIO_PROFILE_STANDARD,nr.AUDIO_PROFILE_STANDARD_STEREO,nr.AUDIO_PROFILE_HIGH,nr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ma(i,t){if(!i)throw new oe({code:ae.INVALID_OPERATION,extraCode:5101,fnName:t})}function X_(i,t,e){if(!i)throw new oe({code:ae.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var NP={type:"number",notLessThanZero:!0},SS={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:ae.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Se(i.roomId))throw new oe({code:ae.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new oe({code:ae.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new oe({code:ae.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new oe({code:ae.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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Hs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:j_},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&mi())throw new oe({code:ae.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:pe(J({},Hs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:j_}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:z_},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&mi())throw new oe({code:ae.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:z_}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Hs,publish:{type:"boolean"},option:q_},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)&&mi())throw new oe({code:ae.ENV_NOT_SUPPORTED,extraCode:5201});if(!da())throw new oe({code:ae.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Hs,publish:{type:"boolean"},option:q_}},muteRemoteAudio:[J_,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[J_,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Hs,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){Ma(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(X_(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ae.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:pe(J({},Hs),{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){Ma(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(X_(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ae.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!=="*"&&L(i.streamType))throw new oe({code:ae.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Ma(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(!pa)throw new oe({code:ae.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:ae.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:ae.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ae.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Ma(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:ae.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:ae.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ae.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Ma(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:ae.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},Et={TRTC:SS};var Dt=class extends Error{};function yS(i,t){let e=lo(i);for(let r=0;r<t.length;r++)Or(e[r],t[r]);return e}function AS(i){this._resolve=Promise.resolve(i)}function bS(i){this._reject=Promise.reject(i)}var Wi=class Wi{constructor(t,e){this.instance=t;this.group=e;l(this,"started",!1);l(this,"ops",[]);l(this,"startSame",()=>!0);l(this,"mergeUpdate",yS);let r=Wi.instances.get(t);r?r.set(e,this):Wi.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Wi.instances.get(t);return r&&r.get(e)||new Wi(t,e)}static gets(t,e){let r=Wi.instances.get(t),o=[];return r&&r.forEach((s,a)=>{e.test(a)&&o.push(s)}),o}action(t,e,r){let o=d=>{var h;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(h=this.currentOp)==null||h.action(),d},s=d=>{var h,m;throw this.ops.shift(),t===0&&((h=this.currentOp)==null?void 0:h.type)===2&&this.ops.shift().reject(new Dt("start failed")),(m=this.currentOp)==null||m.action(),d},a={type:t,action:()=>e(...a.args).then(o,s),args:r,resolve:AS,reject:bS};try{switch(this.state){case 1:if(t===0)throw new Dt("already started");break;case 4:if(t===2)throw new Dt("not started");break;default:return this.cacheOp(a)}}catch(d){return Promise.reject(d)}return this.ops.push(a),a.promise=e(...a.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Dt("already start");break;case 3:switch(t.type){case 2:throw new Dt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Dt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Dt("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 Dt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Dt("start not allowed after update");case 0:throw new Dt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Dt("keep start")),new Dt("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(Wi,"instances",new WeakMap);var Ii=Wi;var cu=new WeakMap,du=(i,t)=>{if(t instanceof Dt){let{stack:e}=t;t=new oe({code:ae.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
91
91
|
`)))}throw t};function Gi(i,t){return Ae((e,r)=>function(...o){let s=Ii.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(du.bind(null,r))):e.apply(this,o)})}function Ho(i,t){let{merge:e,debounce:r}=t||{};return Ae((o,s)=>function(...a){let d=Ii.get(this,typeof i=="string"?i:i.call(this,...a));if(!d)return o.apply(this,a);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:h,getKey:m}=r;return new Promise((T,I)=>{var j,H;let v=(j=cu.get(this))==null?void 0:j.get(m(...a));if(v){let{timeoutId:z,resolve:Te}=v;clearTimeout(z),Te()}let N=setTimeout(()=>{if(d.state===3||d.state===4)return T();d.action(2,o.bind(this),a).catch(du.bind(null,s)).then(T,I)},h);cu.has(this)?(H=cu.get(this))==null||H.set(m(...a),{timeoutId:N,resolve:T}):cu.set(this,new Map([[m(...a),{timeoutId:N,resolve:T}]]))})}return d.action(2,o.bind(this),a).catch(du.bind(null,s))})}function ji(i){return Ae((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Ii.gets(this,o).map(a=>a.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Ii.get(this,o);return s?s.action(3,t.bind(this),r).catch(du.bind(null,e)):t.apply(this,r)})}var K={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"},Q_=new Set([K.ERROR,K.AUTOPLAY_FAILED,K.KICKED_OUT,K.REMOTE_USER_ENTER,K.REMOTE_USER_EXIT,K.REMOTE_AUDIO_AVAILABLE,K.REMOTE_AUDIO_UNAVAILABLE,K.REMOTE_VIDEO_AVAILABLE,K.REMOTE_VIDEO_UNAVAILABLE,K.CONNECTION_STATE_CHANGED,K.PUBLISH_STATE_CHANGED,K.SCREEN_SHARE_STOPPED,K.DEVICE_CHANGED,K.FIRST_VIDEO_FRAME]);function qi(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Oa(i){return i===nr.QOS_PREFERENCE_CLEAR?"detail":i===nr.QOS_PREFERENCE_SMOOTH?"motion":""}var jp={};Kr(jp,{bytes2ms:()=>jh,convertObjectNumberToInt:()=>Fn,copyProperties:()=>Gh,deepClone:()=>lo,deepMerge:()=>Or,delay:()=>Bn,fibonacci:()=>mo,formatedTime:()=>Gc,getConstructorName:()=>Un,getContainerFromElement:()=>Kh,getEnv:()=>$h,getInternalVersion:()=>Yh,getLoggerUrl:()=>ii,getMuteStateFromFlag:()=>Vn,getNetworkType:()=>kn,getNumNetworkType:()=>$c,getReconnectionTimeout:()=>Jh,getStringByteLength:()=>ef,getTurnServer:()=>Zh,getUint32Version:()=>Jc,getValueType:()=>ut,getViewListFromView:()=>ls,glog:()=>Ln,ipv4ToUint32:()=>us,isArray:()=>it,isAudioWorkletSupported:()=>Qh,isBoolean:()=>nt,isConstructor:()=>ds,isEmpty:()=>Wc,isFunction:()=>Fe,isLangChinese:()=>hr,isMediaStreamTrack:()=>zh,isNumber:()=>$e,isObject:()=>rr,isOverseaSdkAppId:()=>xn,isPlainObject:()=>Bt,isPortrait:()=>qc,isPromise:()=>Ni,isRemoteTrack:()=>Xh,isString:()=>Se,isUndefined:()=>L,loadImage:()=>ms,ms2bytes:()=>qh,ms2samples:()=>zl,performanceNow:()=>ge,promiseAny:()=>Hc,samples2ms:()=>Jl,setNetworkType:()=>Wh,stringify:()=>ir,stringifyIncludeValue:()=>jc,throttlePromise:()=>zc});var zp={};Kr(zp,{getAbilityConfigUrl:()=>vS,getScheduleDomain:()=>Pa,isNeedToSchedule:()=>uu,scheduleProxy:()=>Ar,sendScheduleRequest:()=>Jp,setIsNeedToSchedule:()=>Wo,setScheduleProxy:()=>lu});var qp=null,uu=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ri).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
92
92
|
`));function Wo(i){nt(i)&&i!==uu&&(uu=i,U.info(`setIsNeedToSchedule ${i}`))}F.on("28",()=>Wo(!0));F.on("63",()=>Wo(!0));F.on("84",()=>Wo(!0));F.on("201",i=>{i.state==="RECONNECTING"&&Wo(!0)});F.on("202",i=>{i.state==="RECONNECTING"&&Wo(!0)});function RS(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=Ws(i,D.MAIN),a=Ws(i,D.BACKUP);for(let d of o)if(d.startTime>=e&&(d.name===s||d.name===a)&&d.transferSize>0){let h=d.name===s?D.MAIN:D.BACKUP,m=Math.round(d.duration),T=Math.round(d.domainLookupStart-d.startTime),I=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,v=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,N=Math.round(d.domainLookupEnd-d.domainLookupStart),j=Math.round(d.requestStart-d.secureConnectionStart),H=Math.round(d.secureConnectionStart-d.connectStart),z=Math.round(d.responseStart-d.requestStart),Te=Math.round(d.responseEnd-d.responseStart),Pe=[N,j,H,z,Te];Ve.uploadEvent({log:`stat-schedule-net:${m}(${T}(${I}->${v})->${Pe.join("->")}) ${h}`,userId:t}),r=pe(J({},r),{totalCost:m,local:T,dns:N,tcp:H,tls:j,request:z,response:Te});break}}catch(o){U.error("getScheduleDetailCost error",o)}return r}function Jp(m){return A(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:a,role:d,latencyLevel:h}){if(!uu&&qp)return{isCached:!0,result:qp};let T={delta:0,count:[1,1],msg:[],detail:[]};try{let I=new FormData;I.append("userId",String(i)),I.append("sdkAppId",String(t)),I.append("isStrGroupId",String(e)),I.append("groupId",String(r)),I.append("sdkVersion",s),I.append("userSig",String(o)),d&&I.append("role",String(d)),h&&I.append("latencyLevel",String(h)),a&&I.append("frameWorkType",String(a));let v=ge(),N=yield DS(I,T,t);N.config&&(N.config.loggerDomain&&no(N.config.loggerDomain),nt(N.config.scheduleCache)&&Wo(!N.config.scheduleCache)),T.delta=ge()-v;let j=RS(Number(t),i,v);return qp=N,{isCached:!1,result:N,detailCost:j}}catch(I){let v=it(I)?I[0]:I,N=$e(v.code)?v.code:0,j=`schedule failed${v.message?`: ${v.message}`:""}`,H=new ue({code:Y.SCHEDULE_FAILED,extraCode:N,message:st({key:ot.JOIN_ROOM_FAILED,data:{error:j,code:N}})});throw U.error(j,N),H}})}var Ar={main:"",backup:""};function lu(i){it(i)?(Ar.main=i[0],Ar.backup=i[1]):Ar.main=i}function Ws(i,t=D.MAIN,e=!1){return`https://${Ar[t]||Pa(i,t,e)}/api/v1/config`}function vS(i,t=D.MAIN){return`https://${Ar[t]||Pa(i,t)}/api/v1/trtcAutoConf`}function Pa(i,t=D.MAIN,e=!1){let r;return xn(i)?e?r=t===D.MAIN?ri.MAIN_OVERSEA_BACKUP:ri.BACKUP_OVERSEA:r=t===D.MAIN?ri.MAIN_OVERSEA:ri.BACKUP_OVERSEA:r=t===D.MAIN?ri.MAIN:ri.BACKUP,r}function CS(i,t,e){return new Promise((r,o)=>{oi({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 Y_=(i,t)=>Mi({retryFunction:CS,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function DS(i,t,e){return new Promise((r,o)=>{let s=null;Hc([Y_(a=>t.count[0]=a+1,({error:a,retry:d,retriedCount:h,retryFuncArgs:m})=>{t.msg[0]=a.message,s||(h>=1&&(m[0]=Ws(e,D.MAIN,!0)),d())})(Ws(e,D.MAIN),i,{get timeout(){return mo(2+t.count[0])*1e3}}),Y_(a=>t.count[1]=a+1,({error:a,retry:d,retriedCount:h,retryFuncArgs:m})=>{t.msg[1]=a.message,s||(h>=2&&(m[0]=Ws(e,D.BACKUP,!0)),d())})(Ws(e,D.BACKUP),i,{get timeout(){return mo(2+t.count[1])*1e3}})]).then(a=>{s=a,r(s)}).catch(o)})}var NS=i=>i.startsWith("data:application/octet-stream;base64,"),wS=i=>i.startsWith("file://"),mu=class{constructor(){l(this,"_log");this._log=U.createLogger({id:"fd"})}download(t,e){return A(this,null,function*(){let{type:r="blob"}=e||{};try{let o=ge(),s;if(Fe(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let a=ge()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${a}ms`),X.addSuccessEvent({key:522700,cost:ge()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),X.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return A(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok)throw new Error("network response was not ok");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=()=>{s.status===200||s.status===0&&s.response?r({data:s.response}):o(new Error("XHR failed"))},s.onerror=o,s.send(null)})}loadWasm(t,e){return A(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=ge(),o=null,s=null;if(Fe(WebAssembly.instantiateStreaming)&&!NS(t)&&!wS(t)&&Fe(fetch))try{let a=fetch(t);o=(yield WebAssembly.instantiateStreaming(a,e)).instance}catch(a){s=a}if(!o)try{let a=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(a,e)).instance}catch(a){s=a}if(o){let a=ge()-r;return this._log.info(`loadedWasm ${t}, cost: ${a}ms`),X.addSuccessEvent({key:522701,cost:a}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),X.addFailedEvent({key:522701,error:s}),s})}};G([Ui({settings:{timeout:0,retries:3},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],mu.prototype,"download",1);var Z_=new mu;function K_({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:Z_,innerEmitter:F,constants:ql,environment:bs,utils:jp,eventLogger:Ve,log:this.room.getLogger(),loggerManager:U,errorModule:e,kvStatManager:X,rtcDectection:Li,trtc:this,rx:$p,enums:vm,schedule:zp,clearStarted:(o,s)=>{let a=o.getAlias(),d=Ii.instances.get(this);if(d)if(s){let h=d.get(a+s);if(!h)return;h.started=!1}else d.forEach((h,m)=>{m.startsWith(a)&&(h.started=!1)})},startGetPCM:ba,createAudioNode:Qm}}var eg=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=st({key:ot.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return U.warn(`${s}
|
|
93
93
|
|
|
94
|
-
${o.stack}`),!1}},i};var Gs=new WeakMap;function tg(i){let t=Gs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Gs.delete(i))}function rg(i,t){return Ae((e,r)=>function(...o){let s=Gs.get(this);s||(s=new Map,Gs.set(this,s));let a=t(...o),d=s.get(a);if(!d||d<=0){e.apply(this,o);let h=setTimeout(()=>{var m;(m=Gs.get(this))==null||m.delete(a)},i);s.set(a,h)}else{clearTimeout(d);let h=window.setTimeout(()=>{var m;e.apply(this,o),(m=Gs.get(this))==null||m.delete(a)},i);s.set(a,h)}})}var ig="5.9.0-wasm.12";function Nt(...i){return Ae((t,e)=>function(...r){try{hu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Xp(...i){return Ae((t,e)=>function(...r){try{hu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function hu(i,t,e,r){if(it(i))for(let o=0;o<i.length;o++)pu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else pu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function pu({rule:i,value:t,key:e,fnName:r,className:o}){function s(h){return{code:ae.INVALID_PARAMETER,extraCode:h,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(L(t)){if(i.required)throw new oe(s(5001));if(L(i.defaultValue)){Fe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let h=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(h=!0),Fe(i.type[m])&&t instanceof i.type[m]&&(h=!0),Se(i.type[m])&&ut(t)===i.type[m].toLowerCase()&&(h=!0);if(!h)throw new oe({code:ae.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>ds(m)?Un(m):Se(m)?m:ut(m))},value:t}})}else if(!L(i.type)&&ut(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let h=$e(t)&&(t===0||Number.isNaN(t)),m=Se(t)&&t.trim()==="";if(h||m)throw new oe(s(5003))}if(i.notLessThanZero&&$e(t)&&t<0)throw new oe(s(5006));if(!L(i.min)&&$e(t)&&t<i.min)throw new oe(s(5007));if(!L(i.max)&&$e(t)&&t>i.max)throw new oe(s(5008));if(Se(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Fe(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:a}=i;Bt(a)&&rr(t)&&Object.keys(a).forEach(h=>{pu.call(this,{rule:a[h],value:t&&t[h],key:`${h}`,fnName:r,className:o})});let{arrayItem:d}=i;Bt(d)&&it(t)&&t.forEach((h,m)=>{pu.call(this,{rule:d,value:h,key:`${e}[${m}]`,fnName:r,className:o})}),Fe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function qe(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Ae((s,a)=>function(...d){var I;function h(v,N,j){if(j&&j.includes(v))return"hided";if(e){let H=e(...d);if(d[H.argIndex]===N)return H.value}if(N===d||v in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${ut(N)}`:(JSON.stringify(N),N)}catch(H){return`type:${ut(N)}`}}let m=this._log||U;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${a}() ${JSON.stringify(d,(v,N)=>h(v,N,["userSig","privateMapKey"]))}`):m.info(`${a}()`);let T=r?r(...d):Sd[a];try{let v=s.apply(this,d),N=ge();return Ni(v)?v.then(j=>(m.info(`${a}() success ${t.call(this,...d)}`),X.addSuccessEvent({key:T,cost:ge()-N}),j)).catch(j=>{var Te;j=oe.convertFrom.call(this,j,a,d.length===1?d[0]:d);let H=j.extraCode||j.code,z=(Te=j.message)!=null&&Te.includes(H)?"":` code:${H}`;throw m.error(`${a}() failed ${t.call(this,...d)} ${j}${z} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:j}),j}):(X.addSuccessEvent({key:T}),v)}catch(v){v=oe.convertFrom.call(this,v,a);let N=v.extraCode||v.code,j=(I=v.message)!=null&&I.includes(N)?"":` code:${N}`;throw m.error(`${a}() failed ${v}${j} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:v}),v}})}var fu=i=>Ae((t,e)=>function(r,o){return A(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new oe({code:ae.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Fe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:ae.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return hu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var _u=0,Qp=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Ps(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&&(L(t.volume)||(this.volume=t.volume),L(t.loop)||(this.loop=t.loop),L(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 js(i,t){if(t&&typeof t!="function")throw new oe({code:ae.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var $r=class $r{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(`[audioMixer] created id=${this.getAlias()}${_u}`),this.core=t}getName(){return $r.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return $r.startValidateRule;case"update":return $r.updateValidateRule;case"stop":return $r.stopValidateRule}}start(t){return A(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 Qp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return A(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}a.updateSettings(t),a.updateListener(t),L(r)||a.setOperation(r),L(o)||a.seek(o),this.kvUpload(t)})}stop(e){return A(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:a,seekFrom:d,onTimeUpdate:h,onDurationChange:m,onEnded:T}=t;e&&X.addCount({key:502711}),r&&X.addCount({key:502703}),o&&X.addCount({key:502704}),s&&X.addCount({key:502705}),a&&X.addCount({key:502706}),d&&X.addCount({key:502707}),typeof h!="function"&&X.addCount({key:502709}),typeof T!="function"&&X.addCount({key:502710}),typeof m!="function"&&X.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,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($r,"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"],a=o.split(".").pop(),d=s.indexOf(a)>=0,h=o.startsWith("blob"),m=o.startsWith("data");if(!(d||h||m))throw new oe({code:ae.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:ae.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});js("onTimeUpdate",t.onTimeUpdate),js("onEnded",t.onEnded),js("onDurationChange",t.onDurationChange)}}),l($r,"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){js("onTimeUpdate",t.onTimeUpdate),js("onEnded",t.onEnded),js("onDurationChange",t.onDurationChange)}}),l($r,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l($r,"Name","AudioMixer");var gu=$r;var Eu=0,Yp,Si=class Si{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",lt("denoiser"));l(this,"workletNode");Eu=Eu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Eu}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`)}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:ae.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Yp||(Yp=this.doPreload(t)),Yp}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Ro(this.audioContext,r)}finally{URL.revokeObjectURL(r)}})}getName(){return Si.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Si.startValidateRule(this.core);case"update":return Si.updateValidateRule;case"stop":return Si.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:d}=yield PS(pe(J({},t),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${o}. Message: ${d}`),new oe({code:ae.INVALID_PARAMETER,message:d});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:r,sign:s,status:a}}),this.workletNode.port.onmessage=h=>{let{data:m}=h;m.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${m.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(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(Si,"updateValidateRule",{type:"object"}),l(Si,"stopValidateRule",{type:"object"}),l(Si,"Name","AIDenoiser");var Tu=Si;function OS(i,t=D.MAIN){return`https://${Ar[t]||Pa(i,t)}/api/v1/audioAiAuth`}function PS(o){return A(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let a=`${OS(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,d=yield fetch(a),{data:{errCode:h,errMsg:m,sign:T,status:I}}=yield d.json();if(I==="1")return{auth:!0,sign:T,status:I,message:m};let v="Init RTCAIDenoiser failed.",N="";switch(h){case 1:N="Please check your params.";break;case 2:N="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:N="Server is invalid. Please contact our engineer. ";break;case 4:N="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:N="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:N="Your version is not supported.";break}return{auth:!1,status:I,message:m?`${v} Reason: ${m}. ${N}`:`${v}, ${N}`}})}var og=Ci(ki(),1);var Zp=class extends og.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 A(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){Ve.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)&&U.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){Ve.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},xS=new Zp,Kp=xS;function kS([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 d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Do(new DataView(new Uint8Array(s).buffer),!0)}function LS(i){return i.type==="empty"||i.data.byteLength===0}function US(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function VS(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 eh({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-VS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(kS),s=o.reduce((T,I)=>T+I.dataView.byteLength,0),a=new ArrayBuffer(s+i.data.byteLength),d=new DataView(a),h=new DataView(i.data),m=0;for(let T=0;T<o.length;T++)for(let I=0;I<o[T].dataView.byteLength;I++)d.setInt8(m++,o[T].dataView.getInt8(I));for(let T=0;T<i.data.byteLength;T++)d.setInt8(m++,h.getInt8(T));return i.data=a,i}function th({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(LS(i)||!US(e))return i;let r=[],o=0,s=-1,a=-1;for(let d=0;d<i.data.byteLength;d++){let h=e.getUint8(d);if(h===0)o++;else if(h===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:a===-1&&(a=m,r.push(new Do(new DataView(e.buffer.slice(s,a)))),s=m,a=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var rh=0,xa=class xa{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);rh++,this.log=t.log.createChild({id:`${this.getAlias()}${rh}`}),this.log.info(`[sei] created id=${this.getAlias()}${rh}`),this.core=t,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 eh({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return th({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(K.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:ma?this.encode:eh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:ma?this.decode:th,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 xa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(xa,"autoStart",!0),l(xa,"Name","SEI");var Iu=xa;function ih({frame:i,onDump:t}){return t==null||t(),i}function oh({frame:i,onDump:t}){return t==null||t(),i}var sg={"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:
|
|
94
|
+
${o.stack}`),!1}},i};var Gs=new WeakMap;function tg(i){let t=Gs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Gs.delete(i))}function rg(i,t){return Ae((e,r)=>function(...o){let s=Gs.get(this);s||(s=new Map,Gs.set(this,s));let a=t(...o),d=s.get(a);if(!d||d<=0){e.apply(this,o);let h=setTimeout(()=>{var m;(m=Gs.get(this))==null||m.delete(a)},i);s.set(a,h)}else{clearTimeout(d);let h=window.setTimeout(()=>{var m;e.apply(this,o),(m=Gs.get(this))==null||m.delete(a)},i);s.set(a,h)}})}var ig="5.9.0-wasm.13";function Nt(...i){return Ae((t,e)=>function(...r){try{hu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Xp(...i){return Ae((t,e)=>function(...r){try{hu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function hu(i,t,e,r){if(it(i))for(let o=0;o<i.length;o++)pu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else pu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function pu({rule:i,value:t,key:e,fnName:r,className:o}){function s(h){return{code:ae.INVALID_PARAMETER,extraCode:h,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(L(t)){if(i.required)throw new oe(s(5001));if(L(i.defaultValue)){Fe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let h=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(h=!0),Fe(i.type[m])&&t instanceof i.type[m]&&(h=!0),Se(i.type[m])&&ut(t)===i.type[m].toLowerCase()&&(h=!0);if(!h)throw new oe({code:ae.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>ds(m)?Un(m):Se(m)?m:ut(m))},value:t}})}else if(!L(i.type)&&ut(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let h=$e(t)&&(t===0||Number.isNaN(t)),m=Se(t)&&t.trim()==="";if(h||m)throw new oe(s(5003))}if(i.notLessThanZero&&$e(t)&&t<0)throw new oe(s(5006));if(!L(i.min)&&$e(t)&&t<i.min)throw new oe(s(5007));if(!L(i.max)&&$e(t)&&t>i.max)throw new oe(s(5008));if(Se(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Fe(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:a}=i;Bt(a)&&rr(t)&&Object.keys(a).forEach(h=>{pu.call(this,{rule:a[h],value:t&&t[h],key:`${h}`,fnName:r,className:o})});let{arrayItem:d}=i;Bt(d)&&it(t)&&t.forEach((h,m)=>{pu.call(this,{rule:d,value:h,key:`${e}[${m}]`,fnName:r,className:o})}),Fe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function qe(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Ae((s,a)=>function(...d){var I;function h(v,N,j){if(j&&j.includes(v))return"hided";if(e){let H=e(...d);if(d[H.argIndex]===N)return H.value}if(N===d||v in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${ut(N)}`:(JSON.stringify(N),N)}catch(H){return`type:${ut(N)}`}}let m=this._log||U;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${a}() ${JSON.stringify(d,(v,N)=>h(v,N,["userSig","privateMapKey"]))}`):m.info(`${a}()`);let T=r?r(...d):Sd[a];try{let v=s.apply(this,d),N=ge();return Ni(v)?v.then(j=>(m.info(`${a}() success ${t.call(this,...d)}`),X.addSuccessEvent({key:T,cost:ge()-N}),j)).catch(j=>{var Te;j=oe.convertFrom.call(this,j,a,d.length===1?d[0]:d);let H=j.extraCode||j.code,z=(Te=j.message)!=null&&Te.includes(H)?"":` code:${H}`;throw m.error(`${a}() failed ${t.call(this,...d)} ${j}${z} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:j}),j}):(X.addSuccessEvent({key:T}),v)}catch(v){v=oe.convertFrom.call(this,v,a);let N=v.extraCode||v.code,j=(I=v.message)!=null&&I.includes(N)?"":` code:${N}`;throw m.error(`${a}() failed ${v}${j} params: ${JSON.stringify(d,h)}`),X.addFailedEvent({key:T,error:v}),v}})}var fu=i=>Ae((t,e)=>function(r,o){return A(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new oe({code:ae.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Fe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:ae.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return hu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var _u=0,Qp=class{constructor(t,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Ps(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&&(L(t.volume)||(this.volume=t.volume),L(t.loop)||(this.loop=t.loop),L(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 js(i,t){if(t&&typeof t!="function")throw new oe({code:ae.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var $r=class $r{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(`[audioMixer] created id=${this.getAlias()}${_u}`),this.core=t}getName(){return $r.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return $r.startValidateRule;case"update":return $r.updateValidateRule;case"stop":return $r.stopValidateRule}}start(t){return A(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 Qp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return A(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}a.updateSettings(t),a.updateListener(t),L(r)||a.setOperation(r),L(o)||a.seek(o),this.kvUpload(t)})}stop(e){return A(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:a,seekFrom:d,onTimeUpdate:h,onDurationChange:m,onEnded:T}=t;e&&X.addCount({key:502711}),r&&X.addCount({key:502703}),o&&X.addCount({key:502704}),s&&X.addCount({key:502705}),a&&X.addCount({key:502706}),d&&X.addCount({key:502707}),typeof h!="function"&&X.addCount({key:502709}),typeof T!="function"&&X.addCount({key:502710}),typeof m!="function"&&X.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,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($r,"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"],a=o.split(".").pop(),d=s.indexOf(a)>=0,h=o.startsWith("blob"),m=o.startsWith("data");if(!(d||h||m))throw new oe({code:ae.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:ae.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});js("onTimeUpdate",t.onTimeUpdate),js("onEnded",t.onEnded),js("onDurationChange",t.onDurationChange)}}),l($r,"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){js("onTimeUpdate",t.onTimeUpdate),js("onEnded",t.onEnded),js("onDurationChange",t.onDurationChange)}}),l($r,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l($r,"Name","AudioMixer");var gu=$r;var Eu=0,Yp,Si=class Si{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",lt("denoiser"));l(this,"workletNode");Eu=Eu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Eu}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`)}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:ae.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Yp||(Yp=this.doPreload(t)),Yp}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Ro(this.audioContext,r)}finally{URL.revokeObjectURL(r)}})}getName(){return Si.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Si.startValidateRule(this.core);case"update":return Si.updateValidateRule;case"stop":return Si.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:d}=yield PS(pe(J({},t),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${o}. Message: ${d}`),new oe({code:ae.INVALID_PARAMETER,message:d});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:r,sign:s,status:a}}),this.workletNode.port.onmessage=h=>{let{data:m}=h;m.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${m.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(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(Si,"updateValidateRule",{type:"object"}),l(Si,"stopValidateRule",{type:"object"}),l(Si,"Name","AIDenoiser");var Tu=Si;function OS(i,t=D.MAIN){return`https://${Ar[t]||Pa(i,t)}/api/v1/audioAiAuth`}function PS(o){return A(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let a=`${OS(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,d=yield fetch(a),{data:{errCode:h,errMsg:m,sign:T,status:I}}=yield d.json();if(I==="1")return{auth:!0,sign:T,status:I,message:m};let v="Init RTCAIDenoiser failed.",N="";switch(h){case 1:N="Please check your params.";break;case 2:N="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:N="Server is invalid. Please contact our engineer. ";break;case 4:N="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:N="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:N="Your version is not supported.";break}return{auth:!1,status:I,message:m?`${v} Reason: ${m}. ${N}`:`${v}, ${N}`}})}var og=Ci(ki(),1);var Zp=class extends og.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 A(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){Ve.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)&&U.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){Ve.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},xS=new Zp,Kp=xS;function kS([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 d=0;d<r;d++)s.push(255);s.push(o);let a=new DataView(t);return s.push(...new Uint8Array(a.buffer)),s.push(128),new Do(new DataView(new Uint8Array(s).buffer),!0)}function LS(i){return i.type==="empty"||i.data.byteLength===0}function US(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function VS(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 eh({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-VS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(kS),s=o.reduce((T,I)=>T+I.dataView.byteLength,0),a=new ArrayBuffer(s+i.data.byteLength),d=new DataView(a),h=new DataView(i.data),m=0;for(let T=0;T<o.length;T++)for(let I=0;I<o[T].dataView.byteLength;I++)d.setInt8(m++,o[T].dataView.getInt8(I));for(let T=0;T<i.data.byteLength;T++)d.setInt8(m++,h.getInt8(T));return i.data=a,i}function th({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(LS(i)||!US(e))return i;let r=[],o=0,s=-1,a=-1;for(let d=0;d<i.data.byteLength;d++){let h=e.getUint8(d);if(h===0)o++;else if(h===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:a===-1&&(a=m,r.push(new Do(new DataView(e.buffer.slice(s,a)))),s=m,a=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var rh=0,xa=class xa{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);rh++,this.log=t.log.createChild({id:`${this.getAlias()}${rh}`}),this.log.info(`[sei] created id=${this.getAlias()}${rh}`),this.core=t,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 eh({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return th({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(K.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:ma?this.encode:eh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:ma?this.decode:th,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 xa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(xa,"autoStart",!0),l(xa,"Name","SEI");var Iu=xa;function ih({frame:i,onDump:t}){return t==null||t(),i}function oh({frame:i,onDump:t}){return t==null||t(),i}var sg={"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:
|
|
95
95
|
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.
|
|
96
96
|
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:
|
|
97
97
|
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.
|
|
98
|
-
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"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{sg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var Wk=Object.keys(sg);var FS=0,Su,qs=class qs{constructor(t){this.core=t;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++FS}`}),this.log.info("created")}getName(){return qs.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){try{if(Su)yield Su;else{let t=Date.now();Su=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ke}.js`),yield Su,this.log.info(`download debug dialog script cost: ${Date.now()-t}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(t){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(t))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):ih,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):oh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return ih({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return oh({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};l(qs,"Name","Debug"),l(qs,"autoStart",!0),G([Ui({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],qs.prototype,"loadScript",1);var yu=qs;var ng=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Au=class{constructor(t,e,r){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=De(e,re.INIT),this.stopOB=gt(this.trackDoneOB),this.startOB=gt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let a=gt(),d=h=>{let m=this.pipe(e);return a.next("STARTING"),e.log.info(`decoder type: ${this.type}`),be(m,We(this.stopOB),ke(()=>{},T=>{e.log.error(T),o.addFailedEvent({key:ng(this.type),error:T}),h>4?this.startOB.error(T):this.startOB.next(h+1)})),be(m,Sr(1),va(ko))};be(this.startOB,xo(0),Fr(d),We(this.stopOB),ke(()=>{e.player.setOutput(),a.next("STARTED")},h=>{a.next("FAILED")},()=>{o.addSuccessEvent({key:ng(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return gi()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},BS={type:"object"},ka=class ka{constructor(t){this.core=t;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return ka.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return ka.Name}getValidateRule(t){return BS}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new Au(this.core,r,t);return be(o.trackDoneOB,Sr(1),ke(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new Au(this.core,t.track,t))}}};l(ka,"Name","TRTCAudioDecoder");var La=ka;var ag=0,Ua=new Set,Tt=null;Ll(ig);Rs.checkStorage();Vm();var $S={RtcError:oe,ErrorCode:ae,ErrorCodeDictionary:yr},le=class le extends cg.EventEmitter{constructor(e,r){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",U.createLogger({id:`t${++ag}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(J({logger:this._log,frameWorkType:le.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(a=>a.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(gu,r.assetsPath),this._use(Tu,r.assetsPath),this._use(La,r.assetsPath||Oc),this._use(yu),r.enableSEI&&pa&&this._use(Iu),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(K.AUDIO_VOLUME,{result:o.sort((s,a)=>a.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ae.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),eg(this,"trtc")}static create(e){}static _create(e,r){H_();let o=new le(e,r||{});return Ua.add(o),o}get room(){return this._room}_listenEvents(){vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(K.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(K.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(K.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(K.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(K.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=pe(J({},e),{uplinkRTT:Math.min(e.uplinkRTT,On),downlinkRTT:Math.min(e.downlinkRTT,On)});this.emit(K.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{vt(o,o).add("player-state-changed",s=>{let a=pe(J({},s),{userId:e.userId});o.kind===D.VIDEO&&(a.streamType=qi(o.streamType)),this.emit(o.kind===D.AUDIO?K.AUDIO_PLAY_STATE_CHANGED:K.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",s=>{s.getCode()===Y.PLAY_NOT_ALLOWED&&this.emit(K.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{at(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,a=e.videoAvailable,{audioAvailable:d,videoAvailable:h}=r;d||this._remoteAudioConfigMap.delete(o),h||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),a!==h&&(h?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(h?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?K.REMOTE_AUDIO_AVAILABLE:K.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(K.SEI_MESSAGE,pe(J({},e),{streamType:qi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(K.ERROR,new oe({code:ae.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,a,d,h,m,T,I;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,On),upLoss:((h=this._networkQuality)==null?void 0:h.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((T=e.msg_up_stream_info.msg_audio_status)==null?void 0:T.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((I=e.msg_up_stream_info.msg_audio_status)==null?void 0:I.uint32_audio_level)||0)/di},video:e.msg_up_stream_info.msg_video_status.filter(v=>r[v.uint32_video_stream_type]).map(v=>({bitrate:(v.uint32_video_codec_bitrate||0)/1e3,width:v.uint32_video_width,height:v.uint32_video_height,frameRate:v.uint32_video_enc_fps,videoType:r[v.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(v=>({userId:v.msg_user_info.str_identifier,audio:{bitrate:(v.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(v.msg_audio_status.uint32_audio_level||0)/di},video:v.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(K.STATISTICS,o)}).add("custom-message",e=>{this.emit(K.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(K.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},e),{streamType:qi(e.streamType)}))}),vt(this,ht).add("audioInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Tt&&Tt.deviceId===Mn){let r=(yield Vi()).find(o=>o.deviceId===Mn);r&&Tt.groupId!==r.groupId&&(Tt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Vi())[0];if(!r||!Tt||Tt.groupId===r.groupId)return;let o=Tt.deviceId===e.deviceId,s=Tt.deviceId===Mn&&Tt.deviceId===r.deviceId;(o||s)&&(Tt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||Oc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(K_.call(this,{TRTC:le,room:this._room,errorModule:$S,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var h,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Se(e.proxy)&&e.proxy.turnServer&&((m=(h=this._room).setTurnServer)==null||m.call(h,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,nt(e.preferHW)&&(this._room.preferHW=e.preferHW);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,le.frameWorkType),this._checkTrackToPublish(),Kp.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return A(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){at(this),this.removeAllListeners(),this._room.destroy(),Ua.delete(this),Ua.size===0&&Kp.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,a=new fi(this._room.audioManager),d={},h={muted:!0};s&&(L(s.microphoneId)?L(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&$e(s.captureVolume)&&a.setCaptureVolume(s.captureVolume),L(s.profile)||(Se(s.profile)?xc[s.profile]&&a.setProfile(xc[s.profile]):a.setProfile(s.profile)),$e(s.earMonitorVolume)&&(h.muted=!(s.earMonitorVolume>0),h.volume=s.earMonitorVolume),L(s.echoCancellation)||(a.profile.echoCancellation=s.echoCancellation),L(s.noiseSuppression)||(a.profile.noiseSuppression=s.noiseSuppression),L(s.autoGainControl)||(a.profile.autoGainControl=s.autoGainControl)),a.on("5",m=>{this.emit(K.ERROR,new oe({code:ae.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),a.on("2",m=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),a.on("4",m=>{let T;m.error&&(T=oe.convertFrom(m.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},m),{error:T}))}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),L(o)||a.setMute(o),vt(a,a).add("player-state-changed",m=>{this.emit(K.AUDIO_PLAY_STATE_CHANGED,pe(J({},m),{userId:""}))}),this.listeners(K.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(le.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&a.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(le.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._localAudioConfig=pe(J({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:h,track:a})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,a={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):L(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),L(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),L(s.earMonitorVolume)||(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!L(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),L(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Or(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),at(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:a}=e,d=new Ir(this._room.videoManager),h={},m={};a&&(a.cameraId?h.deviceId=a.cameraId:L(a.useFrontCamera)?L(a.videoTrack)||(h.customSource=a.videoTrack):h.facingMode=a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,a.qosPreference&&(h.contentHint=Oa(a.qosPreference)),L(a.profile)||(Se(a.profile)?wr[a.profile]&&d.setProfile(wr[a.profile]):d.setProfile(a.profile)),L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror),L(a.small)||(ua()?Se(a.small)?d.small=wr[a.small]:a.small===!0?d.small=wr["120p"]:d.small=a.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",T=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},T),{streamType:qi(T.streamType)}))}),d.on("5",T=>{this.emit(K.ERROR,new oe({code:ae.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let I;T.error&&(I=oe.convertFrom(T.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},T),{error:I}))}),this._listenOutputTrackChanged(d),yield d.capture(h),L(s)||(yield d.setMute(s)),vt(d,d).add("player-state-changed",T=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,pe(J({},T),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=pe(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:a}=e,d={};if(a)if(L(a.profile)||(Se(a.profile)?wr[a.profile]&&this._localVideoTrack.setProfile(wr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&L(a.useFrontCamera)&&this._localVideoTrack.applyProfile()),a.cameraId?yield this._localVideoTrack.switchDevice(a.cameraId):L(a.useFrontCamera)?L(a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a.videoTrack)):yield this._localVideoTrack.switchDevice(a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),L(a.fillMode)||(d.objectFit=a.fillMode),L(a.mirror)||(d.mirror=a.mirror),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Oa(a.qosPreference)),a.small){let h=!this._localVideoTrack.small;ua()?(a.small===!0?this._localVideoTrack.small=wr["120p"]:Se(a.small)?this._localVideoTrack.small=wr[a.small]:this._localVideoTrack.small=a.small,this._room.videoManager.update(),h&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else a.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!L(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),L(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Or(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),at(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,a=new Bi(this._room.videoManager);a.on("4",I=>{let v;I.error&&(v=oe.convertFrom(I.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},I),{error:v}))}),a.once("first-video-frame",I=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},I),{streamType:qi(I.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,h={},m={};s&&(L(s.profile)||(Se(s.profile)?kc[s.profile]&&a.setProfile(kc[s.profile]):a.setProfile(s.profile)),s.systemAudio&&(h.systemAudio=!0,h.echoCancellation=s.echoCancellation,h.noiseSuppression=s.noiseSuppression,h.autoGainControl=s.autoGainControl),L(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(h.videoTrack=s.videoTrack),s.audioTrack&&(h.audioTrack=s.audioTrack),s.captureElement&&(h.captureElement=s.captureElement),s.preferDisplaySurface&&(h.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(h.contentHint=Oa(s.qosPreference)));let T=yield a.capture(h);if(a.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(K.SCREEN_SHARE_STOPPED)}),T.getAudioTracks()[0]&&(d=new wo(this._room.audioManager),yield d.setInputMediaStreamTrack(T.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),vt(a,a).add("player-state-changed",I=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,pe(J({},I),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let I=[a];d&&I.push(d),this._room.publish(...I).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=pe(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:a})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,a={};if(s&&(L(s.fillMode)||(a.objectFit=s.fillMode),s.qosPreference)){let d=Oa(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!L(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Or(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let h=this._room.remotePublishedUserMap.get(o);if(!h)return;let m={},T=s==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack;this._listenOutputTrackChanged(T),a&&(L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror),m.canvasRender=a.canvasRender,s==="main"&&!L(a.small)&&(h.remoteVideoTrack.setMediaType(a.small?8:4),this._room.changeType(a.small,T.user))),yield this._room.subscribe(T),yield this._enableVideoDecodeFallback(T,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:T}),this._emitTrackEvent(T),this._remoteVideoConfigMap.set(d,{config:e}),a&&!L(a.receiveWhenViewVisible)&&this._observeView({remoteTrack:T,view:r,receiveWhenViewVisible:a.receiveWhenViewVisible,viewRoot:a==null?void 0:a.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var z,Te;let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`,h=this._remoteVideoConfigMap.get(d);if(!h||!this._room.remotePublishedUserMap.has(o))return;let m={};a&&(L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror));let T=null,I=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(I!=null&&I.muteState.hasVideo)&&(T=I.remoteVideoTrack),s==="sub"&&(I!=null&&I.muteState.hasAuxiliary)&&(T=I.remoteAuxiliaryTrack),!T)return;let{config:v}=h;s==="main"&&a&&!L(a.small)&&this._room.changeType(a.small,T.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:T,prevConfig:v}),Or(v,e);let N=L(a==null?void 0:a.receiveWhenViewVisible)?(z=v.option)==null?void 0:z.receiveWhenViewVisible:a.receiveWhenViewVisible,j=L(r)?v.view:r,H=L(a==null?void 0:a.viewRoot)?(Te=v.option)==null?void 0:Te.viewRoot:a.viewRoot;this._observeView({remoteTrack:T,view:j,receiveWhenViewVisible:N,viewRoot:H})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return A(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(h.stop(),d.hasVideo&&o.push(h)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));let a=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);a&&a.observer&&a.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return A(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return A(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return A(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===le.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(le.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(le.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{Q_.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,a;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===le.EVENT.AUDIO_FRAME&&((a=this._getPCMAbortCtrl)==null||a.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",a=!1;if(Se(e)?r=e:(r=e.userId,a=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?a&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,a=null;if(r==="")o==="main"&&this._localVideoTrack&&(a=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(a=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(a=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return a?s&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Vi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Tt=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),h=$e(d)?d:100;s.volume=h,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(a),be(De(a,"decode-failed"),We(De(a,re.INIT)),ke(()=>{this.startPlugin(La.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:a})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(a)})}_stopRemoteAudio(e,r=!0){return A(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;!o||!this._plugins.has("TRTCVideoDecoder")||(this._log.debug("remote video will fall back when decode failed"),be(De(e,"decode-failed"),We(De(e,re.INIT)),Ca(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Vo(De(e,"decode-downgrade-state-changed")),ke(s=>{this.emit(K.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,pe(J({},s),{streamType:r,userId:e.userId}))},s=>{this._log.error("fallback",s)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(a){return A(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),L(e)&&s&&s.view&&!Wc(r)){let d=ls(s.view);d.length>0&&(yield o.play(d,r))}if(!L(e)){let d=ls(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return A(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(a){}L(e.muted)||r.setPlayerMute(e.muted),L(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(K.TRACK,{userId:o,streamType:qi(e.streamType),track:e.outMediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(L(r))return;let a=this._remoteVideoConfigMap.get(`${e.userId}_${qi(e.streamType)}`);if(!a)return;let d=a.observer||void 0;if(r===null||it(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=a.visibleViewMap||new Map,T=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(v=>{v.forEach(N=>{m.set(N.target,N.isIntersecting)}),clearTimeout(T),T=window.setTimeout(()=>{[...m.values()].find(j=>j)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let I=new Set(ls(r));m.forEach((v,N)=>{I.has(N)||(d.unobserve(N),m.delete(N))}),I.forEach(v=>{m.set(v,!0),d.observe(v)}),d.takeRecords().forEach(v=>{m.set(v.target,v.isIntersecting)}),a.visibleViewMap=m,a.observer=d}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),tg(this),this._room.remotePublishedUserMap.forEach(e=>{at(e.remoteAudioTrack),at(e.remoteVideoTrack),at(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),at(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Tt||xs(Tt))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(Tt&&!xs(Tt))this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:Tt});else{let e=yield Vi();e[0]&&!xs(e[0])?(Tt=e[0],this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,a=[s];this._room.autoReceiveAudio&&a.push(o.remoteAudioTrack),this._room.subscribe(...a).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:pe(J({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){U.setLogLevel(e),L(r)||(r?U.enableUploadLog():U.disableUploadLog())}static isSupported(){return Rd()}static getCameraList(e=!0){return er(e)}static getMicrophoneList(e=!0){return Gt(e)}static getSpeakerList(e=!0){return Vi(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(pt&&(e===nr.SPEAKER||e===nr.HEADSET)){let o=yield le.getMicrophoneList(),s="";if(o.forEach(a=>{a.label===e&&(s=a.deviceId)}),!s)return;Ua.forEach(a=>A(this,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Vi()).forEach(o=>{o.deviceId===e&&(Ua.forEach(s=>{s._setCurrentSpeaker(e),s.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Tt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:a,version:d}){switch(d&&(yo.version=d),e){case"count":yo.addCount({key:r,useUV:a});break;case"enum":yo.addEnum({key:r,value:o,useUV:a});break;case"number":yo.addNumber({key:r,value:o,split:s});break}}};l(le,"_loggerManager",U),l(le,"EVENT",K),l(le,"ERROR_CODE",ae),l(le,"TYPE",nr),l(le,"frameWorkType",30),G([qe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],le.prototype,"use",1),G([Nt(Et.TRTC.enterRoom),Gi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Ae(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),qe()],le.prototype,"enterRoom",1),G([qe()],le.prototype,"exitRoom",1),G([Nt(Et.TRTC.switchRole),Ho("room",{merge:(e,r)=>r}),qe()],le.prototype,"switchRole",1),G([qe()],le.prototype,"destroy",1),G([Nt(Et.TRTC.startLocalAudio),Gi("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),qe()],le.prototype,"startLocalAudio",1),G([Nt(Et.TRTC.updateLocalAudio),Ho("audio",{debounce:{delay:200,getKey:()=>`${ag}-localAudio`,isNeedToDebounce:e=>{var r;return!L((r=e.option)==null?void 0:r.captureVolume)}}}),qe()],le.prototype,"updateLocalAudio",1),G([ji("audio"),qe()],le.prototype,"stopLocalAudio",1),G([Nt(Et.TRTC.startLocalVideo),Gi("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),qe()],le.prototype,"startLocalVideo",1),G([Nt(Et.TRTC.updateLocalVideo),Ho("video"),qe()],le.prototype,"updateLocalVideo",1),G([ji("video"),qe()],le.prototype,"stopLocalVideo",1),G([Nt(Et.TRTC.startScreenShare),Gi("screen",()=>!0),qe()],le.prototype,"startScreenShare",1),G([Nt(Et.TRTC.updateScreenShare),Ho("screen"),qe()],le.prototype,"updateScreenShare",1),G([qe()],le.prototype,"stopScreenShare",1),G([Nt(Et.TRTC.startRemoteVideo),Gi(e=>`v${e.userId}${e.streamType}`,()=>!0),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"startRemoteVideo",1),G([Nt(Et.TRTC.updateRemoteVideo),Ho(e=>`v${e.userId}${e.streamType}`),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"updateRemoteVideo",1),G([Nt(Et.TRTC.stopRemoteVideo),Ae(e=>function(r){return A(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"stopRemoteVideo",1),G([ji(e=>`v${e.userId}${e.streamType}`)],le.prototype,"_stopRemoteVideo",1),G([Nt(...Et.TRTC.muteRemoteAudio),qe({getRemoteId:e=>e})],le.prototype,"muteRemoteAudio",1),G([Xp(...Et.TRTC.setRemoteAudioVolume),rg(200,e=>e),qe({getRemoteId:e=>e})],le.prototype,"setRemoteAudioVolume",1),G([fu("start"),Fi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Gi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Nm[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],le.prototype,"startPlugin",1),G([fu("update"),Ho((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>wm[e.getName()]})],le.prototype,"updatePlugin",1),G([fu("stop"),ji((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Mm[e.getName()]})],le.prototype,"stopPlugin",1),G([Xp(...Et.TRTC.enableAudioVolumeEvaluation)],le.prototype,"enableAudioVolumeEvaluation",1),G([qe()],le.prototype,"getVideoSnapshot",1),G([qe()],le.prototype,"_setCurrentSpeaker",1),G([Gi(e=>`a${e.userId}`,()=>!0)],le.prototype,"_startRemoteAudio",1),G([Ae(e=>function(r){return A(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(pe(J({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),ji(e=>`a${e.userId}`)],le.prototype,"_stopRemoteAudio",1),G([ji("room")],le.prototype,"_exitRoom",1),G([ji("screen")],le.prototype,"_stopScreenShare",1),G([Nt(...Et.TRTC.sendSEIMessage),Hp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],le.prototype,"sendSEIMessage",1),G([Nt(Et.TRTC.sendCustomMessage),Hp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],le.prototype,"sendCustomMessage",1),G([Nt(Et.TRTC.create)],le,"_create",1);var sh=le,Js=sh;var bu=class{constructor(t,e){l(this,"_flag");l(this,"terminalType");l(this,"userId");l(this,"tinyId");l(this,"role");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Mo(t,this),this.remoteVideoTrack=new Hi(t,this),this.remoteAuxiliaryTrack=new ou(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Vn(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var nh=class{constructor(){l(this,"_set",new Set);F.on(P.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function HS(){return A(this,null,function*(){let i,t;try{let I=yield Gt();i=I&&I.length}catch(I){}try{let I=yield er();t=I&&I.length}catch(I){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:a}=this.checkSystemResult.detail,d=Li.basis(),h={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:a},m={browser:d.browser,os:d.os,trtc:h,devices:e},T={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Ve.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),Ve.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId})})}function dg(){return Ae(i=>{let t=new nh;return function(e,r,o){return A(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),F.emit(P.JOIN_START,{room:this,roomId:s,params:e});let a=Pr.getEnv();a||(a=ei.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Lc.OLD_CLOUD_LADDER)?a=ei.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Lc.WEBRTC)&&(a=ei.WEBRTC))),Ve.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Li.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,HS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Pr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Pr.performanceNow(),F.emit(P.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Ve.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),F.emit(P.JOIN_FAILED,{room:this,error:d}),d}})}})}var ug=()=>Ae(i=>function(...t){return A(this,null,function*(){F.emit(P.LEAVE_START,{room:this}),yield i.call(this),F.emit(P.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function lg(){return Ae(i=>function(...t){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;F.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function mg(){return Ae(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function pg(){return Ae(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function WS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Ni(r)?r.catch(o=>U.error(`${i.name}() error observed ${o}`)):r}catch(r){U.error(`${i.name}() error observed ${r}`)}}}var Ru=class{constructor(t){l(this,"_frameWorkType");l(this,"_component");l(this,"_language");l(this,"connectionType");l(this,"_room");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_keyPrefix");l(this,"_log");l(this,"_intervalId");l(this,"_firstPublishedUserList");l(this,"_networkQuality");l(this,"_basicInfo");l(this,"_pathJoinRoom");l(this,"_pathLeaveRoom");l(this,"_pathMainVideoMap");l(this,"_pathMainAudioMap");l(this,"_pathAuxiliaryMap");l(this,"_remoteStreamStatMap");l(this,"_localStreamStat");l(this,"_eventMap",new Map);l(this,"_captureCostSum",0);l(this,"_captureCostCount",0);l(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=U.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Fe(this[e])&&(this[e]=WS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ke,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Kn().then(t=>{this._basicInfo.string_os_version=_o(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),F.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(P.JOIN_START,this.handleJoinStart).addEvent(P.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(P.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(P.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(P.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(P.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(P.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(P.JOIN_FAILED,this.handleJoinFailed).addEvent(P.LEAVE_START,this.handleLeaveStart).addEvent(P.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(P.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(P.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(P.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(P.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(P.PUBLISH_START,this.handlePublishStart).addEvent(P.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(P.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(P.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(P.PLAY_TRACK_START,this.handlePlayStart).addEvent(P.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(P.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(P.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(P.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(P.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(P.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((t,e)=>F.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),ft.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(L(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),L(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),L(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:a,tls:d,request:h,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=h,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof ue?Number(e.getExtraCode()||e.getCode()):Y.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:pe(J({},GS),{msg_user_info:new Va({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:a,role:d}=e,h=new Va({userId:s,tinyId:a,role:d==="anchor"?20:21}),m=Date.now(),T=`${s}_${r}`,I=this._remoteStreamStatMap.get(T);I&&I.subscribeStartTime===0&&(I.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(T)&&this._pathMainVideoMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(T)&&this._pathMainAudioMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(T)&&this._pathAuxiliaryMap.set(T,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(o&&(o.statsToReport.uint64_render_first_frame_time===0&&(o.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:d,playStreamTime:h,subscribedTime:m}=s;d.uint32_video_render_first===0&&h-m<=100&&(d.uint32_video_render_first=r-o.sendSubscribeCMDTime)}let a=this._pathAuxiliaryMap.get(e);if(a&&s){let{statsToReport:d,playStreamTime:h,subscribedTime:m}=s;d.uint32_video_render_first===0&&h-m<=100&&(d.uint32_video_render_first=r-a.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:a})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),a&&(d.totalAudioDelay=(d.totalAudioDelay||0)+a,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let h,m,T,I;s&&(m=s,T=1),a&&(h=a,I=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:h,totalVideoDelay:m,audioDelayCount:I,videoDelayCount:T})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:h}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=h,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/di*100)>0&&(this._localStreamStat.totalAudioLevel+=s/di,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:h}=s,m=a.str_identifier,T=this._room.remotePublishedUserMap.get(m);if(h.forEach(I=>{let v=I.uint32_video_stream_type===2,N=I.uint32_video_stream_type===7,j=`${m}_${v?"main":"auxiliary"}`,H=this._remoteStreamStatMap.get(j);if(H&&(v&&(T!=null&&T.remoteVideoTrack.isSubscribed)||N&&(T!=null&&T.remoteAuxiliaryTrack))){H.totalVideoFPS+=I.uint32_video_receive_fps,H.totalVideoBitrate+=I.uint32_video_codec_bitrate,H.videoCount++,H.statsToReport.uint32_video_width===0&&(H.statsToReport.uint32_video_width=I.uint32_video_width),H.statsToReport.uint32_video_height===0&&(H.statsToReport.uint32_video_height=I.uint32_video_height);let z=v?T.remoteVideoTrack:T.remoteAuxiliaryTrack;z.stat.jitterBufferDelay&&(H.videoJitterBufferDelay=z.stat.jitterBufferDelay),z.stat.framesReceived&&(H.statsToReport.uint32_video_consume_render_rate=Math.floor(z.stat.framesDecoded/z.stat.framesReceived*Rn(10,6)))}}),d){let I=`${m}_main`,v=this._remoteStreamStatMap.get(I);this._remoteStreamStatMap.has(I)&&v&&T!=null&&T.remoteAudioTrack.isSubscribed&&(v.totalAudioBitrate+=d.uint32_audio_codec_bitrate,v.audioCount++,T.remoteAudioTrack.stat.jitterBufferDelay&&(v.audioJitterBufferDelay=T.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/di*100)>0&&(v.totalAudioLevel+=d.uint32_audio_level/di,v.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof ue?e.getExtraCode()||e.getCode():Y.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ss)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ns)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&wn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:T,count:I,audioDelayCount:v,videoDelayCount:N,totalAudioDelay:j,totalVideoDelay:H}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(T/I),v&&j&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(j/v),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&H&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(H/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Go);let{badCaseDetector:a}=this._room,{dataFreeze:d,count:h}=a.getDataFreezeDuration(e),{renderFreeze:m}=a.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=h,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),a.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Go&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Go)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Go&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Go)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Go&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Go)}getReportData(){this._basicInfo.uint32_networkType=$c();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Va({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:us(this._signalInfo.relayIp),uint32_client_ip:us(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Rn(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:us(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Fn(t),t}report(){return A(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return A(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Xl(t),o=r instanceof ArrayBuffer,s=`${ii(e,Di.KEY_POINT)}&gzip=${+o}`,a=!1;navigator.sendBeacon&&(a=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(X),this.uploadKVStat(yo)];a||d.push(oi({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return A(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=pe(J({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield Xl(e),o=`${ii(+this._room.sdkAppId,Di.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||oi({url:o,body:r})})}};G([Ui({settings:{timeout:500,retries:3}})],Ru.prototype,"upload",1);var Go=5e3,GS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Va=class{constructor(t){l(this,"str_identifier");l(this,"str_tinyid");l(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},hg=Ru;var ah=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ge())}stop(){this._endTime===0&&(this._endTime=ge())}getDuration(){return this._endTime===0?ge()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},zs=ah;var ch=class{constructor(t){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(P.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(P.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var a;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>F.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>F.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let a=new zs,d=this._durationMap.get(s);d?this.isRecording(d.audio)||d.audio.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[a],video:[]})}else this.stopDurationItem(s,D.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let a=new zs,d=this._durationMap.get(s);d?this.isRecording(d.video)||d.video.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[],video:[a]})}else this.stopDurationItem(s,D.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDurationItem(s,D.AUDIO),this.stopDurationItem(s,D.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new zs,a=this._durationMap.get(o);a?this.isRecording(a[e])||a[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},fg=ch;var dh=class{constructor(t){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(P.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(P.PLAY_TRACK_START,this.onPlayTrackStart).set(P.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}}).set(P.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(P.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>F.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>F.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),a=new zs;s?s.durationItemList.push(a):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[a],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:a}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&a.hasVideo&&!a.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&a.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let a=s.getDuration();a>Fc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:a}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return A(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,a=this._renderFreezeMap.get(s);if(e<=2){let d=ge();a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:d,endTime:0}),a.isFreeze=!0),a||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(a&&a.isFreeze){a.isFreeze=!1;let d=a.freezeTimeline.pop();if(d){d.endTime=ge();let h=d.endTime-d.startTime;a.freezeTimeline.push(d),a.renderFreezeTotal+=Math.min(5e3,h)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||!t.isAvailable)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<Fc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=ge(),a=e.freezeTimeline[e.freezeTimeline.length-1],d=s-a.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},_g=dh;var Eg=Ci(ki(),1);var jS=[1,0,0,0,1,1,0,1],vu=class extends Vt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof _t)try{this.setTexBuffer(jS)}catch(r){t.destroy(new ue({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let a=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),a}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var uh=class{constructor(t,e){this.node=t;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Cu=class extends Vt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});l(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new uh(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,a)=>a?Object.assign(s,{width:Math.max(s.width,a.right),height:Math.max(s.height,a.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof _t&&this.inputs.forEach(s=>{if(s){let a=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,a):s.positionBuffer=this.createBuffer(a)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,a)=>(!a||!a.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let a=this.inputs[s];a&&(a.node.useTexture(),this.draw(a.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:a,name:d}=this,h=Date.now(),m=(e-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:h,fps:m,name:d},J({parent:this.inputs.filter(T=>T).map(T=>T.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof _t))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var qS=`#version 300 es
|
|
98
|
+
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"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{sg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var Wk=Object.keys(sg);var FS=0,Su,qs=class qs{constructor(t){this.core=t;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++FS}`}),this.log.info("created")}getName(){return qs.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){try{if(Su)yield Su;else{let t=Date.now(),e=new URLSearchParams(location.search).get("trtcDebugDialogVersion")||Ke;Su=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${e}.js`),yield Su,this.log.info(`download debug dialog script cost: ${Date.now()-t}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(t){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(t))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):ih,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):oh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return ih({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return oh({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};l(qs,"Name","Debug"),l(qs,"autoStart",!0),G([Ui({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],qs.prototype,"loadScript",1);var yu=qs;var ng=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Au=class{constructor(t,e,r){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=De(e,re.INIT),this.stopOB=gt(this.trackDoneOB),this.startOB=gt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let a=gt(),d=h=>{let m=this.pipe(e);return a.next("STARTING"),e.log.info(`decoder type: ${this.type}`),be(m,We(this.stopOB),ke(()=>{},T=>{e.log.error(T),o.addFailedEvent({key:ng(this.type),error:T}),h>4?this.startOB.error(T):this.startOB.next(h+1)})),be(m,Sr(1),va(ko))};be(this.startOB,xo(0),Fr(d),We(this.stopOB),ke(()=>{e.player.setOutput(),a.next("STARTED")},h=>{a.next("FAILED")},()=>{o.addSuccessEvent({key:ng(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return gi()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},BS={type:"object"},ka=class ka{constructor(t){this.core=t;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return ka.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return ka.Name}getValidateRule(t){return BS}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new Au(this.core,r,t);return be(o.trackDoneOB,Sr(1),ke(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new Au(this.core,t.track,t))}}};l(ka,"Name","TRTCAudioDecoder");var La=ka;var ag=0,Ua=new Set,Tt=null;Ll(ig);Rs.checkStorage();Vm();var $S={RtcError:oe,ErrorCode:ae,ErrorCodeDictionary:yr},le=class le extends cg.EventEmitter{constructor(e,r){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",U.createLogger({id:`t${++ag}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(J({logger:this._log,frameWorkType:le.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(a=>a.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(gu,r.assetsPath),this._use(Tu,r.assetsPath),this._use(La,r.assetsPath||Oc),this._use(yu),r.enableSEI&&pa&&this._use(Iu),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(K.AUDIO_VOLUME,{result:o.sort((s,a)=>a.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ae.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),eg(this,"trtc")}static create(e){}static _create(e,r){H_();let o=new le(e,r||{});return Ua.add(o),o}get room(){return this._room}_listenEvents(){vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(K.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(K.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(K.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(K.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(K.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=pe(J({},e),{uplinkRTT:Math.min(e.uplinkRTT,On),downlinkRTT:Math.min(e.downlinkRTT,On)});this.emit(K.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{vt(o,o).add("player-state-changed",s=>{let a=pe(J({},s),{userId:e.userId});o.kind===D.VIDEO&&(a.streamType=qi(o.streamType)),this.emit(o.kind===D.AUDIO?K.AUDIO_PLAY_STATE_CHANGED:K.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",s=>{s.getCode()===Y.PLAY_NOT_ALLOWED&&this.emit(K.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{at(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,a=e.videoAvailable,{audioAvailable:d,videoAvailable:h}=r;d||this._remoteAudioConfigMap.delete(o),h||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),a!==h&&(h?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(h?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?K.REMOTE_AUDIO_AVAILABLE:K.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(K.SEI_MESSAGE,pe(J({},e),{streamType:qi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(K.ERROR,new oe({code:ae.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,a,d,h,m,T,I;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,On),upLoss:((h=this._networkQuality)==null?void 0:h.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((T=e.msg_up_stream_info.msg_audio_status)==null?void 0:T.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((I=e.msg_up_stream_info.msg_audio_status)==null?void 0:I.uint32_audio_level)||0)/di},video:e.msg_up_stream_info.msg_video_status.filter(v=>r[v.uint32_video_stream_type]).map(v=>({bitrate:(v.uint32_video_codec_bitrate||0)/1e3,width:v.uint32_video_width,height:v.uint32_video_height,frameRate:v.uint32_video_enc_fps,videoType:r[v.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(v=>({userId:v.msg_user_info.str_identifier,audio:{bitrate:(v.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(v.msg_audio_status.uint32_audio_level||0)/di},video:v.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(K.STATISTICS,o)}).add("custom-message",e=>{this.emit(K.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(K.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},e),{streamType:qi(e.streamType)}))}),vt(this,ht).add("audioInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Tt&&Tt.deviceId===Mn){let r=(yield Vi()).find(o=>o.deviceId===Mn);r&&Tt.groupId!==r.groupId&&(Tt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Vi())[0];if(!r||!Tt||Tt.groupId===r.groupId)return;let o=Tt.deviceId===e.deviceId,s=Tt.deviceId===Mn&&Tt.deviceId===r.deviceId;(o||s)&&(Tt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||Oc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(K_.call(this,{TRTC:le,room:this._room,errorModule:$S,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var h,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Se(e.proxy)&&e.proxy.turnServer&&((m=(h=this._room).setTurnServer)==null||m.call(h,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,nt(e.preferHW)&&(this._room.preferHW=e.preferHW);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,le.frameWorkType),this._checkTrackToPublish(),Kp.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return A(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){at(this),this.removeAllListeners(),this._room.destroy(),Ua.delete(this),Ua.size===0&&Kp.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,a=new fi(this._room.audioManager),d={},h={muted:!0};s&&(L(s.microphoneId)?L(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&$e(s.captureVolume)&&a.setCaptureVolume(s.captureVolume),L(s.profile)||(Se(s.profile)?xc[s.profile]&&a.setProfile(xc[s.profile]):a.setProfile(s.profile)),$e(s.earMonitorVolume)&&(h.muted=!(s.earMonitorVolume>0),h.volume=s.earMonitorVolume),L(s.echoCancellation)||(a.profile.echoCancellation=s.echoCancellation),L(s.noiseSuppression)||(a.profile.noiseSuppression=s.noiseSuppression),L(s.autoGainControl)||(a.profile.autoGainControl=s.autoGainControl)),a.on("5",m=>{this.emit(K.ERROR,new oe({code:ae.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),a.on("2",m=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),a.on("4",m=>{let T;m.error&&(T=oe.convertFrom(m.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},m),{error:T}))}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),L(o)||a.setMute(o),vt(a,a).add("player-state-changed",m=>{this.emit(K.AUDIO_PLAY_STATE_CHANGED,pe(J({},m),{userId:""}))}),this.listeners(K.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(le.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&a.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(le.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._localAudioConfig=pe(J({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:h,track:a})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,a={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):L(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),L(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),L(s.earMonitorVolume)||(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!L(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),L(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Or(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),at(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:a}=e,d=new Ir(this._room.videoManager),h={},m={};a&&(a.cameraId?h.deviceId=a.cameraId:L(a.useFrontCamera)?L(a.videoTrack)||(h.customSource=a.videoTrack):h.facingMode=a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,a.qosPreference&&(h.contentHint=Oa(a.qosPreference)),L(a.profile)||(Se(a.profile)?wr[a.profile]&&d.setProfile(wr[a.profile]):d.setProfile(a.profile)),L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror),L(a.small)||(ua()?Se(a.small)?d.small=wr[a.small]:a.small===!0?d.small=wr["120p"]:d.small=a.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",T=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},T),{streamType:qi(T.streamType)}))}),d.on("5",T=>{this.emit(K.ERROR,new oe({code:ae.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let I;T.error&&(I=oe.convertFrom(T.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},T),{error:I}))}),this._listenOutputTrackChanged(d),yield d.capture(h),L(s)||(yield d.setMute(s)),vt(d,d).add("player-state-changed",T=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,pe(J({},T),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=pe(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:a}=e,d={};if(a)if(L(a.profile)||(Se(a.profile)?wr[a.profile]&&this._localVideoTrack.setProfile(wr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&L(a.useFrontCamera)&&this._localVideoTrack.applyProfile()),a.cameraId?yield this._localVideoTrack.switchDevice(a.cameraId):L(a.useFrontCamera)?L(a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a.videoTrack)):yield this._localVideoTrack.switchDevice(a.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),L(a.fillMode)||(d.objectFit=a.fillMode),L(a.mirror)||(d.mirror=a.mirror),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Oa(a.qosPreference)),a.small){let h=!this._localVideoTrack.small;ua()?(a.small===!0?this._localVideoTrack.small=wr["120p"]:Se(a.small)?this._localVideoTrack.small=wr[a.small]:this._localVideoTrack.small=a.small,this._room.videoManager.update(),h&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else a.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!L(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),L(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Or(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),at(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,a=new Bi(this._room.videoManager);a.on("4",I=>{let v;I.error&&(v=oe.convertFrom(I.error)),this.emit(K.PUBLISH_STATE_CHANGED,pe(J({},I),{error:v}))}),a.once("first-video-frame",I=>{this.emit(K.FIRST_VIDEO_FRAME,pe(J({},I),{streamType:qi(I.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,h={},m={};s&&(L(s.profile)||(Se(s.profile)?kc[s.profile]&&a.setProfile(kc[s.profile]):a.setProfile(s.profile)),s.systemAudio&&(h.systemAudio=!0,h.echoCancellation=s.echoCancellation,h.noiseSuppression=s.noiseSuppression,h.autoGainControl=s.autoGainControl),L(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(h.videoTrack=s.videoTrack),s.audioTrack&&(h.audioTrack=s.audioTrack),s.captureElement&&(h.captureElement=s.captureElement),s.preferDisplaySurface&&(h.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(h.contentHint=Oa(s.qosPreference)));let T=yield a.capture(h);if(a.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(K.SCREEN_SHARE_STOPPED)}),T.getAudioTracks()[0]&&(d=new wo(this._room.audioManager),yield d.setInputMediaStreamTrack(T.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),vt(a,a).add("player-state-changed",I=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,pe(J({},I),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let I=[a];d&&I.push(d),this._room.publish(...I).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=pe(J({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:a})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,a={};if(s&&(L(s.fillMode)||(a.objectFit=s.fillMode),s.qosPreference)){let d=Oa(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!L(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Or(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let h=this._room.remotePublishedUserMap.get(o);if(!h)return;let m={},T=s==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack;this._listenOutputTrackChanged(T),a&&(L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror),m.canvasRender=a.canvasRender,s==="main"&&!L(a.small)&&(h.remoteVideoTrack.setMediaType(a.small?8:4),this._room.changeType(a.small,T.user))),yield this._room.subscribe(T),yield this._enableVideoDecodeFallback(T,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:T}),this._emitTrackEvent(T),this._remoteVideoConfigMap.set(d,{config:e}),a&&!L(a.receiveWhenViewVisible)&&this._observeView({remoteTrack:T,view:r,receiveWhenViewVisible:a.receiveWhenViewVisible,viewRoot:a==null?void 0:a.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var z,Te;let{view:r,userId:o,streamType:s,option:a}=e,d=`${o}_${s}`,h=this._remoteVideoConfigMap.get(d);if(!h||!this._room.remotePublishedUserMap.has(o))return;let m={};a&&(L(a.fillMode)||(m.objectFit=a.fillMode),L(a.mirror)||(m.mirror=a.mirror));let T=null,I=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(I!=null&&I.muteState.hasVideo)&&(T=I.remoteVideoTrack),s==="sub"&&(I!=null&&I.muteState.hasAuxiliary)&&(T=I.remoteAuxiliaryTrack),!T)return;let{config:v}=h;s==="main"&&a&&!L(a.small)&&this._room.changeType(a.small,T.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:T,prevConfig:v}),Or(v,e);let N=L(a==null?void 0:a.receiveWhenViewVisible)?(z=v.option)==null?void 0:z.receiveWhenViewVisible:a.receiveWhenViewVisible,j=L(r)?v.view:r,H=L(a==null?void 0:a.viewRoot)?(Te=v.option)==null?void 0:Te.viewRoot:a.viewRoot;this._observeView({remoteTrack:T,view:j,receiveWhenViewVisible:N,viewRoot:H})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return A(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(h.stop(),d.hasVideo&&o.push(h)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));let a=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);a&&a.observer&&a.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return A(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return A(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return A(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===le.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(le.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(le.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{Q_.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,a;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===le.EVENT.AUDIO_FRAME&&((a=this._getPCMAbortCtrl)==null||a.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",a=!1;if(Se(e)?r=e:(r=e.userId,a=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?a&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,a=null;if(r==="")o==="main"&&this._localVideoTrack&&(a=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(a=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(a=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return a?s&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Vi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Tt=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),h=$e(d)?d:100;s.volume=h,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(a),be(De(a,"decode-failed"),We(De(a,re.INIT)),ke(()=>{this.startPlugin(La.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:a})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(a)})}_stopRemoteAudio(e,r=!0){return A(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;!o||!this._plugins.has("TRTCVideoDecoder")||(this._log.debug("remote video will fall back when decode failed"),be(De(e,"decode-failed"),We(De(e,re.INIT)),Ca(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Vo(De(e,"decode-downgrade-state-changed")),ke(s=>{this.emit(K.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,pe(J({},s),{streamType:r,userId:e.userId}))},s=>{this._log.error("fallback",s)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(a){return A(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),L(e)&&s&&s.view&&!Wc(r)){let d=ls(s.view);d.length>0&&(yield o.play(d,r))}if(!L(e)){let d=ls(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return A(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(a){}L(e.muted)||r.setPlayerMute(e.muted),L(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(K.TRACK,{userId:o,streamType:qi(e.streamType),track:e.outMediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(L(r))return;let a=this._remoteVideoConfigMap.get(`${e.userId}_${qi(e.streamType)}`);if(!a)return;let d=a.observer||void 0;if(r===null||it(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=a.visibleViewMap||new Map,T=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(v=>{v.forEach(N=>{m.set(N.target,N.isIntersecting)}),clearTimeout(T),T=window.setTimeout(()=>{[...m.values()].find(j=>j)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let I=new Set(ls(r));m.forEach((v,N)=>{I.has(N)||(d.unobserve(N),m.delete(N))}),I.forEach(v=>{m.set(v,!0),d.observe(v)}),d.takeRecords().forEach(v=>{m.set(v.target,v.isIntersecting)}),a.visibleViewMap=m,a.observer=d}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),tg(this),this._room.remotePublishedUserMap.forEach(e=>{at(e.remoteAudioTrack),at(e.remoteVideoTrack),at(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),at(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Tt||xs(Tt))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(Tt&&!xs(Tt))this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:Tt});else{let e=yield Vi();e[0]&&!xs(e[0])?(Tt=e[0],this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,a=[s];this._room.autoReceiveAudio&&a.push(o.remoteAudioTrack),this._room.subscribe(...a).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:pe(J({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){U.setLogLevel(e),L(r)||(r?U.enableUploadLog():U.disableUploadLog())}static isSupported(){return Rd()}static getCameraList(e=!0){return er(e)}static getMicrophoneList(e=!0){return Gt(e)}static getSpeakerList(e=!0){return Vi(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(pt&&(e===nr.SPEAKER||e===nr.HEADSET)){let o=yield le.getMicrophoneList(),s="";if(o.forEach(a=>{a.label===e&&(s=a.deviceId)}),!s)return;Ua.forEach(a=>A(this,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Vi()).forEach(o=>{o.deviceId===e&&(Ua.forEach(s=>{s._setCurrentSpeaker(e),s.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Tt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:a,version:d}){switch(d&&(yo.version=d),e){case"count":yo.addCount({key:r,useUV:a});break;case"enum":yo.addEnum({key:r,value:o,useUV:a});break;case"number":yo.addNumber({key:r,value:o,split:s});break}}};l(le,"_loggerManager",U),l(le,"EVENT",K),l(le,"ERROR_CODE",ae),l(le,"TYPE",nr),l(le,"frameWorkType",30),G([qe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],le.prototype,"use",1),G([Nt(Et.TRTC.enterRoom),Gi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Ae(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),qe()],le.prototype,"enterRoom",1),G([qe()],le.prototype,"exitRoom",1),G([Nt(Et.TRTC.switchRole),Ho("room",{merge:(e,r)=>r}),qe()],le.prototype,"switchRole",1),G([qe()],le.prototype,"destroy",1),G([Nt(Et.TRTC.startLocalAudio),Gi("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),qe()],le.prototype,"startLocalAudio",1),G([Nt(Et.TRTC.updateLocalAudio),Ho("audio",{debounce:{delay:200,getKey:()=>`${ag}-localAudio`,isNeedToDebounce:e=>{var r;return!L((r=e.option)==null?void 0:r.captureVolume)}}}),qe()],le.prototype,"updateLocalAudio",1),G([ji("audio"),qe()],le.prototype,"stopLocalAudio",1),G([Nt(Et.TRTC.startLocalVideo),Gi("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),qe()],le.prototype,"startLocalVideo",1),G([Nt(Et.TRTC.updateLocalVideo),Ho("video"),qe()],le.prototype,"updateLocalVideo",1),G([ji("video"),qe()],le.prototype,"stopLocalVideo",1),G([Nt(Et.TRTC.startScreenShare),Gi("screen",()=>!0),qe()],le.prototype,"startScreenShare",1),G([Nt(Et.TRTC.updateScreenShare),Ho("screen"),qe()],le.prototype,"updateScreenShare",1),G([qe()],le.prototype,"stopScreenShare",1),G([Nt(Et.TRTC.startRemoteVideo),Gi(e=>`v${e.userId}${e.streamType}`,()=>!0),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"startRemoteVideo",1),G([Nt(Et.TRTC.updateRemoteVideo),Ho(e=>`v${e.userId}${e.streamType}`),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"updateRemoteVideo",1),G([Nt(Et.TRTC.stopRemoteVideo),Ae(e=>function(r){return A(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),qe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],le.prototype,"stopRemoteVideo",1),G([ji(e=>`v${e.userId}${e.streamType}`)],le.prototype,"_stopRemoteVideo",1),G([Nt(...Et.TRTC.muteRemoteAudio),qe({getRemoteId:e=>e})],le.prototype,"muteRemoteAudio",1),G([Xp(...Et.TRTC.setRemoteAudioVolume),rg(200,e=>e),qe({getRemoteId:e=>e})],le.prototype,"setRemoteAudioVolume",1),G([fu("start"),Fi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Gi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Nm[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],le.prototype,"startPlugin",1),G([fu("update"),Ho((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>wm[e.getName()]})],le.prototype,"updatePlugin",1),G([fu("stop"),ji((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),qe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Mm[e.getName()]})],le.prototype,"stopPlugin",1),G([Xp(...Et.TRTC.enableAudioVolumeEvaluation)],le.prototype,"enableAudioVolumeEvaluation",1),G([qe()],le.prototype,"getVideoSnapshot",1),G([qe()],le.prototype,"_setCurrentSpeaker",1),G([Gi(e=>`a${e.userId}`,()=>!0)],le.prototype,"_startRemoteAudio",1),G([Ae(e=>function(r){return A(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(pe(J({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),ji(e=>`a${e.userId}`)],le.prototype,"_stopRemoteAudio",1),G([ji("room")],le.prototype,"_exitRoom",1),G([ji("screen")],le.prototype,"_stopScreenShare",1),G([Nt(...Et.TRTC.sendSEIMessage),Hp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],le.prototype,"sendSEIMessage",1),G([Nt(Et.TRTC.sendCustomMessage),Hp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],le.prototype,"sendCustomMessage",1),G([Nt(Et.TRTC.create)],le,"_create",1);var sh=le,Js=sh;var bu=class{constructor(t,e){l(this,"_flag");l(this,"terminalType");l(this,"userId");l(this,"tinyId");l(this,"role");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Mo(t,this),this.remoteVideoTrack=new Hi(t,this),this.remoteAuxiliaryTrack=new ou(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Vn(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var nh=class{constructor(){l(this,"_set",new Set);F.on(P.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function HS(){return A(this,null,function*(){let i,t;try{let I=yield Gt();i=I&&I.length}catch(I){}try{let I=yield er();t=I&&I.length}catch(I){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:a}=this.checkSystemResult.detail,d=Li.basis(),h={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:a},m={browser:d.browser,os:d.os,trtc:h,devices:e},T={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Ve.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),Ve.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId})})}function dg(){return Ae(i=>{let t=new nh;return function(e,r,o){return A(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ue({code:Y.INVALID_OPERATION,message:st({key:ot.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),F.emit(P.JOIN_START,{room:this,roomId:s,params:e});let a=Pr.getEnv();a||(a=ei.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Lc.OLD_CLOUD_LADDER)?a=ei.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Lc.WEBRTC)&&(a=ei.WEBRTC))),Ve.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Li.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,HS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Pr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Pr.performanceNow(),F.emit(P.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Ve.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),F.emit(P.JOIN_FAILED,{room:this,error:d}),d}})}})}var ug=()=>Ae(i=>function(...t){return A(this,null,function*(){F.emit(P.LEAVE_START,{room:this}),yield i.call(this),F.emit(P.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function lg(){return Ae(i=>function(...t){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;F.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function mg(){return Ae(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function pg(){return Ae(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function WS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Ni(r)?r.catch(o=>U.error(`${i.name}() error observed ${o}`)):r}catch(r){U.error(`${i.name}() error observed ${r}`)}}}var Ru=class{constructor(t){l(this,"_frameWorkType");l(this,"_component");l(this,"_language");l(this,"connectionType");l(this,"_room");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_keyPrefix");l(this,"_log");l(this,"_intervalId");l(this,"_firstPublishedUserList");l(this,"_networkQuality");l(this,"_basicInfo");l(this,"_pathJoinRoom");l(this,"_pathLeaveRoom");l(this,"_pathMainVideoMap");l(this,"_pathMainAudioMap");l(this,"_pathAuxiliaryMap");l(this,"_remoteStreamStatMap");l(this,"_localStreamStat");l(this,"_eventMap",new Map);l(this,"_captureCostSum",0);l(this,"_captureCostCount",0);l(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=U.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Fe(this[e])&&(this[e]=WS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ke,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Kn().then(t=>{this._basicInfo.string_os_version=_o(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),F.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(P.JOIN_START,this.handleJoinStart).addEvent(P.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(P.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(P.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(P.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(P.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(P.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(P.JOIN_FAILED,this.handleJoinFailed).addEvent(P.LEAVE_START,this.handleLeaveStart).addEvent(P.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(P.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(P.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(P.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(P.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(P.PUBLISH_START,this.handlePublishStart).addEvent(P.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(P.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(P.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(P.PLAY_TRACK_START,this.handlePlayStart).addEvent(P.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(P.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(P.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(P.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(P.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(P.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((t,e)=>F.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),ft.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(L(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),L(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),L(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:a,tls:d,request:h,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=h,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof ue?Number(e.getExtraCode()||e.getCode()):Y.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:pe(J({},GS),{msg_user_info:new Va({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:a,role:d}=e,h=new Va({userId:s,tinyId:a,role:d==="anchor"?20:21}),m=Date.now(),T=`${s}_${r}`,I=this._remoteStreamStatMap.get(T);I&&I.subscribeStartTime===0&&(I.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(T)&&this._pathMainVideoMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(T)&&this._pathMainAudioMap.set(T,{statsToReport:{msg_user_info:h,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(T)&&this._pathAuxiliaryMap.set(T,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(o&&(o.statsToReport.uint64_render_first_frame_time===0&&(o.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:d,playStreamTime:h,subscribedTime:m}=s;d.uint32_video_render_first===0&&h-m<=100&&(d.uint32_video_render_first=r-o.sendSubscribeCMDTime)}let a=this._pathAuxiliaryMap.get(e);if(a&&s){let{statsToReport:d,playStreamTime:h,subscribedTime:m}=s;d.uint32_video_render_first===0&&h-m<=100&&(d.uint32_video_render_first=r-a.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:a})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),a&&(d.totalAudioDelay=(d.totalAudioDelay||0)+a,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let h,m,T,I;s&&(m=s,T=1),a&&(h=a,I=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:h,totalVideoDelay:m,audioDelayCount:I,videoDelayCount:T})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:h}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=h,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/di*100)>0&&(this._localStreamStat.totalAudioLevel+=s/di,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:h}=s,m=a.str_identifier,T=this._room.remotePublishedUserMap.get(m);if(h.forEach(I=>{let v=I.uint32_video_stream_type===2,N=I.uint32_video_stream_type===7,j=`${m}_${v?"main":"auxiliary"}`,H=this._remoteStreamStatMap.get(j);if(H&&(v&&(T!=null&&T.remoteVideoTrack.isSubscribed)||N&&(T!=null&&T.remoteAuxiliaryTrack))){H.totalVideoFPS+=I.uint32_video_receive_fps,H.totalVideoBitrate+=I.uint32_video_codec_bitrate,H.videoCount++,H.statsToReport.uint32_video_width===0&&(H.statsToReport.uint32_video_width=I.uint32_video_width),H.statsToReport.uint32_video_height===0&&(H.statsToReport.uint32_video_height=I.uint32_video_height);let z=v?T.remoteVideoTrack:T.remoteAuxiliaryTrack;z.stat.jitterBufferDelay&&(H.videoJitterBufferDelay=z.stat.jitterBufferDelay),z.stat.framesReceived&&(H.statsToReport.uint32_video_consume_render_rate=Math.floor(z.stat.framesDecoded/z.stat.framesReceived*Rn(10,6)))}}),d){let I=`${m}_main`,v=this._remoteStreamStatMap.get(I);this._remoteStreamStatMap.has(I)&&v&&T!=null&&T.remoteAudioTrack.isSubscribed&&(v.totalAudioBitrate+=d.uint32_audio_codec_bitrate,v.audioCount++,T.remoteAudioTrack.stat.jitterBufferDelay&&(v.audioJitterBufferDelay=T.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/di*100)>0&&(v.totalAudioLevel+=d.uint32_audio_level/di,v.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof ue?e.getExtraCode()||e.getCode():Y.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ss)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ns)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&wn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:T,count:I,audioDelayCount:v,videoDelayCount:N,totalAudioDelay:j,totalVideoDelay:H}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(T/I),v&&j&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(j/v),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&H&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(H/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Go);let{badCaseDetector:a}=this._room,{dataFreeze:d,count:h}=a.getDataFreezeDuration(e),{renderFreeze:m}=a.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=h,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),a.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Go&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Go)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Go&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Go)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Go&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Go)}getReportData(){this._basicInfo.uint32_networkType=$c();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Va({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:us(this._signalInfo.relayIp),uint32_client_ip:us(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Rn(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:us(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Fn(t),t}report(){return A(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return A(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Xl(t),o=r instanceof ArrayBuffer,s=`${ii(e,Di.KEY_POINT)}&gzip=${+o}`,a=!1;navigator.sendBeacon&&(a=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(X),this.uploadKVStat(yo)];a||d.push(oi({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return A(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=pe(J({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield Xl(e),o=`${ii(+this._room.sdkAppId,Di.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||oi({url:o,body:r})})}};G([Ui({settings:{timeout:500,retries:3}})],Ru.prototype,"upload",1);var Go=5e3,GS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Va=class{constructor(t){l(this,"str_identifier");l(this,"str_tinyid");l(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},hg=Ru;var ah=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ge())}stop(){this._endTime===0&&(this._endTime=ge())}getDuration(){return this._endTime===0?ge()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},zs=ah;var ch=class{constructor(t){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(P.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(P.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var a;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>F.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>F.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let a=new zs,d=this._durationMap.get(s);d?this.isRecording(d.audio)||d.audio.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[a],video:[]})}else this.stopDurationItem(s,D.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let a=new zs,d=this._durationMap.get(s);d?this.isRecording(d.video)||d.video.push(a):this._durationMap.set(s,{userId:o,type:e,audio:[],video:[a]})}else this.stopDurationItem(s,D.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDurationItem(s,D.AUDIO),this.stopDurationItem(s,D.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new zs,a=this._durationMap.get(o);a?this.isRecording(a[e])||a[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},fg=ch;var dh=class{constructor(t){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(P.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(P.PLAY_TRACK_START,this.onPlayTrackStart).set(P.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(P.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a=`${r.userId}_${s}`;this.stopDataFreeze({key:a,userId:o,type:s})}}).set(P.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(P.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>F.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>F.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),a=new zs;s?s.durationItemList.push(a):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[a],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:a}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&a.hasVideo&&!a.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&a.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let a=s.getDuration();a>Fc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:a}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return A(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,a=this._renderFreezeMap.get(s);if(e<=2){let d=ge();a&&!a.isFreeze&&(a.freezeTimeline.push({startTime:d,endTime:0}),a.isFreeze=!0),a||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(a&&a.isFreeze){a.isFreeze=!1;let d=a.freezeTimeline.pop();if(d){d.endTime=ge();let h=d.endTime-d.startTime;a.freezeTimeline.push(d),a.renderFreezeTotal+=Math.min(5e3,h)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||!t.isAvailable)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<Fc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=ge(),a=e.freezeTimeline[e.freezeTimeline.length-1],d=s-a.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},_g=dh;var Eg=Ci(ki(),1);var jS=[1,0,0,0,1,1,0,1],vu=class extends Vt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof _t)try{this.setTexBuffer(jS)}catch(r){t.destroy(new ue({code:Y.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let a=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),a}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var uh=class{constructor(t,e){this.node=t;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Cu=class extends Vt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});l(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new uh(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,a)=>a?Object.assign(s,{width:Math.max(s.width,a.right),height:Math.max(s.height,a.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof _t&&this.inputs.forEach(s=>{if(s){let a=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,a):s.positionBuffer=this.createBuffer(a)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,a)=>(!a||!a.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let a=this.inputs[s];a&&(a.node.useTexture(),this.draw(a.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:a,name:d}=this,h=Date.now(),m=(e-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:a,timestamp:h,fps:m,name:d},J({parent:this.inputs.filter(T=>T).map(T=>T.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof _t))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var qS=`#version 300 es
|
|
99
99
|
in vec2 a_position;
|
|
100
100
|
in vec2 a_texCoord;
|
|
101
101
|
out vec2 v_texCoord;
|
|
@@ -136,4 +136,4 @@ void main() {
|
|
|
136
136
|
void main() {
|
|
137
137
|
gl_Position = vertexPos;
|
|
138
138
|
textureCoord = texturePos;
|
|
139
|
-
}`});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 lh=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],gg=(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")},wu=class{constructor(t){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,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"downgradeLevel",0);l(this,"config");l(this,"videoElement");l(this,"type","wasm");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");let{track:e,createDecoder:r}=t;if(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=De(e,re.INIT),this.stopOB=gt(this.trackDoneOB),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),this.startOB=gt();let o=gt(),s;be(o,Up((d,h)=>(d!==h&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:s,prevState:d,state:h}),h),"INITIALIZED"),We(this.stopOB),ke());let a=d=>{let h=this.pipe(e);return o.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),be(h,We(this.stopOB),ke(()=>{e.stat.framesDecoded++},m=>{if(e.log.error(m),X.addFailedEvent({key:gg(this.type,this.renderer),error:m}),d>4)this.startOB.error(m);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(d+1)}})),be(h,Sr(1),va(ko))};be(this.startOB,xo(0),Fr(a),We(this.stopOB),ke(()=>{e.player.handlePlaying("canvas"),o.next("STARTED")},d=>{s=d,o.next("FAILED")},()=>{X.addSuccessEvent({key:gg(this.type,this.renderer)}),X.addSuccessEvent({key:514704})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!km()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t){var s;if(this.inputFrameCount++,((s=this.decoder)==null?void 0:s.state)!=="configured")return t;let e=new Uint8Array(t.data)[4]&31,r=!1;switch(e){case 5:case 7:r=!0;break}let{timestamp:o}=t;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(r)this.waitFirstKeyFrame=!1,this.startTimestamp=o,this.startTime=Date.now();else return;let a=(o-this.startTimestamp)/90,h=Date.now()-this.startTime-a,m=h<500?0:h/1e3>>0;switch(r&&(m>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),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.decoder.decode(t);return}return t}pipe(t){return gi()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var s,a;(s=this.decoder)==null||s.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:r,type:o}=this;try{switch(o){case"wasm":this.decoder=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let s=0;s<=lh.length;s++){let{supported:a}=yield VideoDecoder.isConfigSupported(this.config);if(a)break;if(s===lh.length){e.error(3);return}lh[s](this.config)}this.decoder=this.createDecoder(o);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",s=>{this.decodedFrameCount++,e.next(s)}),this.decoder.on("error",s=>{t.log.error(s),e.error(o==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),o==="wasm"&&r==="webgl"){this.videoContext=new _t({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(_t.UNAVAILABLE,a=>{t.log.error(a),e.error(7)});let s=new Nu(this.videoContext);this.decoder.on("videoCodecInfo",a=>s.resize(a.width,a.height)),this.decoder.on("videoFrame",a=>{[s.Y,s.U,s.V]=a,this.downgradeLevel===1?this.decodedFrameCount%2===0&&s.render(this.decodedFrameCount):s.render(this.decodedFrameCount)}),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}else if(r==="videoFrame"){t.player.setCanvas();let s=new MediaStreamTrackGenerator({kind:"video"}),a=s.writable.getWriter();t.setInputMediaStreamTrack(s);let d=0;this.decoder.on("videoFrame",h=>{d++,d<=10&&t.log.info(`Frame ${d} decoded width: ${h.displayWidth} height: ${h.displayHeight}`),a.write(h)}),s.onmute=()=>{e.error(o==="webCodecs"?5:9)},e.defer(()=>s.onmute=null)}else{this.videoContext=new Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let s=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",d=>{s.image=d,s.update()});let a=new Fo(this.videoContext,{name:"remotePlayer",logger:t.log});s.connect(a),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}}catch(s){t.log.error(s),e.error(o==="webCodecs"?2:6)}}))}};var Fa=class extends Eg.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,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",U.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ct({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}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())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ct({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new _t({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("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)}}enablePrintDetail(e=2e3){this._checkId=ft.run(uo,()=>{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(),ft.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Oi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new _t({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}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,settings:a,player:d}=o;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new iu(this.smallVideoContext,s,this.log)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=a.width,this.smallTrackSource.height=a.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Oi&&d.setCanvas(e);let h=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${h?h.label:"no output track"}`),o.setOutputMediaStreamTrack(h)}catch(o){this.log.error("set main output failed",o)}}update(){return A(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),Yt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ei?(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 Ei?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(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new ru(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Du(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let a=this.cameraNode;a.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new vu(this.videoContext,this.log)),a=a.connect(this.mirrorNode),a.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Cu(this.videoContext,this.log),a.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),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),a=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),a.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,a;if(e instanceof Bi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Ir)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Hi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof Bi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Ir?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Hi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return A(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return A(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 ue({code:Y.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,d)=>a.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:a,x:d,y:h,width:m,height:T})=>{s.drawImage(a,d,h,m,T)}),ms(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 A(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return A(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return A(this,null,function*(){var I,v;let r;try{r=yield ms((e==null?void 0:e.imageElement)||e.imageUrl)}catch(N){throw new ue({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:a=r.width,height:d=r.height,type:h="watermark",zIndex:m=2}=e;this.watermarkImageList.some(N=>N.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(N=>N.type!==h),this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:m,type:h,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((I=this.cameraTrack)==null?void 0:I.settings.width,(v=this.cameraTrack)==null?void 0:v.settings.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:a,height:d,image:r,zIndex:m,type:h,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(N,j)=>N==="imageUrl"?void 0:j))})}deleteWatermark(e="watermark"){return A(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 A(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return A(this,null,function*(){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 ms(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}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 ue({code:Y.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._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return A(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 wu(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,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}};G([__(function(e){this.log.error("update failed",e)})],Fa.prototype,"update",1);var zS=0;var Mu=class extends re{constructor(e){super("room");l(this,"seq",++zS);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,"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}});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,"_isUsingCachedSchedule",!1);l(this,"_log",U.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,nt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),nt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),nt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new hg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new fg({room:this}),this.badCaseDetector=new _g({room:this}),this.audioManager=new $d(this),this.videoManager=new Fa(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 A(this,null,function*(){return this.publish(e)})}removeTrack(e){return A(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return A(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Se(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:a,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(lu([d,d]),no(`https://${d}`)):(s&&no(s),a&&lu(a))}F.once(P.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ar.main,sched_back_domain:Ar.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return A(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return A(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 A(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 ue({code:Y.INVALID_OPERATION,message:st({key:ot.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Wt.INVALID_DESTROY),new ue({code:Y.INVALID_OPERATION,message:st({key:ot.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,F.emit(P.ROOM_DESTROY,{room:this})}schedule(e,r){return A(this,null,function*(){var s,a,d;let o=ge();try{let{isCached:h,result:m,detailCost:T}=yield Jp({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ke,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=h,this._log.info(`schedule cache:${+h} ${ir(m,{keysToExclude:["username","credential"]})}`),h&&F.once(P.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),m),$e((s=m.config)==null?void 0:s.retryCount)&&$l(m.config.retryCount),Se((a=m.config)==null?void 0:a.loggerDomain)&&no(m.config.loggerDomain),this.videoDecodeFallbackType=((d=m.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,F.emit(P.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:T}),X.addSuccessEvent({key:521700,cost:ge()-o,split:50})}catch(h){throw X.addFailedEvent({key:521700,error:h}),h}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};function Tg(i,t=!1){let e=Object.defineProperties(gt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Oe,i.onmessageerror=Oe,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 mh=class extends ne{constructor(t,e){super(t);let r=new ne(t);r.next=Oe,e(r)}},M1=ce(mh,"takeUntilComplete");var St={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},hh="__INLINE__WORKER__",Ig="__INLINE__WASM__",{debug:Sg}=console;St.debug||(console.debug=()=>{});var ph=!hh.startsWith("__"),XS=!Ig.startsWith("__");function yg(){return`${St.assetsPath?`${St.assetsPath}/`:""}worker.js`}function Ag(){let i=yg();return ph||i.startsWith("http")?URL.createObjectURL(new Blob([ph?atob(hh):`importScripts('${i}')`])):i}function bg(){let i=yg();return ph?URL.createObjectURL(new Blob([atob(hh)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Ba;function Ou(){return A(this,null,function*(){let i=St.assetsPath?`${St.assetsPath}/`:"";return Ba||(XS?Ba=new TextEncoder().encode(atob(Ig)).buffer:Ba=yield fetch(`${i}av_processing.wasm`).then(t=>t.arrayBuffer()),Ba)})}var fh=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 A(this,null,function*(){let t=lt("player"),e=bg();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),U.info("global audio player worklet addModule success",e)}catch(r){throw U.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Ou(),flag:St},numberOfInputs:2}),U.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return A(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},Pu=new fh;var _h=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),F1=_h?Promise.resolve().then(function(){return KS}):Promise.resolve().then(function(){return sy});var B1=_h?Promise.resolve().then(function(){return ty}):Promise.resolve().then(function(){return ay});var QS=_h?Promise.resolve().then(function(){return iy}):Promise.resolve().then(function(){return dy});function gh(...i){return A(this,null,function*(){return(yield QS).default(...i)})}var YS=i=>A(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),ZS=(...t)=>A(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,a)=>{e[a]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(d=>{e[a].accept[d]=s.extensions||[]}):e[a].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(YS));return i[0].multiple?o:o[0]}),KS={__proto__:null,default:ZS};function xu(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 xu=function(e){this.s=e,this.n=e.next},xu.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 xu(i)}var Rg=(o,s,...a)=>A(void 0,[o,s,...a],function*(i,t,e=i.name,r){let d=[],h=[];var m,T=!1,I=!1;try{for(var v,N=function(j){var H,z,Te,Pe=2;for(typeof Symbol!="undefined"&&(z=Symbol.asyncIterator,Te=Symbol.iterator);Pe--;){if(z&&(H=j[z])!=null)return H.call(j);if(Te&&(H=j[Te])!=null)return new xu(H.call(j));z="@@asyncIterator",Te="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());T=!(v=yield N.next()).done;T=!1){let j=v.value,H=`${e}/${j.name}`;j.kind==="file"?h.push(j.getFile().then(z=>(z.directoryHandle=i,z.handle=j,Object.defineProperty(z,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>H})))):j.kind!=="directory"||!t||r&&r(j)||d.push(Rg(j,t,H,r))}}catch(j){I=!0,m=j}finally{try{T&&N.return!=null&&(yield N.return())}finally{if(I)throw m}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(h)]}),ey=(...t)=>A(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 Rg(e,i.recursive,void 0,i.skipDirectory)}),ty={__proto__:null,default:ey},ry=(s,...a)=>A(void 0,[s,...a],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let d=[],h=null;if(i instanceof Blob&&i.type?h=i.type:i.headers&&i.headers.get("content-type")&&(h=i.headers.get("content-type")),t.forEach((I,v)=>{d[v]={description:I.description||"Files",accept:{}},I.mimeTypes?(v===0&&h&&I.mimeTypes.push(h),I.mimeTypes.map(N=>{d[v].accept[N]=I.extensions||[]})):h?d[v].accept[h]=I.extensions||[]:d[v].accept["*/*"]=I.extensions||[]}),e)try{yield e.getFile()}catch(I){if(e=null,r)throw I}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let T=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(T),m):"body"in i?(yield i.body.pipeTo(T),m):(yield T.write(yield i),yield T.close(),m)}),iy={__proto__:null,default:ry},oy=(...t)=>A(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 a=m=>{typeof d=="function"&&d(),e(m)},d=i[0].legacySetup&&i[0].legacySetup(a,()=>d(r),o),h=()=>{window.removeEventListener("focus",h),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",h)}),o.addEventListener("change",()=>{window.removeEventListener("focus",h),o.remove(),a(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),sy={__proto__:null,default:oy},ny=(...t)=>A(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=d=>{typeof a=="function"&&a(),e(d)},a=i[0].legacySetup&&i[0].legacySetup(s,()=>a(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(h=>h.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):d=d.filter(h=>h.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),ay={__proto__:null,default:ny},cy=(e,...r)=>A(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(h,m){return A(this,null,function*(){let T=h.getReader(),I=new ReadableStream({start:j=>function H(){return A(this,null,function*(){return T.read().then(({done:z,value:Te})=>{if(!z)return j.enqueue(Te),H();j.close()})})}()}),v=new Response(I),N=yield v.blob();return T.releaseLock(),new Blob([N],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let a=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(a,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),a()}),o.click(),null}),dy={__proto__:null,default:cy};var Eh=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){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(Ag(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>A(this,null,function*(){e.onmessage=({data:{id:s,type:a,payload:d}})=>{var h;if(s)(h=this.transactions.get(s))==null||h(d),this.transactions.delete(s);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let m=typeof d.old=="string"?d.old:`${d.old.action}ing`,T=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(Gc(),d.group,d.name,m,"\u{1F449}",T)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},e.postMessage({wasm:yield Ou(),flag:St},this.ports)}))}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Th=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()}},Ih=class i extends Eh{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 A(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Lt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ji=new Ih,jo,uy=-1;function vg(i){return console.log(i),jo.push(i.slice()),jo.length>1e3&&jo.shift(),i}function Cg(i){return A(this,null,function*(){switch(uy){case 0:this.edpl.willDecodeAudio=vg;break;case 2:this.edpl.didEncodeAudio=vg;break}yield Ji.create(),F.emit(P.JOIN_SEND_CMD,{room:this});let t=new Th(Ji,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:a,payload:d}=s;this.onWorkerEvent(a,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(F.emit(P.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ue({code:Y.JOIN_ROOM_FAILED,extraCode:Number(e),message:st({key:ot.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Sh},useWt:{set:ly},enableDebug:{set(i){console.debug=i?Sg:()=>{},Ji.setSwitchValue("enableDebug",i)}},useV2:{set:yh},dump:{value(){if(jo||(console.warn("dump audio will be activated at next time join room"),jo=[]),!jo.length){console.warn("no audio data to dump,try it later");return}let i=[];return jo.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),gh(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;Ji.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:a})=>{console.log(a),e.push(a),e.length>t&&(s.port2.onmessage=null,Ji.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return gh(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:St.useHardDecoder="prefer-hardware";break;case!1:St.useHardDecoder="prefer-software";break;default:St.useHardDecoder="no-preference"}}}});function Sh(i){return A(this,null,function*(){Ji.setSwitchValue("useAINS",i)})}function yh(i){return A(this,null,function*(){Ji.setSwitchValue("useV2",i)})}function ly(i){return A(this,null,function*(){Ji.setSwitchValue("useWt",i)})}function Dg(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function Ng(i){return A(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),be(Tg(r.port2),We(De(i,re.INIT)),ke(s=>{let{data:a,packetsReceived:d}=s;i.stat.packetsReceived=d,i.stat.framesReceived++,e++;let h=a[4]&31;if(e<=10){let T=Array.from(a.slice(0,10)).map(I=>I.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${a.length} bytes, Type: ${h}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${T}`)}let m;switch(h){case 5:case 7:m="key";break;default:m="delta";break}i.decodeFrame({data:a.buffer,type:m,timestamp:(Date.now()-t)*1e3})},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var ku=[];function Mg(i){var h;let t=gt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=ku.length;m++)if(!ku[m]){ku[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;(h=this.session)==null||h.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(pe(J({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,a,d=m=>{let T=s.getAudioTracks()[0];T&&(a.disconnect(),s.removeTrack(T)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),a=lt("player").createMediaStreamSource(s),a.connect(Pu.worklet,0,this.index)};be(De(i,"output-media-track-changed"),We(De(i,"capture")),ke(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,a.disconnect(),ku[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,Ca(m=>i.volume=m),Vo(tu(1e3)),ke(()=>{i.volume=0})),d(i.outMediaTrack)}var IF=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Ah=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,"encoder");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(a,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(a),s++,d.enqueue(a))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:a=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),a.timestamp,a.displayWidth,a.displayHeight),(a.displayWidth!==this.config.width||a.displayHeight!==this.config.height)&&(console.log("resize video track frame:",a.displayWidth,a.displayHeight,this.config.width,this.config.height),this.configure({width:a.displayWidth,height:a.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(a),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,a.close())}}),e).catch(a=>{console.warn(a),o.close()})}recreate(t,e=0){let r=0,o=new VideoEncoder({output:s=>{let a=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e===0&&F.emit(P.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let h=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(h.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:a},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:a}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function Lu(i,t){return A(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:St.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 a=new Ah(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)a.insertKeyFrame=!0;else if(!e){let{bitrate:h}=d.data;Ln({configureBr:[d.data.bitrate,h]}),a.configure({bitrate:h})}},this._log.info("start push",r,t),a})}function Og(i){return A(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:a}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=a;let d=yield Lu.call(this,i,r);this._log.info("VideoEncoder created",r);let h,m=T=>A(this,null,function*(){if(h==null||h.abort("track changed"),!T)return;h=new AbortController;let{width:I,height:v,displaySurface:N}=T.getSettings();I&&(d.config.width=I),v&&(d.config.height=v);let j=Qt.match(/Chrome\/(\d+)/);(j==null?void 0:j[1])==="114"&&N==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",T.readyState,T.getSettings());let H=new MediaStreamTrackProcessor({track:T}).readable,z="small"in i&&i.small;z?(this.smallEncoder||(this.smallEncoder=yield Lu.call(this,i,{profile:z,type:3,trackType:o})),this.smallEncoder.track=T,this.smallEncoder.label="small",H=this.smallEncoder.trans(H,h,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=T,d.label=e,d.start(H,h,this)});return be(De(i,"output-media-track-changed"),We(De(i,"capture")),ke(m,console.error,()=>{var T;this._log.info("stop push",e,r),h.abort("unpublish"),d.close(),(T=this.smallEncoder)==null||T.close()})),m(i.outMediaTrack)})}var zi=class zi extends re{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(zi.INTERVALCHANGED,this.interval)}),be(De(this,zi.INTERVALCHANGED),Fr(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(L_(s),Vs(()=>[]))),ke(s=>{s.forEach(a=>{this.room.remotePublishedUserMap.has(a.userId)&&(this.room.remotePublishedUserMap.get(a.userId).remoteAudioTrack.volume=a.volume)}),(!document.hidden||this.enableInBackground)&&this.state==re.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(zi.INTERVALCHANGED,this.interval)}stop(){}};l(zi,"INTERVALCHANGED","intervalChanged"),G([ye([re.INIT,re.OFF],re.ON)],zi.prototype,"start",1),G([ye([],re.OFF)],zi.prototype,"stop",1);var Uu=zi;var Xi=class Xi extends Mu{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 Uu(this));l(this,"enableAIVoice",Sh);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:um(),uint32_device_type:0,str_os_verion:lm(),uint32_link_type:1,str_client_version:Ke,uint32_net_type:ao[Pr.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,yh(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return A(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 a=new MessageChannel;this.postMessage({cmd:e,payload:r},[a.port1]),a.port2.onmessageerror=s,a.port2.onmessage=d=>{a.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var a;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(a=this.session)==null||a.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return A(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 A(this,null,function*(){var h,m,T;let s=Pr.getEnv(),a=Ad(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(h=this.proxy_wt)==null?void 0:h.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(T=this.scheduleResult.iceServers)!=null&&T.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:As(),browserInfo:Ad(),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:Ke,browserVersion:a.browserName+a.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 Cg.call(this,d),console.log(this),Pu.playAudio(I=>this.postMessage({cmd:"setAudioWorkletPort"},[I])),this.checkDestroy()})}_leave(e=0){return A(this,null,function*(){console.log(this.userId,"leave",e),this.remotePublishedUserMap.forEach(r=>{r.remoteAudioTrack.close(),r.remoteAuxiliaryTrack.close(),r.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((r,o)=>o.unpublish())})}leave(){return A(this,null,function*(){return this._leave()})}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 A(this,null,function*(){let e=We(De(this,"left"));be(r=>A(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,ke(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.buffer}});o.postMessage(new Uint8Array(s.data),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case P.RECEIVED_PUBLISHED_USER_LIST:F.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new bu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let I=r,v=this.remotePublishedUserMap.get(I);v&&(v.remoteVideoTrack.close(),v.remoteAuxiliaryTrack.close(),v.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(I),this.emit("remote-unpublished",v))}return;case"banned":switch(this._leave(r),r){case 8:this.emit("banned",{reason:"kick",message:""});break;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});case 7:case 5:this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:I,muteState:v,flag:N}=r,j=this.remotePublishedUserMap.get(v.userId);if(!j){this.emit("remote-publish-state-changed",r);return}j.flag=N}F.emit(P.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:a,uplinkInfo:d,downlinkInfo:h,msg_down_stream_info:m}=r,T={str_sdk_version:Ke,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:ao[kn()]},msg_event_msg:U_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:m};F.emit(P.HEARTBEAT_REPORT,{room:this,report:T}),this.emit("heartbeat-report",T),F.emit(P.NETWORK_QUALITY,{room:this,uplink:{rtt:a,loss:s},downlinks:h}),delete r.downlinkInfo;break;case"signal-connection-state-changed":F.emit(P.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return A(this,null,function*(){let r=e.reduce((d,h)=>h.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,a=d=>A(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),vt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:Mg.call(this,d);break;default:yield Og.call(this,d)}});yield Promise.all(e.map(a)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return A(this,null,function*(){e.forEach(at)})}subscribe(...e){return A(this,null,function*(){let r=e.reduce((I,v)=>v.mediaType|I,0),{userId:o,tinyId:s,streamType:a}=e[0],d=this.remotePublishedUserMap.get(o),h=J({},d.subscribeState),m=Object.assign(new oa,h);m.mediaType|=r,F.emit(P.SUBSCRIBE_START,{room:this,streamType:a,remotePublishedUser:d,subscribeState:m});let T=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(I=>m.mediaType&I).map(I=>({mediaType:I,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",T),yield Promise.all(e.filter(I=>!I.isSubscribed).map(I=>{switch(I.mediaType){case 1:return Dg.call(this,I);default:return Ng.call(this,I)}})),F.emit(P.SUBSCRIBE_SUCCESS,{room:this,streamType:a,remotePublishedUser:d})})}unsubscribe(...e){return A(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:a}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:a,userId:o}),F.emit(P.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return A(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield Lu.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),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let a={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=a.mediaType,this.postMessage("changetype",a)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};G([Fi(Xi.prototype.afterJoin),ye(["left",re.INIT],"joined"),dg()],Xi.prototype,"join",1),G([ye("joined","left",{ignoreError:!0}),ug()],Xi.prototype,"_leave",1),G([Vd((...e)=>0),lg()],Xi.prototype,"publish",1),G([Vd((...e)=>0),mg()],Xi.prototype,"unpublish",1),G([Vd((...e)=>e[0].userId),pg()],Xi.prototype,"subscribe",1);var Vu=Xi;Js.frameWorkType=37;Js.create=function(i){let t=Js._create.call(this,Vu,i);return t._use(wa,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(St.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",Ke,"created",St),t};Object.assign(Js.prototype,{_setCurrentSpeaker(i){let t=lt("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return A(this,null,function*(){return this.startPlugin(wa.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{be(De(i,"decode-downgrade-state-changed"),Uo(o=>o.state==="STARTED"),Sr(1),Bp(1e4),We(De(i,re.INIT)),ke(e,r))})})}});var WB=Js;export{WB as default};
|
|
139
|
+
}`});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 lh=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],gg=(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")},wu=class{constructor(t){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,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"downgradeLevel",0);l(this,"config");l(this,"videoElement");l(this,"type","wasm");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");let{track:e,createDecoder:r}=t;if(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=De(e,re.INIT),this.stopOB=gt(this.trackDoneOB),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),this.startOB=gt();let o=gt(),s;be(o,Up((d,h)=>(d!==h&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:s,prevState:d,state:h}),h),"INITIALIZED"),We(this.stopOB),ke());let a=d=>{let h=this.pipe(e);return o.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),be(h,We(this.stopOB),ke(()=>{e.stat.framesDecoded++},m=>{if(e.log.error(m),X.addFailedEvent({key:gg(this.type,this.renderer),error:m}),d>4)this.startOB.error(m);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(d+1)}})),be(h,Sr(1),va(ko))};be(this.startOB,xo(0),Fr(a),We(this.stopOB),ke(()=>{e.player.handlePlaying("canvas"),o.next("STARTED")},d=>{s=d,o.next("FAILED")},()=>{X.addSuccessEvent({key:gg(this.type,this.renderer)}),X.addSuccessEvent({key:514704})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!km()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t){var s;if(this.inputFrameCount++,((s=this.decoder)==null?void 0:s.state)!=="configured")return t;let e=new Uint8Array(t.data)[4]&31,r=!1;switch(e){case 5:case 7:r=!0;break}let{timestamp:o}=t;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(r)this.waitFirstKeyFrame=!1,this.startTimestamp=o,this.startTime=Date.now();else return;let a=(o-this.startTimestamp)/90,h=Date.now()-this.startTime-a,m=h<500?0:h/1e3>>0;switch(r&&(m>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),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.inputFrameCount<10&&console.log(`decode ${this.inputFrameCount} ${this.downgradeLevel} ${this.gop_helper} ${this.gop}`),this.decoder.decode(t);return}return t}pipe(t){return gi()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var s,a;(s=this.decoder)==null||s.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:r,type:o}=this;try{switch(o){case"wasm":this.decoder=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let s=0;s<=lh.length;s++){let{supported:a}=yield VideoDecoder.isConfigSupported(this.config);if(a)break;if(s===lh.length){e.error(3);return}lh[s](this.config)}this.decoder=this.createDecoder(o);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",s=>{this.decodedFrameCount++,e.next(s)}),this.decoder.on("error",s=>{t.log.error(s),e.error(o==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),o==="wasm"&&r==="webgl"){this.videoContext=new _t({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(_t.UNAVAILABLE,a=>{t.log.error(a),e.error(7)});let s=new Nu(this.videoContext);this.decoder.on("videoCodecInfo",a=>s.resize(a.width,a.height)),this.decoder.on("videoFrame",a=>{[s.Y,s.U,s.V]=a,this.downgradeLevel===1?this.decodedFrameCount%2===0&&s.render(this.decodedFrameCount):s.render(this.decodedFrameCount)}),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}else if(r==="videoFrame"){t.player.setCanvas();let s=new MediaStreamTrackGenerator({kind:"video"}),a=s.writable.getWriter();t.setInputMediaStreamTrack(s);let d=0;this.decoder.on("videoFrame",h=>{d++,d<=10&&t.log.info(`Frame ${d} decoded width: ${h.displayWidth} height: ${h.displayHeight}`),a.write(h)}),s.onmute=()=>{e.error(o==="webCodecs"?5:9)},e.defer(()=>s.onmute=null)}else{this.videoContext=new Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let s=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",d=>{s.image=d,s.update()});let a=new Fo(this.videoContext,{name:"remotePlayer",logger:t.log});s.connect(a),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}}catch(s){t.log.error(s),e.error(o==="webCodecs"?2:6)}}))}};var Fa=class extends Eg.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,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",U.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ct({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}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())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ct({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new _t({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("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)}}enablePrintDetail(e=2e3){this._checkId=ft.run(uo,()=>{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(),ft.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Oi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new _t({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}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,settings:a,player:d}=o;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new iu(this.smallVideoContext,s,this.log)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=a.width,this.smallTrackSource.height=a.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Oi&&d.setCanvas(e);let h=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${h?h.label:"no output track"}`),o.setOutputMediaStreamTrack(h)}catch(o){this.log.error("set main output failed",o)}}update(){return A(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),Yt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ei?(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 Ei?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(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new ru(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Du(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let a=this.cameraNode;a.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new vu(this.videoContext,this.log)),a=a.connect(this.mirrorNode),a.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Cu(this.videoContext,this.log),a.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),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),a=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),a.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,a;if(e instanceof Bi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Ir)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Hi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof Bi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Ir?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Hi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return A(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return A(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 ue({code:Y.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,d)=>a.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:a,x:d,y:h,width:m,height:T})=>{s.drawImage(a,d,h,m,T)}),ms(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 A(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return A(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return A(this,null,function*(){var I,v;let r;try{r=yield ms((e==null?void 0:e.imageElement)||e.imageUrl)}catch(N){throw new ue({code:Y.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:a=r.width,height:d=r.height,type:h="watermark",zIndex:m=2}=e;this.watermarkImageList.some(N=>N.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(N=>N.type!==h),this.pushWaterMarkImageList({x:o,y:s,width:a,height:d,image:r,zIndex:m,type:h,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((I=this.cameraTrack)==null?void 0:I.settings.width,(v=this.cameraTrack)==null?void 0:v.settings.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:a,height:d,image:r,zIndex:m,type:h,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(N,j)=>N==="imageUrl"?void 0:j))})}deleteWatermark(e="watermark"){return A(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 A(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return A(this,null,function*(){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 ms(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}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 ue({code:Y.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._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return A(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 wu(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,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}};G([__(function(e){this.log.error("update failed",e)})],Fa.prototype,"update",1);var zS=0;var Mu=class extends re{constructor(e){super("room");l(this,"seq",++zS);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,"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}});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,"_isUsingCachedSchedule",!1);l(this,"_log",U.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,nt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),nt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),nt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new hg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new fg({room:this}),this.badCaseDetector=new _g({room:this}),this.audioManager=new $d(this),this.videoManager=new Fa(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 A(this,null,function*(){return this.publish(e)})}removeTrack(e){return A(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return A(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Se(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:a,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(lu([d,d]),no(`https://${d}`)):(s&&no(s),a&&lu(a))}F.once(P.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ar.main,sched_back_domain:Ar.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return A(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return A(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 A(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 ue({code:Y.INVALID_OPERATION,message:st({key:ot.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Wt.INVALID_DESTROY),new ue({code:Y.INVALID_OPERATION,message:st({key:ot.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,F.emit(P.ROOM_DESTROY,{room:this})}schedule(e,r){return A(this,null,function*(){var s,a,d;let o=ge();try{let{isCached:h,result:m,detailCost:T}=yield Jp({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ke,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=h,this._log.info(`schedule cache:${+h} ${ir(m,{keysToExclude:["username","credential"]})}`),h&&F.once(P.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=J(J({},this.scheduleResult),m),$e((s=m.config)==null?void 0:s.retryCount)&&$l(m.config.retryCount),Se((a=m.config)==null?void 0:a.loggerDomain)&&no(m.config.loggerDomain),this.videoDecodeFallbackType=((d=m.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,F.emit(P.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:T}),X.addSuccessEvent({key:521700,cost:ge()-o,split:50})}catch(h){throw X.addFailedEvent({key:521700,error:h}),h}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};function Tg(i,t=!1){let e=Object.defineProperties(gt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Oe,i.onmessageerror=Oe,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 mh=class extends ne{constructor(t,e){super(t);let r=new ne(t);r.next=Oe,e(r)}},M1=ce(mh,"takeUntilComplete");var St={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},hh="__INLINE__WORKER__",Ig="__INLINE__WASM__",{debug:Sg}=console;St.debug||(console.debug=()=>{});var ph=!hh.startsWith("__"),XS=!Ig.startsWith("__");function yg(){return`${St.assetsPath?`${St.assetsPath}/`:""}worker.js`}function Ag(){let i=yg();return ph||i.startsWith("http")?URL.createObjectURL(new Blob([ph?atob(hh):`importScripts('${i}')`])):i}function bg(){let i=yg();return ph?URL.createObjectURL(new Blob([atob(hh)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Ba;function Ou(){return A(this,null,function*(){let i=St.assetsPath?`${St.assetsPath}/`:"";return Ba||(XS?Ba=new TextEncoder().encode(atob(Ig)).buffer:Ba=yield fetch(`${i}av_processing.wasm`).then(t=>t.arrayBuffer()),Ba)})}var fh=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 A(this,null,function*(){let t=lt("player"),e=bg();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),U.info("global audio player worklet addModule success",e)}catch(r){throw U.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Ou(),flag:St},numberOfInputs:2}),U.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return A(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},Pu=new fh;var _h=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),F1=_h?Promise.resolve().then(function(){return KS}):Promise.resolve().then(function(){return sy});var B1=_h?Promise.resolve().then(function(){return ty}):Promise.resolve().then(function(){return ay});var QS=_h?Promise.resolve().then(function(){return iy}):Promise.resolve().then(function(){return dy});function gh(...i){return A(this,null,function*(){return(yield QS).default(...i)})}var YS=i=>A(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),ZS=(...t)=>A(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,a)=>{e[a]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(d=>{e[a].accept[d]=s.extensions||[]}):e[a].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(YS));return i[0].multiple?o:o[0]}),KS={__proto__:null,default:ZS};function xu(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 xu=function(e){this.s=e,this.n=e.next},xu.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 xu(i)}var Rg=(o,s,...a)=>A(void 0,[o,s,...a],function*(i,t,e=i.name,r){let d=[],h=[];var m,T=!1,I=!1;try{for(var v,N=function(j){var H,z,Te,Pe=2;for(typeof Symbol!="undefined"&&(z=Symbol.asyncIterator,Te=Symbol.iterator);Pe--;){if(z&&(H=j[z])!=null)return H.call(j);if(Te&&(H=j[Te])!=null)return new xu(H.call(j));z="@@asyncIterator",Te="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());T=!(v=yield N.next()).done;T=!1){let j=v.value,H=`${e}/${j.name}`;j.kind==="file"?h.push(j.getFile().then(z=>(z.directoryHandle=i,z.handle=j,Object.defineProperty(z,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>H})))):j.kind!=="directory"||!t||r&&r(j)||d.push(Rg(j,t,H,r))}}catch(j){I=!0,m=j}finally{try{T&&N.return!=null&&(yield N.return())}finally{if(I)throw m}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(h)]}),ey=(...t)=>A(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 Rg(e,i.recursive,void 0,i.skipDirectory)}),ty={__proto__:null,default:ey},ry=(s,...a)=>A(void 0,[s,...a],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let d=[],h=null;if(i instanceof Blob&&i.type?h=i.type:i.headers&&i.headers.get("content-type")&&(h=i.headers.get("content-type")),t.forEach((I,v)=>{d[v]={description:I.description||"Files",accept:{}},I.mimeTypes?(v===0&&h&&I.mimeTypes.push(h),I.mimeTypes.map(N=>{d[v].accept[N]=I.extensions||[]})):h?d[v].accept[h]=I.extensions||[]:d[v].accept["*/*"]=I.extensions||[]}),e)try{yield e.getFile()}catch(I){if(e=null,r)throw I}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let T=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(T),m):"body"in i?(yield i.body.pipeTo(T),m):(yield T.write(yield i),yield T.close(),m)}),iy={__proto__:null,default:ry},oy=(...t)=>A(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 a=m=>{typeof d=="function"&&d(),e(m)},d=i[0].legacySetup&&i[0].legacySetup(a,()=>d(r),o),h=()=>{window.removeEventListener("focus",h),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",h)}),o.addEventListener("change",()=>{window.removeEventListener("focus",h),o.remove(),a(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),sy={__proto__:null,default:oy},ny=(...t)=>A(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=d=>{typeof a=="function"&&a(),e(d)},a=i[0].legacySetup&&i[0].legacySetup(s,()=>a(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(h=>h.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):d=d.filter(h=>h.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),ay={__proto__:null,default:ny},cy=(e,...r)=>A(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(h,m){return A(this,null,function*(){let T=h.getReader(),I=new ReadableStream({start:j=>function H(){return A(this,null,function*(){return T.read().then(({done:z,value:Te})=>{if(!z)return j.enqueue(Te),H();j.close()})})}()}),v=new Response(I),N=yield v.blob();return T.releaseLock(),new Blob([N],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let a=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(a,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),a()}),o.click(),null}),dy={__proto__:null,default:cy};var Eh=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){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(Ag(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>A(this,null,function*(){e.onmessage=({data:{id:s,type:a,payload:d}})=>{var h;if(s)(h=this.transactions.get(s))==null||h(d),this.transactions.delete(s);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let m=typeof d.old=="string"?d.old:`${d.old.action}ing`,T=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(Gc(),d.group,d.name,m,"\u{1F449}",T)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},e.postMessage({wasm:yield Ou(),flag:St},this.ports)}))}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Th=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()}},Ih=class i extends Eh{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 A(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Lt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ji=new Ih,jo,uy=-1;function vg(i){return console.log(i),jo.push(i.slice()),jo.length>1e3&&jo.shift(),i}function Cg(i){return A(this,null,function*(){switch(uy){case 0:this.edpl.willDecodeAudio=vg;break;case 2:this.edpl.didEncodeAudio=vg;break}yield Ji.create(),F.emit(P.JOIN_SEND_CMD,{room:this});let t=new Th(Ji,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:a,payload:d}=s;this.onWorkerEvent(a,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(F.emit(P.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ue({code:Y.JOIN_ROOM_FAILED,extraCode:Number(e),message:st({key:ot.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Sh},useWt:{set:ly},enableDebug:{set(i){console.debug=i?Sg:()=>{},Ji.setSwitchValue("enableDebug",i)}},useV2:{set:yh},dump:{value(){if(jo||(console.warn("dump audio will be activated at next time join room"),jo=[]),!jo.length){console.warn("no audio data to dump,try it later");return}let i=[];return jo.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),gh(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;Ji.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:a})=>{console.log(a),e.push(a),e.length>t&&(s.port2.onmessage=null,Ji.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return gh(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:St.useHardDecoder="prefer-hardware";break;case!1:St.useHardDecoder="prefer-software";break;default:St.useHardDecoder="no-preference"}}}});function Sh(i){return A(this,null,function*(){Ji.setSwitchValue("useAINS",i)})}function yh(i){return A(this,null,function*(){Ji.setSwitchValue("useV2",i)})}function ly(i){return A(this,null,function*(){Ji.setSwitchValue("useWt",i)})}function Dg(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function Ng(i){return A(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),be(Tg(r.port2),We(De(i,re.INIT)),ke(s=>{let{data:a,packetsReceived:d}=s;i.stat.packetsReceived=d,i.stat.framesReceived++,e++;let h=a[4]&31;if(e<=10){let T=Array.from(a.slice(0,10)).map(I=>I.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${a.length} bytes, Type: ${h}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${T}`)}let m;switch(h){case 5:case 7:m="key";break;default:m="delta";break}i.decodeFrame({data:a.buffer,type:m,timestamp:(Date.now()-t)*1e3})},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var ku=[];function Mg(i){var h;let t=gt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=ku.length;m++)if(!ku[m]){ku[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;(h=this.session)==null||h.postMessage({cmd:"pushAudio",payload:J({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(pe(J({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,a,d=m=>{let T=s.getAudioTracks()[0];T&&(a.disconnect(),s.removeTrack(T)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),a=lt("player").createMediaStreamSource(s),a.connect(Pu.worklet,0,this.index)};be(De(i,"output-media-track-changed"),We(De(i,"capture")),ke(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,a.disconnect(),ku[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,Ca(m=>i.volume=m),Vo(tu(1e3)),ke(()=>{i.volume=0})),d(i.outMediaTrack)}var IF=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Ah=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,"encoder");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(a,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(a),s++,d.enqueue(a))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:a=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),a.timestamp,a.displayWidth,a.displayHeight),(a.displayWidth!==this.config.width||a.displayHeight!==this.config.height)&&(console.log("resize video track frame:",a.displayWidth,a.displayHeight,this.config.width,this.config.height),this.configure({width:a.displayWidth,height:a.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(a),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,a.close())}}),e).catch(a=>{console.warn(a),o.close()})}recreate(t,e=0){let r=0,o=new VideoEncoder({output:s=>{let a=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e===0&&F.emit(P.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let h=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(h.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:a},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:a}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function Lu(i,t){return A(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:St.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 a=new Ah(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)a.insertKeyFrame=!0;else if(!e){let{bitrate:h}=d.data;Ln({configureBr:[d.data.bitrate,h]}),a.configure({bitrate:h})}},this._log.info("start push",r,t),a})}function Og(i){return A(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:a}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=a;let d=yield Lu.call(this,i,r);this._log.info("VideoEncoder created",r);let h,m=T=>A(this,null,function*(){if(h==null||h.abort("track changed"),!T)return;h=new AbortController;let{width:I,height:v,displaySurface:N}=T.getSettings();I&&(d.config.width=I),v&&(d.config.height=v);let j=Qt.match(/Chrome\/(\d+)/);(j==null?void 0:j[1])==="114"&&N==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",T.readyState,T.getSettings());let H=new MediaStreamTrackProcessor({track:T}).readable,z="small"in i&&i.small;z?(this.smallEncoder||(this.smallEncoder=yield Lu.call(this,i,{profile:z,type:3,trackType:o})),this.smallEncoder.track=T,this.smallEncoder.label="small",H=this.smallEncoder.trans(H,h,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=T,d.label=e,d.start(H,h,this)});return be(De(i,"output-media-track-changed"),We(De(i,"capture")),ke(m,console.error,()=>{var T;this._log.info("stop push",e,r),h.abort("unpublish"),d.close(),(T=this.smallEncoder)==null||T.close()})),m(i.outMediaTrack)})}var zi=class zi extends re{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(zi.INTERVALCHANGED,this.interval)}),be(De(this,zi.INTERVALCHANGED),Fr(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(L_(s),Vs(()=>[]))),ke(s=>{s.forEach(a=>{this.room.remotePublishedUserMap.has(a.userId)&&(this.room.remotePublishedUserMap.get(a.userId).remoteAudioTrack.volume=a.volume)}),(!document.hidden||this.enableInBackground)&&this.state==re.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(zi.INTERVALCHANGED,this.interval)}stop(){}};l(zi,"INTERVALCHANGED","intervalChanged"),G([ye([re.INIT,re.OFF],re.ON)],zi.prototype,"start",1),G([ye([],re.OFF)],zi.prototype,"stop",1);var Uu=zi;var Xi=class Xi extends Mu{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 Uu(this));l(this,"enableAIVoice",Sh);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:um(),uint32_device_type:0,str_os_verion:lm(),uint32_link_type:1,str_client_version:Ke,uint32_net_type:ao[Pr.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,yh(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return A(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 a=new MessageChannel;this.postMessage({cmd:e,payload:r},[a.port1]),a.port2.onmessageerror=s,a.port2.onmessage=d=>{a.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var a;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(a=this.session)==null||a.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return A(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 A(this,null,function*(){var h,m,T;let s=Pr.getEnv(),a=Ad(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(h=this.proxy_wt)==null?void 0:h.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(T=this.scheduleResult.iceServers)!=null&&T.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:As(),browserInfo:Ad(),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:Ke,browserVersion:a.browserName+a.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 Cg.call(this,d),console.log(this),Pu.playAudio(I=>this.postMessage({cmd:"setAudioWorkletPort"},[I])),this.checkDestroy()})}_leave(e=0){return A(this,null,function*(){console.log(this.userId,"leave",e),this.remotePublishedUserMap.forEach(r=>{r.remoteAudioTrack.close(),r.remoteAuxiliaryTrack.close(),r.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((r,o)=>o.unpublish())})}leave(){return A(this,null,function*(){return this._leave()})}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 A(this,null,function*(){let e=We(De(this,"left"));be(r=>A(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,ke(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.buffer}});o.postMessage(new Uint8Array(s.data),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case P.RECEIVED_PUBLISHED_USER_LIST:F.emit(e,J({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new bu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let I=r,v=this.remotePublishedUserMap.get(I);v&&(v.remoteVideoTrack.close(),v.remoteAuxiliaryTrack.close(),v.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(I),this.emit("remote-unpublished",v))}return;case"banned":switch(this._leave(r),r){case 8:this.emit("banned",{reason:"kick",message:""});break;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});case 7:case 5:this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:I,muteState:v,flag:N}=r,j=this.remotePublishedUserMap.get(v.userId);if(!j){this.emit("remote-publish-state-changed",r);return}j.flag=N}F.emit(P.REMOTE_PUBLISH_STATE_CHANGED,J({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=J({},r);let{uplinkLoss:s,uplinkRTT:a,uplinkInfo:d,downlinkInfo:h,msg_down_stream_info:m}=r,T={str_sdk_version:Ke,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:ao[kn()]},msg_event_msg:U_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:m};F.emit(P.HEARTBEAT_REPORT,{room:this,report:T}),this.emit("heartbeat-report",T),F.emit(P.NETWORK_QUALITY,{room:this,uplink:{rtt:a,loss:s},downlinks:h}),delete r.downlinkInfo;break;case"signal-connection-state-changed":F.emit(P.SIGNAL_CONNECTION_STATE_CHANGED,J({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return A(this,null,function*(){let r=e.reduce((d,h)=>h.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,a=d=>A(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),vt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:Mg.call(this,d);break;default:yield Og.call(this,d)}});yield Promise.all(e.map(a)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return A(this,null,function*(){e.forEach(at)})}subscribe(...e){return A(this,null,function*(){let r=e.reduce((I,v)=>v.mediaType|I,0),{userId:o,tinyId:s,streamType:a}=e[0],d=this.remotePublishedUserMap.get(o),h=J({},d.subscribeState),m=Object.assign(new oa,h);m.mediaType|=r,F.emit(P.SUBSCRIBE_START,{room:this,streamType:a,remotePublishedUser:d,subscribeState:m});let T=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(I=>m.mediaType&I).map(I=>({mediaType:I,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",T),yield Promise.all(e.filter(I=>!I.isSubscribed).map(I=>{switch(I.mediaType){case 1:return Dg.call(this,I);default:return Ng.call(this,I)}})),F.emit(P.SUBSCRIBE_SUCCESS,{room:this,streamType:a,remotePublishedUser:d})})}unsubscribe(...e){return A(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:a}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:a,userId:o}),F.emit(P.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return A(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield Lu.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),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let a={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=a.mediaType,this.postMessage("changetype",a)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};G([Fi(Xi.prototype.afterJoin),ye(["left",re.INIT],"joined"),dg()],Xi.prototype,"join",1),G([ye("joined","left",{ignoreError:!0}),ug()],Xi.prototype,"_leave",1),G([Vd((...e)=>0),lg()],Xi.prototype,"publish",1),G([Vd((...e)=>0),mg()],Xi.prototype,"unpublish",1),G([Vd((...e)=>e[0].userId),pg()],Xi.prototype,"subscribe",1);var Vu=Xi;Js.frameWorkType=37;Js.create=function(i){let t=Js._create.call(this,Vu,i);return t._use(wa,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(St.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",Ke,"created",St),t};Object.assign(Js.prototype,{_setCurrentSpeaker(i){let t=lt("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return A(this,null,function*(){return this.startPlugin(wa.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{be(De(i,"decode-downgrade-state-changed"),Uo(o=>o.state==="STARTED"),Sr(1),Bp(1e4),We(De(i,re.INIT)),ke(e,r))})})}});var WB=Js;export{WB as default};
|