trtc-sdk-v5 5.8.1-beta.2 → 5.8.1-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -58,11 +58,11 @@ uniform sampler2D u_texture;
58
58
 
59
59
  void main() {
60
60
  gl_FragColor = texture2D(u_texture, v_texCoord);
61
- } `,Ro=class extends ${constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Or(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Dr(this,e)}createVideoImageSource(e,t){return new js(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new qs(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}},Gp={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ye=class extends Ro{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",Gp),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Fp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Hp),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,n=s.createShader(e);return s.shaderSource(n,t),s.compileShader(n),n}createProgram(e,t){let s=this.ctx,n=s.createProgram();return s.attachShader(n,e),s.attachShader(n,t),s.linkProgram(n),s.getProgramParameter(n,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(n)),n}};y([ue($.INIT,"created",{sync:!0})],ye.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],ye.prototype,"destroy",1);var $e=class extends Ro{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};y([ue($.INIT,"created",{sync:!0})],$e.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0})],$e.prototype,"destroy",1);function Wp(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var gt=class extends rt{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"pipeline",[]);this.manager=e.videoManager}play(e,t){return fs===17&&(t==null?void 0:t.canvasRender)!==!1&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new $e({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new Js(e);t.connect(s),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=Wp(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}get decodeFPS(){var o;let{msg_video_status:e}=((o=this.room.heartbeatReport)==null?void 0:o.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some(e=>e)}decodeFrame(e){return this.pipeline.reduce((t,s)=>s?s(t,this):t,e)}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Mr=class extends gt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Te(...r){}var Jp=r=>r();function Tc(){this.dispose()}var jp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",qp=1,oi=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new gc(i,this,this.streamId++);return Tt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Xs=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Te,this.error=Te,this.next=Te,this.dispose=Te,this.subscribe=Te,this.doDefer()}subscribe(i){return i instanceof oi?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Jp),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},F=class extends Xs{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}};function ul(r,...i){return i.reduce((e,t)=>t(e),r)}function ai(r,i,e){if(jp()){let t=Object.defineProperties(Object.setPrototypeOf(r,oi.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Tt.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof oi&&Tt.addSource(t,n)}return t}return r}function J(r,i){return function(...e){return t=>{if(t instanceof oi){let s=ai(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,Tt.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ni(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var gc=class extends F{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Tt.defer(this.source,this.id)})}next(i){Tt.next(this.source,this.id,i),this.sink.next(i)}complete(){Tt.complete(this.source,this.id),this.sink.complete()}error(i){Tt.complete(this.source,this.id,i),this.sink.error(i)}},Tt={addSource(r,i){Ni("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ni("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ni("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ni("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ni("defer",{id:r.id,streamId:i})},pipe(r){Ni("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ni("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=qp++),Ni("create",{name:r.toString(),id:r.id})}},bo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Sc=class extends Xs{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function No(){return r=>{let i=new Sc(r);if(r instanceof oi){let e=ai(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Tt.pipe(e),e}return ai(i.add.bind(i),"share",arguments)}}function Xp(...r){return ai(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new F(i);l.next=m=>{--t===0?(l.next=p=>{n[d]=p,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Ic=class extends F{constructor(i,...e){super(i);let t=new F(this.sink);t.next=s=>this.buffer=s,t.complete=Te,t.subscribe(Xp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},OA=J(Ic,"withLatestFrom"),Ac=class extends F{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},MA=J(Ac,"bufferCount"),Cc=class extends F{constructor(i,e){super(i),this.buffer=[];let t=new F(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=Te,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},kA=J(Cc,"buffer");function Rc(r){let i=arguments,e=No()(ai(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=Te,e.complete=Te,e.error=Te,e}function ll(r){return ai(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var yc=class extends F{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},Qp=J(yc,"reduce");var bc=class extends F{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},zp=J(bc,"filter"),Nc=class extends F{next(i){}},GA=J(Nc,"ignoreElements"),vc=class extends F{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Yp=J(vc,"take"),Dc=class extends F{constructor(i,e){super(i);let t=new F(i);t.next=()=>i.complete(),t.complete=Tc,t.subscribe(e)}},WA=J(Dc,"takeUntil"),Oc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Kp=J(Oc,"takeWhile");var Mc=class extends F{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},JA=J(Mc,"skip"),kc=class extends F{constructor(i,e){super(i),i.next=Te;let t=new F(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Tc,t.subscribe(e)}},jA=J(kc,"skipUntil"),Lc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Zp=J(Lc,"skipWhile"),e_={leading:!0,trailing:!1},xc=class extends F{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Pc=class extends F{constructor(i,e,t=e_){super(i),this.durationSelector=e,this.config=t,this._throttle=new xc(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=Te,this._throttle.complete(),super.complete()}},qA=J(Pc,"throttle");var wc=class extends F{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Vc=class extends F{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new wc(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},XA=J(Vc,"debounce");var Uc=class extends F{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},QA=J(Uc,"elementAt");var Bc=class extends F{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},zA=J(Bc,"findIndex"),$c=class extends F{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},YA=J($c,"first"),Fc=class extends F{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},KA=J(Fc,"last"),Hc=class extends F{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ZA=J(Hc,"every");var Gc=class extends F{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},rC=J(Gc,"scan"),Wc=class extends F{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},sC=J(Wc,"pairwise"),Jc=class extends F{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},hl=J(Jc,"map");var kr=class extends F{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Lr=class extends F{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},vo=class extends kr{},Do=class extends Lr{next(i){this.subInner(i,vo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vo)}}},t_=J(Do,"switchMap");function Lo(r){return(i,e)=>r(()=>i,e)}var nC=Lo(J(Do,"switchMapTo")),jc=class extends kr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Oo=class extends Lr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),jc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},oC=J(Oo,"concatMap"),aC=Lo(J(Oo,"concatMapTo")),qc=class extends kr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Mo=class extends Lr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,qc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},cC=J(Mo,"mergeMap"),dC=Lo(J(Mo,"mergeMapTo")),Xc=class extends kr{dispose(){this.context.resetNext(),super.dispose()}},ko=class extends Lr{next(i){this.next=Te,this.subInner(i,Xc)}},uC=J(ko,"exhaustMap"),lC=Lo(J(ko,"exhaustMapTo")),Qc=class extends F{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Rc(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},hC=J(Qc,"groupBy"),zc=class extends F{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},mC=J(zc,"timeInterval"),Yc=class extends F{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},pC=J(Yc,"bufferTime"),Kc=class extends F{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},_C=J(Kc,"delay"),Zc=class extends F{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},fC=J(Zc,"catchError");var ed=class extends F{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},SC=J(ed,"tap"),td=class extends F{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new bo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},IC=J(td,"timeout");var UC=ul(ll(250),hl(()=>performance.now()),No());var xr=new Map;T.on(E.JOIN_SUCCESS,({room:r})=>{ae(r.userId,{eventId:32788})});T.on(E.LEAVE_START,({room:r})=>{ae(r.userId,{eventId:32789})});T.on(E.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ae(r.room.userId,{eventId:i})}});T.on(E.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ae(r.room.userId,{eventId:i})}});T.on(E.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});T.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});T.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});T.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});T.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ae(r.userId,{eventId:t})});T.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n;switch(e){case"CONNECTED":i==="RECONNECTING"?n=s?32801:32798:n=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(n=s?32802:32799);break;case"RECONNECTING":n=s?32800:32797;break}n&&ae(r.userId,{eventId:n,remoteUserId:t})});T.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:n})=>{let o=t?1:0;s||(o=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:o,param2:a,streamType:n||2};i&&(c.remoteUserId=i,c.eventId=4005),ae(r,c),D.addEnum({key:i?514701:513701,value:o}),D.addEnum({key:i?514700:513700,value:a})});T.on(E.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ae(r.userId,e)}});function ae(r,i){let e=w(v({},i),{timestamp:zr()});xr.has(r)?xr.get(r).push(e):xr.set(r,[e])}function ml(r){if(xr.has(r)){let i=xr.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return xr.delete(r),i}return[]}var pl=Se(Ne(),1);var xo=class extends pl.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let n=`peer leave [${e}]`;g(t)||(n+=`:${Sa[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let s=t[this.key];if(e.findIndex(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=Ai(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ai(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function id({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return W((t,s)=>{let n=new Map;return T.on(E.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new b({code:A.INVALID_OPERATION,message:k({key:M.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var _l=!0,fl=function(){var r;_l&&(_l=!1,S.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${At}/en/index.html`),console.info(`* Changelog: ${At}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),S.info("TRTC Web SDK Version:",Re),S.info("UA:",navigator.userAgent),S.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Es().then(i=>{i&&S.info(dt)}))};var st={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"};var rd=(i=>(i.Debug="Debug",i))(rd||{});var P={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},Ft=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",I[I.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",I[I.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",I[I.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(Ft||{});function gl({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ft[r];try{s=El[n]}catch(o){s=El.UNKNOWN_ERROR}return z(s)?t=s(i):Y(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var El=w(v({},Ae),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' 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:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' 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:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=qi(r),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:r,deviceType:i=qi(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=qi(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function qi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Xi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=gl({code:t||e,params:v({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Ft[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");Ei?p.href=`ms-settings:privacy-${m[this.functionName]}`:yt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof b){let{stack:o}=e,a={code:P.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=P.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=P.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=P.ENV_NOT_SUPPORTED,e.getCode()===A.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ae.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case A.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case A.SERVER_TIMEOUT:case A.SWITCH_ROLE_FAILED:a.code=P.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=P.OPERATION_ABORT;break;case A.DEVICE_NOT_FOUND:case A.DEVICE_AUTO_RECOVER_FAILED:case A.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=i_(e.name));break;case A.UNKNOWN:break;default:a.code=P.OPERATION_FAILED}n=new Xi(a),o&&(n.stack+=o.substr(o.indexOf(`
61
+ } `,Ro=class extends ${constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Or(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Dr(this,e)}createVideoImageSource(e,t){return new js(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new qs(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}},Gp={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ye=class extends Ro{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",Gp),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Fp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Hp),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,n=s.createShader(e);return s.shaderSource(n,t),s.compileShader(n),n}createProgram(e,t){let s=this.ctx,n=s.createProgram();return s.attachShader(n,e),s.attachShader(n,t),s.linkProgram(n),s.getProgramParameter(n,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(n)),n}};y([ue($.INIT,"created",{sync:!0})],ye.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],ye.prototype,"destroy",1);var $e=class extends Ro{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};y([ue($.INIT,"created",{sync:!0})],$e.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0})],$e.prototype,"destroy",1);function Wp(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var gt=class extends rt{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"pipeline",[]);this.manager=e.videoManager}play(e,t){return(fs===17||(t==null?void 0:t.canvasRender))&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new $e({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new Js(e);t.connect(s),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=Wp(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}get decodeFPS(){var o;let{msg_video_status:e}=((o=this.room.heartbeatReport)==null?void 0:o.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some(e=>e)}decodeFrame(e){return this.pipeline.reduce((t,s)=>s?s(t,this):t,e)}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Mr=class extends gt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Te(...r){}var Jp=r=>r();function Tc(){this.dispose()}var jp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",qp=1,oi=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new gc(i,this,this.streamId++);return Tt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Xs=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Te,this.error=Te,this.next=Te,this.dispose=Te,this.subscribe=Te,this.doDefer()}subscribe(i){return i instanceof oi?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Jp),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},F=class extends Xs{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}};function ul(r,...i){return i.reduce((e,t)=>t(e),r)}function ai(r,i,e){if(jp()){let t=Object.defineProperties(Object.setPrototypeOf(r,oi.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Tt.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof oi&&Tt.addSource(t,n)}return t}return r}function J(r,i){return function(...e){return t=>{if(t instanceof oi){let s=ai(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,Tt.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ni(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var gc=class extends F{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Tt.defer(this.source,this.id)})}next(i){Tt.next(this.source,this.id,i),this.sink.next(i)}complete(){Tt.complete(this.source,this.id),this.sink.complete()}error(i){Tt.complete(this.source,this.id,i),this.sink.error(i)}},Tt={addSource(r,i){Ni("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ni("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ni("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ni("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ni("defer",{id:r.id,streamId:i})},pipe(r){Ni("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ni("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=qp++),Ni("create",{name:r.toString(),id:r.id})}},bo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Sc=class extends Xs{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function No(){return r=>{let i=new Sc(r);if(r instanceof oi){let e=ai(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Tt.pipe(e),e}return ai(i.add.bind(i),"share",arguments)}}function Xp(...r){return ai(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new F(i);l.next=m=>{--t===0?(l.next=p=>{n[d]=p,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Ic=class extends F{constructor(i,...e){super(i);let t=new F(this.sink);t.next=s=>this.buffer=s,t.complete=Te,t.subscribe(Xp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},OA=J(Ic,"withLatestFrom"),Ac=class extends F{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},MA=J(Ac,"bufferCount"),Cc=class extends F{constructor(i,e){super(i),this.buffer=[];let t=new F(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=Te,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},kA=J(Cc,"buffer");function Rc(r){let i=arguments,e=No()(ai(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=Te,e.complete=Te,e.error=Te,e}function ll(r){return ai(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var yc=class extends F{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},Qp=J(yc,"reduce");var bc=class extends F{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},zp=J(bc,"filter"),Nc=class extends F{next(i){}},GA=J(Nc,"ignoreElements"),vc=class extends F{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Yp=J(vc,"take"),Dc=class extends F{constructor(i,e){super(i);let t=new F(i);t.next=()=>i.complete(),t.complete=Tc,t.subscribe(e)}},WA=J(Dc,"takeUntil"),Oc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Kp=J(Oc,"takeWhile");var Mc=class extends F{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},JA=J(Mc,"skip"),kc=class extends F{constructor(i,e){super(i),i.next=Te;let t=new F(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Tc,t.subscribe(e)}},jA=J(kc,"skipUntil"),Lc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Zp=J(Lc,"skipWhile"),e_={leading:!0,trailing:!1},xc=class extends F{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Pc=class extends F{constructor(i,e,t=e_){super(i),this.durationSelector=e,this.config=t,this._throttle=new xc(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=Te,this._throttle.complete(),super.complete()}},qA=J(Pc,"throttle");var wc=class extends F{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Vc=class extends F{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new wc(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},XA=J(Vc,"debounce");var Uc=class extends F{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},QA=J(Uc,"elementAt");var Bc=class extends F{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},zA=J(Bc,"findIndex"),$c=class extends F{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},YA=J($c,"first"),Fc=class extends F{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},KA=J(Fc,"last"),Hc=class extends F{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ZA=J(Hc,"every");var Gc=class extends F{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},rC=J(Gc,"scan"),Wc=class extends F{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},sC=J(Wc,"pairwise"),Jc=class extends F{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},hl=J(Jc,"map");var kr=class extends F{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Lr=class extends F{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},vo=class extends kr{},Do=class extends Lr{next(i){this.subInner(i,vo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vo)}}},t_=J(Do,"switchMap");function Lo(r){return(i,e)=>r(()=>i,e)}var nC=Lo(J(Do,"switchMapTo")),jc=class extends kr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Oo=class extends Lr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),jc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},oC=J(Oo,"concatMap"),aC=Lo(J(Oo,"concatMapTo")),qc=class extends kr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Mo=class extends Lr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,qc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},cC=J(Mo,"mergeMap"),dC=Lo(J(Mo,"mergeMapTo")),Xc=class extends kr{dispose(){this.context.resetNext(),super.dispose()}},ko=class extends Lr{next(i){this.next=Te,this.subInner(i,Xc)}},uC=J(ko,"exhaustMap"),lC=Lo(J(ko,"exhaustMapTo")),Qc=class extends F{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Rc(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},hC=J(Qc,"groupBy"),zc=class extends F{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},mC=J(zc,"timeInterval"),Yc=class extends F{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},pC=J(Yc,"bufferTime"),Kc=class extends F{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},_C=J(Kc,"delay"),Zc=class extends F{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},fC=J(Zc,"catchError");var ed=class extends F{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},SC=J(ed,"tap"),td=class extends F{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new bo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},IC=J(td,"timeout");var UC=ul(ll(250),hl(()=>performance.now()),No());var xr=new Map;T.on(E.JOIN_SUCCESS,({room:r})=>{ae(r.userId,{eventId:32788})});T.on(E.LEAVE_START,({room:r})=>{ae(r.userId,{eventId:32789})});T.on(E.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ae(r.room.userId,{eventId:i})}});T.on(E.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ae(r.room.userId,{eventId:i})}});T.on(E.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});T.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});T.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});T.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});T.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ae(r.userId,{eventId:t})});T.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n;switch(e){case"CONNECTED":i==="RECONNECTING"?n=s?32801:32798:n=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(n=s?32802:32799);break;case"RECONNECTING":n=s?32800:32797;break}n&&ae(r.userId,{eventId:n,remoteUserId:t})});T.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:n})=>{let o=t?1:0;s||(o=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:o,param2:a,streamType:n||2};i&&(c.remoteUserId=i,c.eventId=4005),ae(r,c),D.addEnum({key:i?514701:513701,value:o}),D.addEnum({key:i?514700:513700,value:a})});T.on(E.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ae(r.userId,e)}});function ae(r,i){let e=w(v({},i),{timestamp:zr()});xr.has(r)?xr.get(r).push(e):xr.set(r,[e])}function ml(r){if(xr.has(r)){let i=xr.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return xr.delete(r),i}return[]}var pl=Se(Ne(),1);var xo=class extends pl.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let n=`peer leave [${e}]`;g(t)||(n+=`:${Sa[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let s=t[this.key];if(e.findIndex(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=Ai(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ai(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function id({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return W((t,s)=>{let n=new Map;return T.on(E.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new b({code:A.INVALID_OPERATION,message:k({key:M.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var _l=!0,fl=function(){var r;_l&&(_l=!1,S.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${At}/en/index.html`),console.info(`* Changelog: ${At}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),S.info("TRTC Web SDK Version:",Re),S.info("UA:",navigator.userAgent),S.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Es().then(i=>{i&&S.info(dt)}))};var st={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"};var rd=(i=>(i.Debug="Debug",i))(rd||{});var P={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},Ft=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",I[I.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",I[I.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",I[I.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(Ft||{});function gl({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ft[r];try{s=El[n]}catch(o){s=El.UNKNOWN_ERROR}return z(s)?t=s(i):Y(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var El=w(v({},Ae),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' 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:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' 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:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=qi(r),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:r,deviceType:i=qi(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=qi(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=qi(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function qi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Xi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=gl({code:t||e,params:v({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Ft[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");Ei?p.href=`ms-settings:privacy-${m[this.functionName]}`:yt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof b){let{stack:o}=e,a={code:P.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=P.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=P.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=P.ENV_NOT_SUPPORTED,e.getCode()===A.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ae.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case A.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case A.SERVER_TIMEOUT:case A.SWITCH_ROLE_FAILED:a.code=P.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=P.OPERATION_ABORT;break;case A.DEVICE_NOT_FOUND:case A.DEVICE_AUTO_RECOVER_FAILED:case A.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=i_(e.name));break;case A.UNKNOWN:break;default:a.code=P.OPERATION_FAILED}n=new Xi(a),o&&(n.stack+=o.substr(o.indexOf(`
62
62
  `)))}else{if(e instanceof Xi)return e;n=new Xi({code:P.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function i_(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var L=Xi;var Tl={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}}},Sl={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}}},Pr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)&&!document.getElementById(r))throw new L({code:P.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Il={name:"userId",required:!0,type:"string"},Al={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[st.AUDIO_PROFILE_STANDARD,st.AUDIO_PROFILE_STANDARD_STEREO,st.AUDIO_PROFILE_HIGH,st.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function zs(r,i){if(!r)throw new L({code:P.INVALID_OPERATION,extraCode:5101,fnName:i})}function Cl(r,i,e){if(!r)throw new L({code:P.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var My={type:"number",notLessThanZero:!0},r_={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new L({code:P.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new L({code:P.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new L({code:P.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new L({code:P.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new L({code:P.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:Pr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Tl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},Pr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Tl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Al},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Al}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Pr,publish:{type:"boolean"},option:Sl},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ds())throw new L({code:P.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Pr,publish:{type:"boolean"},option:Sl}},muteRemoteAudio:[Il,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Il,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Pr,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(r,i,e){zs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Cl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:P.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},Pr),{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(r,i,e){zs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Cl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:P.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&g(r.streamType))throw new L({code:P.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){zs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!ft)throw new L({code:P.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new L({code:P.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new L({code:P.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:P.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});zs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new L({code:P.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},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(r,i,e,t){if(r.byteLength>1e3)throw new L({code:P.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:P.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(zs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new L({code:P.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:r_};var Me=class extends Error{};function s_(r,i){let e=Sr(r);for(let t=0;t<i.length;t++)Yt(e[t],i[t]);return e}function n_(r){this._resolve=Promise.resolve(r)}function o_(r){this._reject=Promise.reject(r)}var Qi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=s_;let t=Qi.instances.get(i);t?t.set(e,this):Qi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Qi.instances.get(i);return t&&t.get(e)||new Qi(i,e)}static gets(i,e){let t=Qi.instances.get(i),s=[];return t&&t.forEach((n,o)=>{e.test(o)&&s.push(n)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Me("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:n_,reject:o_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),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,i.args),this.lastOp.promise;case 3:throw new Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.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}},Ht=Qi;Ht.instances=new WeakMap;var wo=new WeakMap,Vo=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new L({code:P.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
63
63
  `)))}throw i};function vi(r,i){return W((e,t)=>function(...s){let n=Ht.get(this,typeof r=="string"?r:r.call(this,...s));return n?(i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(Vo.bind(null,t))):e.apply(this,s)})}function zi(r,i){let{merge:e,debounce:t}=i||{};return W((s,n)=>function(...o){let a=Ht.get(this,typeof r=="string"?r:r.call(this,...o));if(!a)return s.apply(this,o);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var R,C;let p=(R=wo.get(this))==null?void 0:R.get(d(...o));if(p){let{timeoutId:N,resolve:U}=p;clearTimeout(N),U()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(Vo.bind(null,n)).then(l,m)},c);wo.has(this)?(C=wo.get(this))==null||C.set(d(...o),{timeoutId:f,resolve:l}):wo.set(this,new Map([[d(...o),{timeoutId:f,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(Vo.bind(null,n))})}function Di(r){return W((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Ht.gets(this,s).map(o=>o.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let n=Ht.get(this,s);return n?n.action(3,i.bind(this),t).catch(Vo.bind(null,e)):i.apply(this,t)})}var H={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",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"};function Uo(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Yi(r){return r===st.QOS_PREFERENCE_CLEAR?"detail":r===st.QOS_PREFERENCE_SMOOTH?"motion":""}var a_=r=>r.startsWith("data:application/octet-stream;base64,"),c_=r=>r.startsWith("file://"),Bo=class{constructor(){u(this,"_log");this._log=S.createLogger({id:"fd"})}download(i,e){return _(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),n;if(z(fetch)?n=yield this.downloadWithFetch(i,t):n=yield this.downloadWithXHR(i,t),!n||!n.data)throw new Error("data is empty");let o=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${o}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),n.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return _(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let n=new XMLHttpRequest;n.open("GET",i,!0),n.responseType=e,n.onload=()=>{n.status===200||n.status===0&&n.response?t({data:n.response}):s(new Error("XHR failed"))},n.onerror=s,n.send(null)})}loadWasm(i,e){return _(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,n=null;if(z(WebAssembly.instantiateStreaming)&&!a_(i)&&!c_(i)&&z(fetch))try{let o=fetch(i);s=(yield WebAssembly.instantiateStreaming(o,e)).instance}catch(o){n=o}if(!s)try{let o=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(o,e)).instance}catch(o){n=o}if(s){let o=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${o}ms`),D.addSuccessEvent({key:522701,cost:o}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${n}`),D.addFailedEvent({key:522701,error:n}),n})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Bo.prototype,"download",1);var Rl=new Bo;function yl({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Rl,innerEmitter:T,constants:Ia,environment:Er,utils:Pe,eventLogger:Z,log:this.room.getLogger(),loggerManager:S,errorModule:e,kvStatManager:D,trtc:this,clearStarted:(s,n)=>{let o=s.getAlias(),a=Ht.instances.get(this);if(!!a)if(n){let c=a.get(o+n);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(o)&&(c.started=!1)})}}}var bl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=k({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return S.warn(`${n}
64
64
 
65
- ${s.stack}`),!1}},r};var $o=new WeakMap;function Nl(r,i){return W((e,t)=>function(...s){var a,c;let n=(a=$o.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);$o.has(this)?(c=$o.get(this))==null||c.set(i(...s),o):$o.set(this,new Map([[i(...s),o]]))})}var vl="5.8.1-beta.2";function ke(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function od(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ho(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Fo.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Fo.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Fo({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:P.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new L(n(5001));if(g(r.defaultValue)){z(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),z(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new L({code:P.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Cs(d)?Wn(d):Y(d)?d:fe(d))},value:i}})}else if(!g(r.type)&&fe(i)!==r.type)throw new L(n(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new L(n(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new L(n(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new L(n(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new L(n(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new L(n(5004))}else if(z(r.instanceOf)&&!(i instanceof r.instanceOf))throw new L(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new L(n(5005));let{properties:o}=r;Ge(o)&&mt(i)&&Object.keys(o).forEach(c=>{Fo.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Ge(a)&&he(i)&&i.forEach((c,d)=>{Fo.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),z(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,n)=>function(...o){function a(l,m,p){if(p&&p.includes(l))return"hided";if(e){let f=e(...o);if(o[f.argIndex]===m)return f.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${fe(m)}`:(JSON.stringify(m),m)}catch(f){return`type:${fe(m)}`}}let c=this._log||S;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):ro[n];try{let l=s.apply(this,o),m=x();return As(l)?l.then(p=>(c.info(`${n}() success ${i.call(this,...o)}`),D.addSuccessEvent({key:d,cost:x()-m}),p)).catch(p=>{throw p=L.convertFrom.call(this,p,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${p} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:p}),p}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=L.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var Go=r=>W((i,e)=>function(t,s){return _(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new L({code:P.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ho.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Wo=0,ad=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new br(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function wr(r,i){if(i&&typeof i!="function")throw new L({code:P.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Vr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Wo=Wo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wo}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Wo}`),this.core=i}getName(){return Vr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Vr.startValidateRule;case"update":return Vr.updateValidateRule;case"stop":return Vr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new ad(i,e.audioManager),this.cacheMusicMap.set(t,n)),n.updateListener(i),n.updateSettings(i),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:n}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let o=this.mixedMusicMap.get(e);if(!o){this.log.warn(`update music source failed, music id: ${e} not found.`);return}o.updateSettings(i),o.updateListener(i),g(t)||o.setOperation(t),g(s)||o.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:n,operation:o,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),n&&D.addCount({key:502705}),o&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,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()}},Oi=Vr;u(Oi,"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(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new L({code:P.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new L({code:P.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});wr("onTimeUpdate",i.onTimeUpdate),wr("onEnded",i.onEnded),wr("onDurationChange",i.onDurationChange)}}),u(Oi,"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(i,e,t){wr("onTimeUpdate",i.onTimeUpdate),wr("onEnded",i.onEnded),wr("onDurationChange",i.onDurationChange)}}),u(Oi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Oi,"Name","AudioMixer");var u_=r=>(r=Number(r),r>0&&r<14e8),Jo=0,cd,Ur=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",Je("denoiser"));u(this,"workletNode");Jo=Jo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Jo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Jo}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){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,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new L({code:P.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return cd||(cd=this.doPreload(i)),cd}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Fi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Ur.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ur.startValidateRule(this.core);case"update":return Ur.updateValidateRule;case"stop":return Ur.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield h_(w(v({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new L({code:P.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Ki=Ur;u(Ki,"updateValidateRule",{type:"object"}),u(Ki,"stopValidateRule",{type:"object"}),u(Ki,"Name","AIDenoiser");var Dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function l_(r){let i;return u_(r)?i=Dl.MAIN_OVERSEA:i=Dl.MAIN,i}function h_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${l_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let p="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${f}`:`${p}, ${f}`}})}var Ol=Se(Ne(),1);var dd=class extends Ol.EventEmitter{constructor(){super();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 _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!de&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&S.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},m_=new dd,ud=m_;var ld=0,hd=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);ld++,this.log=i.log.createChild({id:`${this.getAlias()}${ld}`}),this.log.info(`[sei] created id=${this.getAlias()}${ld}`),this.core=i}hasSEI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}encodeSEINalu([i,e]){let t=e.byteLength,s=parseInt(String(t/255),10),n=t%255,o=[];o.push(0,0,0,1,6,i);for(let c=0;c<s;c++)o.push(255);o.push(n);let a=new DataView(e);return o.push(...new Uint8Array(a.buffer)),o.push(128),new ji(new DataView(new Uint8Array(o).buffer),!0)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),n=9-s;if(n<=0)return 0;let o=t.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),a=o.reduce((p,f)=>p+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let f=0;f<o[p].dataView.byteLength;f++)d.setInt8(m++,o[p].dataView.getInt8(f));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,l.getInt8(p));return i.data=c,o.length}return 0}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}decode(i,e){try{if(i.type==="empty"||i.data.byteLength===0)return i;let t=new DataView(i.data);if(!this.hasSEI(t))return i;let s=[],n=0,o=-1,a=-1;for(let c=0;c<i.data.byteLength;c++){let d=t.getUint8(c);if(d===0)n++;else if(d===1){if(n===2||n===3){let l=c-n;if(o===-1?o=l:a===-1&&(a=l,s.push(new ji(new DataView(t.buffer.slice(o,a)))),o=l,a=-1),!(t.getUint8(c+1)===6)){i.data=t.buffer.slice(l);break}}n=0}else n=0}this.log.debug(`${s.length} sei received`),s.reverse().forEach(c=>{this.core.trtc.emit(H.SEI_MESSAGE,{seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}catch(t){this.log.warn(t)}return i}start(i){this.core.room.videoManager.enableSEI((e,t)=>{try{let s=this.encode(e,t);s&&this.log.debug(`${s} sei sent`)}catch(s){this.log.warn(s)}return e},(e,t)=>this.decode(e,t))}stop(i){this.core.room.videoManager.disableSEI()}update(i){(i.options.toSubStream?this._subStreamSeiMessageList:this._seiMessageList).push([i.options.seiPayloadType,i.buffer])}getName(){return hd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Ys=hd;u(Ys,"Name","SEI");var Ml=0,jo=new Set,Le=null;da(vl);var p_={RtcError:L,ErrorCode:P,ErrorCodeDictionary:Ft},Br=class extends kl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",S.createLogger({id:`t${++Ml}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(v({logger:this._log,frameWorkType:Br.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Oi,t.assetsPath),this._use(Ki,t.assetsPath),t.enableSEI&&ft&&(this._use(Ys),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(H.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new L({code:P.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),bl(this,"trtc")}static create(e){}static _create(e,t){fl();let s=new Br(e,t||{});return jo.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(H.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(H.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(H.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(H.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(H.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit(H.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",n=>{let o=w(v({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Uo(s.streamType)),this.emit(s.kind===h.AUDIO?H.AUDIO_PLAY_STATE_CHANGED:H.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===A.PLAY_NOT_ALLOWED&&this.emit(H.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?H.REMOTE_AUDIO_AVAILABLE:H.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?H.REMOTE_VIDEO_AVAILABLE:H.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?H.REMOTE_VIDEO_AVAILABLE:H.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit(H.ERROR,new L({code:P.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/ct},video:p.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit(H.STATISTICS,s)}).add("custom-message",e=>{this.emit(H.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===rs){let t=(yield Wi()).find(s=>s.deviceId===rs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Wi())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===rs&&Le.groupId!==t.groupId)&&(Le=t,this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(yl.call(this,{TRTC:Br,room:this._room,errorModule:p_,assetsPath:t}));this._plugins.set(e.Name,n),Object.values(rd).includes(n.getName())&&(this.startPlugin(n.getName()),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,pe(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Br.frameWorkType),this._checkTrackToPublish(),ud.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){me(this),this.removeAllListeners(),this._room.destroy(),jo.delete(this),jo.size===0&&ud.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:n}=e,o=new Oe(this._room.audioManager),a={},c={muted:!0};n&&(g(n.microphoneId)?g(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&ee(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),g(n.profile)||(Y(n.profile)?gn[n.profile]&&o.setProfile(gn[n.profile]):o.setProfile(n.profile)),ee(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),g(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),g(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),g(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=L.convertFrom(d.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),g(s)||o.setMute(s),De(o,o).add("player-state-changed",d=>{this.emit(H.AUDIO_PLAY_STATE_CHANGED,w(v({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):g(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),g(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),g(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Yt(this._localAudioConfig,e)})}stopLocalAudio(){return _(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),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:n,option:o}=e,a=new le(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:g(o.useFrontCamera)?g(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(o.profile)||(Y(o.profile)?Ke[o.profile]&&a.setProfile(Ke[o.profile]):a.setProfile(o.profile)),g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),g(o.small)||(Os()?Y(o.small)?a.small=Ke[o.small]:o.small===!0?a.small=Ke["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=L.convertFrom(l.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Yi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(g(o.profile)||(Y(o.profile)?Ke[o.profile]&&this._localVideoTrack.setProfile(Ke[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&g(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):g(o.useFrontCamera)?g(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(o.fillMode)||(a.objectFit=o.fillMode),g(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Yi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Os()?(o.small===!0?this._localVideoTrack.small=Ke["120p"]:Y(o.small)?this._localVideoTrack.small=Ke[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Yt(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:n}=e,o=new Xe(this._room.videoManager);o.on("4",m=>{let p;m.error&&(p=L.convertFrom(m.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},m),{error:p}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(g(n.profile)||(Y(n.profile)?Tn[n.profile]&&o.setProfile(Tn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),g(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Yi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(H.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new $t(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(o,o).add("player-state-changed",m=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(g(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Yi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Yt(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),d.canvasRender=o.canvasRender,n==="main"&&!g(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!g(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var N,U;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:p}=c;n==="main"&&o&&!g(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:p}),Yt(p,e);let f=g(o==null?void 0:o.receiveWhenViewVisible)?(N=p.option)==null?void 0:N.receiveWhenViewVisible:o.receiveWhenViewVisible,R=g(t)?p.view:t,C=g(o==null?void 0:o.viewRoot)?(U=p.option)==null?void 0:U.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&(yield this._startRemoteAudio({userId:n.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(Y(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(g(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),g(e)&&n&&n.view&&!Ba(t)){let a=ys(n.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ys(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.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,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(H.TRACK,{userId:s,streamType:Uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.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:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(g(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Uo(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(ys(t));d.forEach((p,f)=>{m.has(f)||(a.unobserve(f),d.delete(f))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return _(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 t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Nr(Le))this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Wi();if(e[0]&&!Nr(e[0]))Le=e[0],this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Nr(Le))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:t||{seiPayloadType:243}}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){S.setLogLevel(e),g(t)||(t?S.enableUploadLog():S.disableUploadLog())}static isSupported(){return Kn()}static getCameraList(e=!0){return je(e)}static getMicrophoneList(e=!0){return Ue(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield Wi()).forEach(s=>{s.deviceId===e&&(jo.forEach(n=>{n.setCurrentSpeaker(e),n.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&($i.version=a),e){case"count":$i.addCount({key:t,useUV:o});break;case"enum":$i.addEnum({key:t,value:s,useUV:o});break;case"number":$i.addNumber({key:t,value:s,split:n});break}}},Q=Br;u(Q,"_loggerManager",S),u(Q,"EVENT",H),u(Q,"ERROR_CODE",P),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),vi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],Q.prototype,"enterRoom",1),y([ne()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),zi("room",{merge:(r,i)=>i}),ne()],Q.prototype,"switchRole",1),y([ne()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),vi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),zi("audio",{debounce:{delay:200,getKey:()=>`${Ml}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],Q.prototype,"updateLocalAudio",1),y([Di("audio"),ne()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),vi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),zi("video"),ne()],Q.prototype,"updateLocalVideo",1),y([Di("video"),ne()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),vi("screen",()=>!0),ne()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),zi("screen"),ne()],Q.prototype,"updateScreenShare",1),y([ne()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),vi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),zi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),W(r=>function(i){return _(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Di(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([od(...Ce.TRTC.setRemoteAudioVolume),Nl(200,r=>r),ne({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([Go("start"),yi(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),vi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>tc[r.getName()]})],Q.prototype,"startPlugin",1),y([Go("update"),zi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ic[r.getName()]})],Q.prototype,"updatePlugin",1),y([Go("stop"),Di((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>rc[r.getName()]})],Q.prototype,"stopPlugin",1),y([od(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([ne()],Q.prototype,"getVideoSnapshot",1),y([ne()],Q.prototype,"setCurrentSpeaker",1),y([vi(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([W(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(w(v({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Di(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Di("room")],Q.prototype,"_exitRoom",1),y([Di("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var Ks=Q;var md=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function __(){return _(this,null,function*(){let r,i;try{let m=yield Ue();r=m&&m.length}catch(m){}try{let m=yield je();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=ii.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Ll(){return W(r=>{let i=new md;return function(e,t,s){return _(this,null,function*(){let n=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=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:A.INVALID_OPERATION,message:k({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:k({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield ii.checkSystemRequirementsInternal(),this.checkDestroy();let o=Pe.getEnv();o||(o=Jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Sn.OLD_CLOUD_LADDER)?o=Jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Sn.WEBRTC)&&(o=Jt.WEBRTC))),Z.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),__.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ii.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:k({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Pe.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Pe.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(Xt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var xl=()=>W(r=>function(...i){return _(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Pl(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Vl=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var St={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},wl=[St.UPDATE_REMOTE_MUTE_STAT,St.UPLINK_NETWORK_STATS,St.USER_LIST_RES,St.MUTE_RESULT,St.SERVER_FIRST_PACKAGE_RECEIVED,St.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},j={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var qo=new Set;function Ul(r){let i=[...qo.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var $r=class extends Vl.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-qo.size>0&&this.room.enableSPC&&(this.keepAlive=!0,qo.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=S.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return _(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=x();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Ss(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Jn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(St),c=Object.keys(St)[o.indexOf(s)],d=V[c]||s;switch(wl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case St.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Jd(n.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:k({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:l}),this.emit(_e.SETUP_FAILED,l)}break}case St.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;Ot(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Jn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let f=new b({code:A.API_CALL_TIMEOUT,message:k({key:M.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(f),d(f)},s),m=f=>{f.data.seq===p&&(clearTimeout(l),this.off(n,m),c(f))};this.on(n,m);let p=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),qo.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=n=>{n.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],$r.prototype,"connect",1);var Bl=Se(Ne());var pd=0,_d=!1,Qo=new Set,E_=r=>pd>2&&!_d&&Qo.size===0&&r,fd=!1,ze=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new Bl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=S.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={encodedInsertableStreams:this._enableSEI&&ft,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Qo.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ot;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return ot;i=this._peerConnection.getSenders()[0].transport}else{if(!Bi()||this._peerConnection.getReceivers().length===0)return ot;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ot}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:we.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(pd=0,_d=!1,fd=!0,Qo.add(this)):Qo.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Ci(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});pd+=1,E_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),_d=!0,this._emitter.emit("firewall-restriction")),e(a)},is);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=jt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:k({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(_e.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var Sd=Se(Td());var ce=function(r){return Sd.default.parse(r)},Ye=function(r){return Sd.default.write(r)},ql=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Ye(i)};function Xl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),Ye(i)}function zo(r){return Object.keys(r).filter(i=>r[i])}var Ad=class extends ze{constructor(e){super(w(v({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ni(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new gt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Mr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===ts?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
65
+ ${s.stack}`),!1}},r};var $o=new WeakMap;function Nl(r,i){return W((e,t)=>function(...s){var a,c;let n=(a=$o.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);$o.has(this)?(c=$o.get(this))==null||c.set(i(...s),o):$o.set(this,new Map([[i(...s),o]]))})}var vl="5.8.1-beta.4";function ke(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function od(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ho(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Fo.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Fo.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Fo({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:P.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new L(n(5001));if(g(r.defaultValue)){z(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),z(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new L({code:P.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Cs(d)?Wn(d):Y(d)?d:fe(d))},value:i}})}else if(!g(r.type)&&fe(i)!==r.type)throw new L(n(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new L(n(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new L(n(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new L(n(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new L(n(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new L(n(5004))}else if(z(r.instanceOf)&&!(i instanceof r.instanceOf))throw new L(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new L(n(5005));let{properties:o}=r;Ge(o)&&mt(i)&&Object.keys(o).forEach(c=>{Fo.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Ge(a)&&he(i)&&i.forEach((c,d)=>{Fo.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),z(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,n)=>function(...o){function a(l,m,p){if(p&&p.includes(l))return"hided";if(e){let f=e(...o);if(o[f.argIndex]===m)return f.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${fe(m)}`:(JSON.stringify(m),m)}catch(f){return`type:${fe(m)}`}}let c=this._log||S;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):ro[n];try{let l=s.apply(this,o),m=x();return As(l)?l.then(p=>(c.info(`${n}() success ${i.call(this,...o)}`),D.addSuccessEvent({key:d,cost:x()-m}),p)).catch(p=>{throw p=L.convertFrom.call(this,p,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${p} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:p}),p}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=L.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var Go=r=>W((i,e)=>function(t,s){return _(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new L({code:P.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ho.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Wo=0,ad=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new br(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function wr(r,i){if(i&&typeof i!="function")throw new L({code:P.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Vr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Wo=Wo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wo}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Wo}`),this.core=i}getName(){return Vr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Vr.startValidateRule;case"update":return Vr.updateValidateRule;case"stop":return Vr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new ad(i,e.audioManager),this.cacheMusicMap.set(t,n)),n.updateListener(i),n.updateSettings(i),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:n}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let o=this.mixedMusicMap.get(e);if(!o){this.log.warn(`update music source failed, music id: ${e} not found.`);return}o.updateSettings(i),o.updateListener(i),g(t)||o.setOperation(t),g(s)||o.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:n,operation:o,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),n&&D.addCount({key:502705}),o&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,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()}},Oi=Vr;u(Oi,"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(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new L({code:P.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new L({code:P.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});wr("onTimeUpdate",i.onTimeUpdate),wr("onEnded",i.onEnded),wr("onDurationChange",i.onDurationChange)}}),u(Oi,"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(i,e,t){wr("onTimeUpdate",i.onTimeUpdate),wr("onEnded",i.onEnded),wr("onDurationChange",i.onDurationChange)}}),u(Oi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Oi,"Name","AudioMixer");var u_=r=>(r=Number(r),r>0&&r<14e8),Jo=0,cd,Ur=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",Je("denoiser"));u(this,"workletNode");Jo=Jo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Jo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Jo}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){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,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new L({code:P.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return cd||(cd=this.doPreload(i)),cd}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Fi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Ur.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ur.startValidateRule(this.core);case"update":return Ur.updateValidateRule;case"stop":return Ur.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield h_(w(v({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new L({code:P.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Ki=Ur;u(Ki,"updateValidateRule",{type:"object"}),u(Ki,"stopValidateRule",{type:"object"}),u(Ki,"Name","AIDenoiser");var Dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function l_(r){let i;return u_(r)?i=Dl.MAIN_OVERSEA:i=Dl.MAIN,i}function h_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${l_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let p="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${f}`:`${p}, ${f}`}})}var Ol=Se(Ne(),1);var dd=class extends Ol.EventEmitter{constructor(){super();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 _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!de&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&S.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},m_=new dd,ud=m_;var ld=0,hd=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);ld++,this.log=i.log.createChild({id:`${this.getAlias()}${ld}`}),this.log.info(`[sei] created id=${this.getAlias()}${ld}`),this.core=i}hasSEI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}encodeSEINalu([i,e]){let t=e.byteLength,s=parseInt(String(t/255),10),n=t%255,o=[];o.push(0,0,0,1,6,i);for(let c=0;c<s;c++)o.push(255);o.push(n);let a=new DataView(e);return o.push(...new Uint8Array(a.buffer)),o.push(128),new ji(new DataView(new Uint8Array(o).buffer),!0)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),n=9-s;if(n<=0)return 0;let o=t.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),a=o.reduce((p,f)=>p+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let f=0;f<o[p].dataView.byteLength;f++)d.setInt8(m++,o[p].dataView.getInt8(f));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,l.getInt8(p));return i.data=c,o.length}return 0}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}decode(i,e){try{if(i.type==="empty"||i.data.byteLength===0)return i;let t=new DataView(i.data);if(!this.hasSEI(t))return i;let s=[],n=0,o=-1,a=-1;for(let c=0;c<i.data.byteLength;c++){let d=t.getUint8(c);if(d===0)n++;else if(d===1){if(n===2||n===3){let l=c-n;if(o===-1?o=l:a===-1&&(a=l,s.push(new ji(new DataView(t.buffer.slice(o,a)))),o=l,a=-1),!(t.getUint8(c+1)===6)){i.data=t.buffer.slice(l);break}}n=0}else n=0}this.log.debug(`${s.length} sei received`),s.reverse().forEach(c=>{this.core.trtc.emit(H.SEI_MESSAGE,{seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}catch(t){this.log.warn(t)}return i}start(i){this.core.room.videoManager.enableSEI((e,t)=>{try{let s=this.encode(e,t);s&&this.log.debug(`${s} sei sent`)}catch(s){this.log.warn(s)}return e},(e,t)=>this.decode(e,t))}stop(i){this.core.room.videoManager.disableSEI()}update(i){(i.options.toSubStream?this._subStreamSeiMessageList:this._seiMessageList).push([i.options.seiPayloadType,i.buffer])}getName(){return hd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Ys=hd;u(Ys,"Name","SEI");var Ml=0,jo=new Set,Le=null;da(vl);var p_={RtcError:L,ErrorCode:P,ErrorCodeDictionary:Ft},Br=class extends kl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",S.createLogger({id:`t${++Ml}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(v({logger:this._log,frameWorkType:Br.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Oi,t.assetsPath),this._use(Ki,t.assetsPath),t.enableSEI&&ft&&(this._use(Ys),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(H.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new L({code:P.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),bl(this,"trtc")}static create(e){}static _create(e,t){fl();let s=new Br(e,t||{});return jo.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(H.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(H.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(H.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(H.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(H.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit(H.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",n=>{let o=w(v({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Uo(s.streamType)),this.emit(s.kind===h.AUDIO?H.AUDIO_PLAY_STATE_CHANGED:H.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===A.PLAY_NOT_ALLOWED&&this.emit(H.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?H.REMOTE_AUDIO_AVAILABLE:H.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?H.REMOTE_VIDEO_AVAILABLE:H.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?H.REMOTE_VIDEO_AVAILABLE:H.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit(H.ERROR,new L({code:P.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/ct},video:p.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit(H.STATISTICS,s)}).add("custom-message",e=>{this.emit(H.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===rs){let t=(yield Wi()).find(s=>s.deviceId===rs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Wi())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===rs&&Le.groupId!==t.groupId)&&(Le=t,this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(yl.call(this,{TRTC:Br,room:this._room,errorModule:p_,assetsPath:t}));this._plugins.set(e.Name,n),Object.values(rd).includes(n.getName())&&(this.startPlugin(n.getName()),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,pe(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Br.frameWorkType),this._checkTrackToPublish(),ud.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){me(this),this.removeAllListeners(),this._room.destroy(),jo.delete(this),jo.size===0&&ud.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:n}=e,o=new Oe(this._room.audioManager),a={},c={muted:!0};n&&(g(n.microphoneId)?g(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&ee(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),g(n.profile)||(Y(n.profile)?gn[n.profile]&&o.setProfile(gn[n.profile]):o.setProfile(n.profile)),ee(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),g(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),g(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),g(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=L.convertFrom(d.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),g(s)||o.setMute(s),De(o,o).add("player-state-changed",d=>{this.emit(H.AUDIO_PLAY_STATE_CHANGED,w(v({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):g(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),g(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),g(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Yt(this._localAudioConfig,e)})}stopLocalAudio(){return _(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),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:n,option:o}=e,a=new le(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:g(o.useFrontCamera)?g(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(o.profile)||(Y(o.profile)?Ke[o.profile]&&a.setProfile(Ke[o.profile]):a.setProfile(o.profile)),g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),g(o.small)||(Os()?Y(o.small)?a.small=Ke[o.small]:o.small===!0?a.small=Ke["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=L.convertFrom(l.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Yi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(g(o.profile)||(Y(o.profile)?Ke[o.profile]&&this._localVideoTrack.setProfile(Ke[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&g(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):g(o.useFrontCamera)?g(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(o.fillMode)||(a.objectFit=o.fillMode),g(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Yi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Os()?(o.small===!0?this._localVideoTrack.small=Ke["120p"]:Y(o.small)?this._localVideoTrack.small=Ke[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Yt(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:n}=e,o=new Xe(this._room.videoManager);o.on("4",m=>{let p;m.error&&(p=L.convertFrom(m.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},m),{error:p}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(g(n.profile)||(Y(n.profile)?Tn[n.profile]&&o.setProfile(Tn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),g(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Yi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(H.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new $t(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(o,o).add("player-state-changed",m=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(g(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Yi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Yt(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),d.canvasRender=o.canvasRender,n==="main"&&!g(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!g(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var N,U;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:p}=c;n==="main"&&o&&!g(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:p}),Yt(p,e);let f=g(o==null?void 0:o.receiveWhenViewVisible)?(N=p.option)==null?void 0:N.receiveWhenViewVisible:o.receiveWhenViewVisible,R=g(t)?p.view:t,C=g(o==null?void 0:o.viewRoot)?(U=p.option)==null?void 0:U.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&(yield this._startRemoteAudio({userId:n.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(Y(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(g(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),g(e)&&n&&n.view&&!Ba(t)){let a=ys(n.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ys(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.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,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(H.TRACK,{userId:s,streamType:Uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.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:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(g(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Uo(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(ys(t));d.forEach((p,f)=>{m.has(f)||(a.unobserve(f),d.delete(f))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return _(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 t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Nr(Le))this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Wi();if(e[0]&&!Nr(e[0]))Le=e[0],this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Nr(Le))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:t||{seiPayloadType:243}}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){S.setLogLevel(e),g(t)||(t?S.enableUploadLog():S.disableUploadLog())}static isSupported(){return Kn()}static getCameraList(e=!0){return je(e)}static getMicrophoneList(e=!0){return Ue(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield Wi()).forEach(s=>{s.deviceId===e&&(jo.forEach(n=>{n.setCurrentSpeaker(e),n.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&($i.version=a),e){case"count":$i.addCount({key:t,useUV:o});break;case"enum":$i.addEnum({key:t,value:s,useUV:o});break;case"number":$i.addNumber({key:t,value:s,split:n});break}}},Q=Br;u(Q,"_loggerManager",S),u(Q,"EVENT",H),u(Q,"ERROR_CODE",P),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),vi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],Q.prototype,"enterRoom",1),y([ne()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),zi("room",{merge:(r,i)=>i}),ne()],Q.prototype,"switchRole",1),y([ne()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),vi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),zi("audio",{debounce:{delay:200,getKey:()=>`${Ml}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],Q.prototype,"updateLocalAudio",1),y([Di("audio"),ne()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),vi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),zi("video"),ne()],Q.prototype,"updateLocalVideo",1),y([Di("video"),ne()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),vi("screen",()=>!0),ne()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),zi("screen"),ne()],Q.prototype,"updateScreenShare",1),y([ne()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),vi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),zi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),W(r=>function(i){return _(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Di(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([od(...Ce.TRTC.setRemoteAudioVolume),Nl(200,r=>r),ne({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([Go("start"),yi(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),vi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>tc[r.getName()]})],Q.prototype,"startPlugin",1),y([Go("update"),zi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ic[r.getName()]})],Q.prototype,"updatePlugin",1),y([Go("stop"),Di((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>rc[r.getName()]})],Q.prototype,"stopPlugin",1),y([od(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([ne()],Q.prototype,"getVideoSnapshot",1),y([ne()],Q.prototype,"setCurrentSpeaker",1),y([vi(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([W(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(w(v({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Di(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Di("room")],Q.prototype,"_exitRoom",1),y([Di("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var Ks=Q;var md=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function __(){return _(this,null,function*(){let r,i;try{let m=yield Ue();r=m&&m.length}catch(m){}try{let m=yield je();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=ii.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Ll(){return W(r=>{let i=new md;return function(e,t,s){return _(this,null,function*(){let n=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=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:A.INVALID_OPERATION,message:k({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:k({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield ii.checkSystemRequirementsInternal(),this.checkDestroy();let o=Pe.getEnv();o||(o=Jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Sn.OLD_CLOUD_LADDER)?o=Jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Sn.WEBRTC)&&(o=Jt.WEBRTC))),Z.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),__.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ii.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:k({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Pe.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Pe.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(Xt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var xl=()=>W(r=>function(...i){return _(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Pl(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Vl=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var St={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},wl=[St.UPDATE_REMOTE_MUTE_STAT,St.UPLINK_NETWORK_STATS,St.USER_LIST_RES,St.MUTE_RESULT,St.SERVER_FIRST_PACKAGE_RECEIVED,St.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},j={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var qo=new Set;function Ul(r){let i=[...qo.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var $r=class extends Vl.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-qo.size>0&&this.room.enableSPC&&(this.keepAlive=!0,qo.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=S.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return _(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=x();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Ss(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Jn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(St),c=Object.keys(St)[o.indexOf(s)],d=V[c]||s;switch(wl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case St.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Jd(n.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:k({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:l}),this.emit(_e.SETUP_FAILED,l)}break}case St.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;Ot(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Jn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let f=new b({code:A.API_CALL_TIMEOUT,message:k({key:M.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(f),d(f)},s),m=f=>{f.data.seq===p&&(clearTimeout(l),this.off(n,m),c(f))};this.on(n,m);let p=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),qo.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=n=>{n.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],$r.prototype,"connect",1);var Bl=Se(Ne());var pd=0,_d=!1,Qo=new Set,E_=r=>pd>2&&!_d&&Qo.size===0&&r,fd=!1,ze=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new Bl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=S.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={encodedInsertableStreams:this._enableSEI&&ft,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Qo.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ot;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return ot;i=this._peerConnection.getSenders()[0].transport}else{if(!Bi()||this._peerConnection.getReceivers().length===0)return ot;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ot}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:we.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(pd=0,_d=!1,fd=!0,Qo.add(this)):Qo.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Ci(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});pd+=1,E_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),_d=!0,this._emitter.emit("firewall-restriction")),e(a)},is);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=jt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:k({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(_e.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var Sd=Se(Td());var ce=function(r){return Sd.default.parse(r)},Ye=function(r){return Sd.default.write(r)},ql=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Ye(i)};function Xl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),Ye(i)}function zo(r){return Object.keys(r).filter(i=>r[i])}var Ad=class extends ze{constructor(e){super(w(v({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ni(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new gt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Mr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===ts?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
66
66
  `),s=new Map;t.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let n=[...s];for(let o=0;o<n.length;o++){let[a,c]=n[o];t.splice(a+o,0,c)}return t.join(`\r
67
67
  `)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),Ye(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ce(e);return s.media.forEach(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),Ye(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return _(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===se.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(s){return _(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let n=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${zo(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=j.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=j.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:k({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return _(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return _(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:j.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:V.SUBSCRIBE_RESULT,timeout:ga});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:k({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return _(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===pi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield Yn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Xl(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=ql(t.sdp),this._sdpSemantics===pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return _(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===xi)throw new b({code:A.NOT_SUPPORTED_H264,message:k({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:k({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",w(v({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(ts)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ts)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ma)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return _(this,null,function*(){if(!(Ie(Ad.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=Mt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},en=Ad;y([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],en.prototype,"subscribe",1),y([yi(ze.prototype.afterConnect),_o(ze.prototype.beforeConnect)],en.prototype,"connect",1);var Id=en;var zl={voiceActivityDetection:!1},Cd=class extends ze{constructor(e){super(w(v({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(kt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),n}publish(n){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:q.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let p=n?3:1;yield l[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(p),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(q.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(n){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return _(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!kt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:j.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Lt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:j.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(this,null,function*(){var s;if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return _(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===q.INACTIVE&&(yield this.setTransceiverDirection(q.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;kt()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let n=s.track;this.removeSender(s),yield this.updateOffer("remove",n)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof le&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===nr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;kt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&z(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(q.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return _(this,null,function*(){if(!te)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
68
68
  `).map(d=>{if(d.match(new RegExp(`a=(${q.INACTIVE}|${q.RECVONLY}|${q.SENDONLY})`))&&a++,t.includes(a)){if(e===q.INACTIVE&&d.includes(`a=${q.RECVONLY}`))return n=!0,`a=${e}`;if(e===q.SENDONLY&&d.includes(`a=${q.INACTIVE}`))return n=!0,`a=${q.RECVONLY}`}return d}).join(`\r