trtc-sdk-v5 5.6.0 → 5.6.2-beta.1
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/index.d.ts +1820 -1820
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +2 -2
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -9,7 +9,7 @@ var sh=Object.create;var Ur=Object.defineProperty,nh=Object.defineProperties,Ed=
|
|
|
9
9
|
|
|
10
10
|
`,l+=n)),s&&(l+=`
|
|
11
11
|
Refer to: ${xd("en",a)}
|
|
12
|
-
`),l}var Wh=0,Jh=1,Pd=2;function jh({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:n,context:o}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,l=0,m=-1,_=Wh,g=(R,y)=>p(this,null,function*(){let x=o||this;try{let ie=yield r.apply(x,a);l>0&&n&&n.call(this,l),l=0,R(ie)}catch(ie){let J=()=>{clearTimeout(m),l=0,_=Pd,y(ie)},rn=()=>{_!==Pd&&l<(X(c)?c():c)?(l++,_=Jh,X(t)&&t.call(this,l,J),m=window.setTimeout(()=>{m=-1,g(R,y)},X(d)?d(l):d)):(J(),X(s)&&s.call(this,ie))};X(e)?e.call(this,{error:ie,retry:rn,reject:y,retryFuncArgs:a,retriedCount:l}):rn()}});return new Promise(g)}}var Tt=jh;var wd=Ae(ke(),1),qh=new wd.default,T=qh;var ki=(H=>(H.ROOM_DESTROY="1",H.JOIN_START="21",H.JOIN_SCHEDULE_SUCCESS="22",H.JOIN_SIGNAL_CONNECTION_START="23",H.JOIN_SIGNAL_CONNECTION_END="24",H.JOIN_SEND_CMD="25",H.JOIN_RECEIVED_CMD_RES="26",H.JOIN_SUCCESS="27",H.JOIN_FAILED="28",H.LEAVE_START="51",H.LEAVE_SEND_CMD="52",H.LEAVE_SUCCESS="53",H.PUBLISH_START="61",H.SEND_FIRST_VIDEO_FRAME="62",H.PUBLISH_FAILED="63",H.SUBSCRIBE_START="81",H.SUBSCRIBE_SUCCESS="82",H.SUBSCRIBE_FAILED="84",H.UNSUBSCRIBE_SUCCESS="83",H.LOCAL_TRACK_CAPTURE_START="101",H.LOCAL_TRACK_CAPTURE_SUCCESS="102",H.LOCAL_TRACK_CAPTURE_FAILED="103",H.LOCAL_TRACK_PUBLISHED="104",H.LOCAL_TRACK_UNPUBLISHED="105",H.LOCAL_TRACK_REPLACED="106",H.SWITCH_DEVICE_SUCCESS="107",H.TRACK_MUTED="108",H.TRACK_UNMUTED="109",H.REMOTE_TRACK_SUBSCRIBED="110",H.REMOTE_TRACK_UNSUBSCRIBED="111",H.PLAY_TRACK_START="151",H.PLAYER_STATE_CHANGED="152",H.VIDEO_LOADED_DATA="153",H.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",H.SIGNAL_CONNECTION_STATE_CHANGED="201",H.PEER_CONNECTION_STATE_CHANGED="202",H.SINGLE_CONNECTION_STAT="203",H.SPC_RECONNECTED="204",H.HEARTBEAT_REPORT="251",H.RECEIVED_PUBLISHED_USER_LIST="252",H.REMOTE_PUBLISH_STATE_CHANGED="253",H.AUDIO_LEVEL_INTERVAL="260",H.NETWORK_QUALITY="261",H))(ki||{});var Sa=class{constructor(){this
|
|
12
|
+
`),l}var Wh=0,Jh=1,Pd=2;function jh({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:n,context:o}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,l=0,m=-1,_=Wh,g=(R,y)=>p(this,null,function*(){let x=o||this;try{let ie=yield r.apply(x,a);l>0&&n&&n.call(this,l),l=0,R(ie)}catch(ie){let J=()=>{clearTimeout(m),l=0,_=Pd,y(ie)},rn=()=>{_!==Pd&&l<(X(c)?c():c)?(l++,_=Jh,X(t)&&t.call(this,l,J),m=window.setTimeout(()=>{m=-1,g(R,y)},X(d)?d(l):d)):(J(),X(s)&&s.call(this,ie))};X(e)?e.call(this,{error:ie,retry:rn,reject:y,retryFuncArgs:a,retriedCount:l}):rn()}});return new Promise(g)}}var Tt=jh;var wd=Ae(ke(),1),qh=new wd.default,T=qh;var ki=(H=>(H.ROOM_DESTROY="1",H.JOIN_START="21",H.JOIN_SCHEDULE_SUCCESS="22",H.JOIN_SIGNAL_CONNECTION_START="23",H.JOIN_SIGNAL_CONNECTION_END="24",H.JOIN_SEND_CMD="25",H.JOIN_RECEIVED_CMD_RES="26",H.JOIN_SUCCESS="27",H.JOIN_FAILED="28",H.LEAVE_START="51",H.LEAVE_SEND_CMD="52",H.LEAVE_SUCCESS="53",H.PUBLISH_START="61",H.SEND_FIRST_VIDEO_FRAME="62",H.PUBLISH_FAILED="63",H.SUBSCRIBE_START="81",H.SUBSCRIBE_SUCCESS="82",H.SUBSCRIBE_FAILED="84",H.UNSUBSCRIBE_SUCCESS="83",H.LOCAL_TRACK_CAPTURE_START="101",H.LOCAL_TRACK_CAPTURE_SUCCESS="102",H.LOCAL_TRACK_CAPTURE_FAILED="103",H.LOCAL_TRACK_PUBLISHED="104",H.LOCAL_TRACK_UNPUBLISHED="105",H.LOCAL_TRACK_REPLACED="106",H.SWITCH_DEVICE_SUCCESS="107",H.TRACK_MUTED="108",H.TRACK_UNMUTED="109",H.REMOTE_TRACK_SUBSCRIBED="110",H.REMOTE_TRACK_UNSUBSCRIBED="111",H.PLAY_TRACK_START="151",H.PLAYER_STATE_CHANGED="152",H.VIDEO_LOADED_DATA="153",H.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",H.SIGNAL_CONNECTION_STATE_CHANGED="201",H.PEER_CONNECTION_STATE_CHANGED="202",H.SINGLE_CONNECTION_STAT="203",H.SPC_RECONNECTED="204",H.HEARTBEAT_REPORT="251",H.RECEIVED_PUBLISHED_USER_LIST="252",H.REMOTE_PUBLISH_STATE_CHANGED="253",H.AUDIO_LEVEL_INTERVAL="260",H.NETWORK_QUALITY="261",H))(ki||{});var Sa=class{constructor(){u(this,"_roomIdMap",new Map);u(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Se,env:xt.QCLOUD,browserVersion:_t.name+_t.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:s}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(s))}logSuccessEvent(i){at||!A.isAbleToUpload||this._configs.env===xt.QCLOUD&&this.uploadEventToKibana(L(N({},i),{result:"success"}))}logFailedEvent(i){if(at||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:n}=i,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||I.UNKNOWN};this._configs.env===xt.QCLOUD&&this.uploadEventToKibana(L(N({},o),{error:s}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let s={timestamp:on(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Se,log:i};t&&(s.errorInfo=t.message),this.sendRequest(hi(this._configs.sdkAppId,ni.LOG),s)}sendRequest(i,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}Vt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},ee=new Sa;var Ia=null,Aa=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(rt).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
|
|
13
13
|
`));function It(r){ue(r)&&r!==Aa&&(Aa=r,A.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>It(!0));T.on("63",()=>It(!0));T.on("84",()=>It(!0));T.on("201",r=>{r.state==="RECONNECTING"&&It(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&It(!0)});function Kh(r,i,e){let t=performance.getEntriesByType("resource"),s=hr(r,h.MAIN),n=hr(r,h.BACKUP),o={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of t)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=Math.round(a.domainLookupEnd-a.domainLookupStart),_=Math.round(a.requestStart-a.secureConnectionStart),g=Math.round(a.secureConnectionStart-a.connectStart),R=Math.round(a.responseStart-a.requestStart),y=Math.round(a.responseEnd-a.responseStart),x=[l,m,_,g,R,y];ee.uploadEvent({log:`stat-schedule-net:${d}(${x.join("->")}) ${c}`,userId:i}),o=L(N({},o),{totalCost:d,local:l,dns:m,tcp:g,tls:_,request:R,response:y});break}return o}function Ud(a){return p(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:n,frameWorkType:o}){if(!Aa&&Ia)return{isCached:!0,result:Ia};let c={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(r)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(e)),d.append("groupId",String(t)),d.append("sdkVersion",n),d.append("userSig",String(s)),o&&d.append("frameWorkType",String(o));let l=B(),m=yield Qh(d,c,i);m.config&&(m.config.loggerDomain&&yi(m.config.loggerDomain),ue(m.config.scheduleCache)&&It(!m.config.scheduleCache)),c.delta=B()-l;let _=Kh(Number(i),r,l);return Ia=m,{isCached:!1,result:m,detailCost:_}}catch(d){let l=de(d)?d[0]:d,m=re(l.code)?l.code:0,_=`schedule failed${l.message?`: ${l.message}`:""}`,g=new C({code:I.SCHEDULE_FAILED,extraCode:m,message:D({key:v.JOIN_ROOM_FAILED,data:{error:_,code:m}})});throw A.error(_,m),g}})}var mi={main:"",backup:""};function Ra(r){de(r)?(mi.main=r[0],mi.backup=r[1]):mi.main=r}function hr(r,i=h.MAIN,e=!1){return`https://${mi[i]||$d(r,i,e)}/api/v1/config`}function Bd(r,i=h.MAIN){return`https://${mi[i]||$d(r,i)}/api/v1/trtcAutoConf`}function $d(r,i=h.MAIN,e=!1){if(us(r))return i===h.MAIN?rt.MAIN_OVERSEA:rt.BACKUP_OVERSEA;let t;return us(r)?e?t=i===h.MAIN?rt.MAIN_OVERSEA_OLD:rt.BACKUP_OVERSEA_OLD:t=i===h.MAIN?rt.MAIN_OVERSEA:rt.BACKUP_OVERSEA:t=i===h.MAIN?rt.MAIN:rt.BACKUP,t}function Xh(r,i,e){return new Promise((t,s)=>{Vt({url:r,body:i,timeout:e.timeout}).then(n=>{n.data.code===0?t(n.data.data):s({code:n.data.code,message:n.data.msg})}).catch(s)})}var Vd=(r,i)=>Tt({retryFunction:Xh,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function Qh(r,i,e){return new Promise((t,s)=>{let n=null;ls([Vd(o=>i.count[0]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=o.message,n||(c>=2&&(d[0]=hr(e,h.MAIN,!0)),a())})(hr(e,h.MAIN),r,{get timeout(){return mr(2+i.count[0])*1e3}}),Vd(o=>i.count[1]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=o.message,n||(c>=2&&(d[0]=hr(e,h.BACKUP,!0)),a())})(hr(e,h.BACKUP),r,{get timeout(){return mr(2+i.count[1])*1e3}})]).then(o=>{n=o,t(n)}).catch(s)})}var zh=function(){return new URLSearchParams(location.search).get("trtc_env")||""},us=r=>Number(r)<14e8,hi=function(r,i){let e;Jr?e=Jr:e=us(r)?Qo:Xo;let t=Math.floor(Math.random()*Br(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},hs="unknown";function Fd(){if(hs!=="unknown")return hs;let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();return s==="slow-2"&&(s="2g"),t&&(hs=Gd(t,s)),hs}function Gd(r,i){if(cn[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ca(r){hs=Gd(r)}function _r(){return cn[Fd()]}function Yh(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function Zh(r,i=48e3){return Wd(r/4,i)}function Wd(r,i=48e3){return r*1e3/i}function em(r,i=48e3){return Jd(r,i)*4}function Jd(r,i=48e3){return r*i/1e3}var jd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},gt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Be=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function mr(r,i=1,e=1){return r<=1?e:mr(r-1,e,i+e)}function At(r){return r>8?30*1e3:mr(r)*1e3}function he(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var X=r=>typeof r=="function",E=r=>typeof r=="undefined",Q=r=>typeof r=="string",re=r=>typeof r=="number",ue=r=>typeof r=="boolean",ct=r=>he(r)==="object",de=r=>he(r)==="array",tm=r=>he(r)==="MediaStreamTrack".toLowerCase(),pi=r=>r.isRemote,ms=r=>he(r)==="promise",ps=r=>X(r)&&r.prototype.constructor===r,wn=r=>ps(r)?r.prototype.constructor.name:"",im=typeof AudioWorkletNode!="undefined";function ls(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(n=>{t.push(n),t.length===r.length&&e(t)})})})}function B(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Hd=r=>+r<10?`0${r}`:r,rm=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=Hd(e[1])+Hd(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},sm=Object.prototype.hasOwnProperty,{toString:lf}=Object.prototype;function ya(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Be(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(sm.call(r,i))return!1;return!0}}return!1}function _i(r,i){return{userId:i,hasAudio:!!(r&ai),hasVideo:!!(r&oi),hasAuxiliary:!!(r&Ni),hasSmall:!!(r&jr),audioMuted:!!(r&mn),videoMuted:!!(r&pn),audioAvailable:!!(r&ai)&&!(r&mn),videoAvailable:!!(r&oi)&&!(r&pn)}}function nm(r){let i={urls:`turn:${r.url}`};return!E(r.username)&&!E(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",E(r.credentialType)||(i.credentialType=r.credentialType)),i}function _s(r,i=!0){if(!Q(r))return 0;let e=r.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Ht=function(r,i,e,t){if(!(ct(r)&&ct(i)))return 0;let s=0,n=Object.keys(i),o;for(let a=0,c=n.length;a<c;a++)if(o=n[a],!(E(i[o])||e&&e.includes(o)))if(ct(r[o])&&ct(i[o]))s+=Ht(r[o],i[o],e,t);else{if(t&&t.includes(i[o]))continue;r[o]!==i[o]&&(r[o]=pr(i[o]),s+=1)}return s};function pr(r){if(de(r)){let i=[];return r.forEach((e,t)=>{i[t]=pr(e)}),i}if(ct(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=pr(r[e])}),i}return r}var fs=r=>{let i=[];if(de(r))i=[...r];else if(Q(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},om=r=>Q(r)?document.getElementById(r):r,am=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),cm=()=>am.format(new Date);function dt(r,{keysToInclude:i,keysToExclude:e}){try{if(de(r))return`[${r.map(o=>dt(o,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Be(r)||!de(i)&&!de(e))return JSON.stringify(r);let t={},s=new Set(i),n=new Set(e);return Object.keys(r).forEach(o=>{(n.size===0&&s.has(o)||s.size===0&&!n.has(o))&&(t[o]=Be(r[o])||de(r[o])?JSON.parse(dt(r[o],{keysToExclude:e,keysToInclude:i})):r[o])}),JSON.stringify(t)}catch(t){return"{}"}}function Na(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),dt(r,{keysToInclude:e})}function Vn(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var ba=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Es=r=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(Q(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=e})}),va=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Un=r=>(Object.keys(r).forEach(i=>{re(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Be(r[i])||de(r[i]))&&Un(r[i])}),r);var dm=Object.prototype.hasOwnProperty;var qd=r=>typeof r=="undefined";var Kd=r=>typeof r=="boolean";var um=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Xd(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(um(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(dm.call(r,i))return!1;return!0}}return!1}var fr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Kd(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),A.log(i,e,qd(this.userId)||Xd(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var f=ki;var lm="%cTRTC%c%s",hm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",mm="display: inline",pm=!(Ue||ye||_a),Oa=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!zi&&!Wr&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(f.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&tt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(f.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(f.JOIN_FAILED,()=>{this.startUpload()}),T.on(f.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:n})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})});else if(Q(t.userId)&&re(t.sdkAppId)){let{userId:s,sdkAppId:n}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let n=0;n<s.length;n++){let{userId:o,sdkAppId:a,logs:c}=s[n];yield this.uploadLogWithRetry(JSON.stringify({timestamp:on(),sdkAppId:String(a),userId:o,version:Se,log:c.map(d=>d.log).join(`
|
|
14
14
|
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Tt({retryFunction:()=>Vt({url:hi(e,ni.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Fr());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${tt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(tt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(Q(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,n){var a;if(e.unshift(this.getPrefix(i)),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:i,userId:s,sdkAppId:n,forAllJoinedClients:t}),i<this._logLevel)return;let o=((a=tt[i])==null?void 0:a.toLowerCase())||"info";pm?console[o](lm,hm,mm,...e):console[o](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new fr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;tt[t]&&(this._logLevelToUpload=t)}},A=new Oa;var _m=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},gs=_m;var Da=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!$t())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let n=JSON.parse(s);if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!$t())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){A.warn(i)}}getItem(i){if(!$t())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){A.warn(e)}}setItem(i,e){if(!!$t())try{let t={expiresIn:Date.now()+dn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.warn(t)}}deleteItem(i){if(!$t())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return A.warn(e),!1}}clear(){if(!!$t())try{localStorage.clear()}catch(i){A.warn(i)}}},Ft=new Da;var jt={};$r(jt,{HTTPS_API:()=>Om,IS_GET_CAPABILITIES_SUPPORTED:()=>Va,IS_GET_SETTINGS_SUPPORTED:()=>Ct,IS_SEI_SUPPORTED:()=>Ei,IS_SPC_SUPPORTED:()=>As,basis:()=>km,checkSystemRequirementsInternal:()=>Hn,decodeSupportStatus:()=>$n,encodeSupportStatus:()=>xa,getBrowserInfo:()=>ym,getDisplayResolution:()=>ou,isAddTransceiverSupported:()=>Qe,isBrowserSupported:()=>Pa,isGetReceiversSupported:()=>xi,isGetSendersSupported:()=>gr,isGetTransceiversSupported:()=>Rt,isGetUserMediaSupported:()=>au,isMediaDevicesSupported:()=>Bn,isMediaSessionSupported:()=>lu,isMediaStreamTrackProcessorSupported:()=>Nm,isReplaceTrackSupported:()=>wa,isScreenCaptureApiAvailable:()=>Ss,isSelectedCandidatePair:()=>fi,isSetParametersSupported:()=>Rs,isSmallStreamAPISupported:()=>du,isSmallStreamSupported:()=>Is,isStopTransceiverSupported:()=>Mm,isTRTCSupported:()=>bm,isUnifiedPlanDefault:()=>Dm,isUsedInHttpProtocol:()=>Jt,isWebAudioSupported:()=>cu,isWebCodecSupported:()=>uu,isWebCodecsSupported:()=>nu,isWebRTCSupported:()=>Ua,isWebTransportSupported:()=>hu});var La=Ae(ru(),1);var z={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Cm=new Map([[Y,["Firefox",En]],[rr,["Edg",Tn]],[dr,["Chrome",xn]],[Xe,["Safari",ur]],[ot,["TBS",An]],[es,["XWEB",Rn]],[sr&&Di,["WeChat",Cn]],[ts,["QQ(Win)",yn]],[or,["QQ(Mobile)",tr]],[nr,["QQ(Mobile X5)",tr]],[is,["QQ(Mac)",Nn]],[rs,["QQ(iPad)",bn]],[ss,["MI",On]],[ns,["HW",Dn]],[os,["Samsung",Mn]],[ar,["OPPO",kn]],[cr,["VIVO",Ln]],[ir,["EDGE",gn]],[Yr,["SogouMobile",Sn]],[Zr,["Sogou",In]]]);function ym(){let r=Cm.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var Pa=function(){return!(ma||ir||rr&&ha<80||Y&&la<56)},nu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Bn=function(){if(!navigator.mediaDevices)return Jt()||A.error(Ee.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},su=!1;function Jt(){return location.protocol==="http:"&&!at?(su||A.error(D({key:v.NOT_SUPPORTED_HTTP})),su=!0,!0):!1}var Nm=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},xa=function(){return p(this,null,function*(){if(z.detail.isH264EncodeSupported&&z.detail.isVp8EncodeSupported)return{isH264EncodeSupported:z.detail.isH264EncodeSupported,isVp8EncodeSupported:z.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let n=s.captureStream(0);return t.addTrack(n.getVideoTracks()[0],n),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),z.detail.isH264EncodeSupported=i,z.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:z.detail.isH264EncodeSupported,isVp8EncodeSupported:z.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},$n=function(){return p(this,null,function*(){if(z.detail.isH264DecodeSupported&&z.detail.isVp8DecodeSupported)return{isH264DecodeSupported:z.detail.isH264DecodeSupported,isVp8DecodeSupported:z.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Hn=function(){return p(this,null,function*(){if(z.result&&z.detail.isH264EncodeSupported&&z.detail.isVp8EncodeSupported&&z.detail.isH264DecodeSupported&&z.detail.isVp8DecodeSupported)return z;let r=Pa(),i=Ua(),e=nu(),t=Bn(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield xa(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield $n();if(!s||!n){let c=yield xa();A.warn(`detect encode again h264:${s} vp8:${n} result: ${JSON.stringify(c)}`),s=c.isH264EncodeSupported,n=c.isVp8EncodeSupported}if(s&&o&&(ar||cr||fa)&&!ot&&Ut()<79){let{encode:c,decode:d}=yield vm();s=c,o=d}return z.result=r&&i&&t&&(s||n)&&(o||a),z.detail.isBrowserSupported=r,z.detail.isWebRTCSupported=i,z.detail.isWebCodecsSupported=e,z.detail.isMediaDevicesSupported=t,z.detail.isScreenShareSupported=Ss(),z.detail.isSmallStreamSupported=Is(),z.detail.isH264EncodeSupported=s,z.detail.isVp8EncodeSupported=n,z.detail.isH264DecodeSupported=o,z.detail.isVp8DecodeSupported=a,z.result||A.error(`${navigator.userAgent} ${Na(z.detail,!1)}`),Lm(),z})},bm=function(){return z.result},Ss=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)};function vm(){return p(this,null,function*(){return new Promise(r=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{A.warn("start detect h264 supported by encoding and decoding canvas stream");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=640,t.height=480;let n=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},33),o=-1,a=-1;e=()=>{clearInterval(o),clearInterval(n),clearTimeout(a),d.close(),l.close(),c.getTracks().forEach(y=>y.stop())},a=setTimeout(()=>{e(),r(i)},3*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",y=>l.addIceCandidate(y.candidate)),l.addEventListener("icecandidate",y=>d.addIceCandidate(y.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield l.setRemoteDescription(m);let _=yield l.createAnswer(),g=La.default.parse(_.sdp),R=g.media[0].rtp.findIndex(y=>y.codec==="H264");g.media[0].rtp=[g.media[0].rtp[R]],g.media[0].fmtp=g.media[0].fmtp.filter(y=>y.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(y=>y.payload===g.media[0].rtp[0].payload)),_.sdp=La.default.write(g),yield l.setLocalDescription(_),yield d.setRemoteDescription(_),o=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let y=yield d.getStats(),x=yield l.getStats();i.encode||y.forEach(ie=>{ie.type==="outbound-rtp"&&ie.mediaType===h.VIDEO&&ie.framesEncoded>0&&(i.encode=!0)}),i.decode||x.forEach(ie=>{ie.type==="inbound-rtp"&&ie.mediaType===h.VIDEO&&ie.framesDecoded>0&&(i.decode=!0)})}),500)}catch(t){e(),A.warn(t),r(i)}}))})}var Om=(r,i,e)=>{location.protocol==="http:"&&!at&&(r[i]=()=>{throw new C({code:I.INVALID_OPERATION,message:Ee.NOT_SUPPORTED_HTTP})})},fi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(ue(r.selected)&&!r.selected):!1};function ou(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function au(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function cu(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function du(){return"captureStream"in HTMLCanvasElement.prototype}function Is(){return sr||Ue||Bt&&Bt<63?!1:!!(Pa()&&du())}var Dm=function(){if(E(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:ci}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function xi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function gr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Rt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Qe(){return as===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var As=(()=>!(!Qe()||Mi&&Bt<74))();function Mm(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function wa(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Rs(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&gr()}var Ct=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Va=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ei="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ut()>=86,Ua=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function uu(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(r.AudioDecoder=!0),E(window.AudioEncoder)||(r.AudioEncoder=!0),E(window.VideoDecoder)||(r.VideoDecoder=!0),E(window.VideoEncoder)||(r.VideoEncoder=!0),E(window.ImageDecoder)||(r.ImageDecoder=!0),r}function lu(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function hu(){return!E(window.WebTransport)}function km(){let r={browser:`${_t.name}/${_t.version}`,os:Pn(),displayResolution:ou(),isScreenShareSupported:Ss(),isWebRTCSupported:Ua(),isGetUserMediaSupported:au(),isWebAudioSupported:cu(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:uu(),isMediaSessionSupported:lu(),isWebTransportSupported:hu()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var mu="checkResult";function Lm(){Ft.setItem(mu,{ua:navigator.userAgent,checkResult:z})}(function(){Jt();let i=Ft.getItem(mu);i&&i.ua===navigator.userAgent&&(z=i.checkResult),Hn()})();var _u=Ae(ke(),1);var pu=Symbol("instance"),Kf=Symbol("abortCtrl"),Fn=Symbol("cacheResult"),Cs=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,bs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},ys=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function xm(r){return typeof r=="object"&&r&&"then"in r}var Ns=new Map;function oe(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Ns.get(t)||[];Ns.has(t)||Ns.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=V.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[Fn]:Promise.resolve(d[Fn]);d.state instanceof Cs&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(r)?r.length==0?d.state instanceof Cs&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new ys(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(l=new ys(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`));let m=x=>{if(e.fail&&e.fail.call(this,x),e.sync){if(e.ignoreError)return x;throw x}else return e.ignoreError?Promise.resolve(x):Promise.reject(x)};if(l)return m(l);let _=d.state,g=new Cs(_,i,o);bs.call(d,g);let R=x=>{var ie;return d[Fn]=x,g.aborted||(bs.call(d,i),(ie=e.success)===null||ie===void 0||ie.call(this,d[Fn])),x},y=x=>{let ie=x instanceof Error?x.message:String(x);return bs.call(d,_,x),m(new ys(d._state,`action '${o}' failed :${ie}`,x instanceof Error?x:new Error(ie)))};try{let x=a.apply(this,c);return xm(x)?x.then(R).catch(y):e.sync?R(x):Promise.resolve(R(x))}catch(x){return y(x)}}}}var Pm=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function bs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(V.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var V=class extends _u.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=V.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[pu];s?this.name=s.name+"-"+s.count++:t[pu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Ns.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Ns.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=V.instances.get(i),e||V.instances.set(i,e=new V(i,void 0,Object.create(V.prototype)))):(e=V.instances2.get(i),e||V.instances2.set(i,e=new V(i.constructor.name,void 0,Object.create(V.prototype)))),e}static getState(i){var e;return(e=V.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Pm(V.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){bs.call(this,i)}};V.STATECHANGED="stateChanged";V.UPDATEAFSM="updateAFSM";V.INIT="[*]";V.ON="on";V.OFF="off";V.instances=new Map;V.instances2=new WeakMap;var fu=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},wm=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Vm=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),vs=class{static generateTaskID(){return this.currentTaskID++}static run(i=di,e,t){i===Oi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===pt?t=N({delay:1e4,count:0},t):i===Qr?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),ct(e)&&(t=N(N({},t),e)),X(i)&&(e=i,i=di);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.delay=(1e3/i.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
|
|
15
15
|
let timerID = null;
|
|
@@ -32,7 +32,7 @@ Refer to: ${xd("en",a)}
|
|
|
32
32
|
`)))}else{if(e instanceof Hi)return e;n=new Hi({code:k.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function Ip(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 M=Hi;var zu={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}}},Yu={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}}},vr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Q(r)&&!document.getElementById(r))throw new M({code:k.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Zu={name:"userId",required:!0,type:"string"},el={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Ze.AUDIO_PROFILE_STANDARD,Ze.AUDIO_PROFILE_STANDARD_STEREO,Ze.AUDIO_PROFILE_HIGH,Ze.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Vs(r,i){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5101,fnName:i})}function tl(r,i,e){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var lC={type:"number",notLessThanZero:!0},Ap={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 M({code:k.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Q(r.roomId))throw new M({code:k.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new M({code:k.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 M({code:k.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new M({code:k.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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:vr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:zu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Jt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:zu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:el},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Jt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:el}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:vr,publish:{type:"boolean"},option:Yu},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&Jt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ss())throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:vr,publish:{type:"boolean"},option:Yu}},muteRemoteAudio:[Zu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Zu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:vr,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){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{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){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.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!=="*"&&E(r.streamType))throw new M({code:k.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){Vs(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(!Ei)throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new M({code:k.INVALID_OPERATION,messageParams:{key:v.SEI_DISABLED}});if(r.byteLength>1e3)throw new M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});if(Vs(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new M({code:k.INVALID_PARAMETER,messageParams:{key:v.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}],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 M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(Vs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new M({code:k.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Te={TRTC:Ap};var be=class extends Error{};function Rp(r,i){let e=pr(r);for(let t=0;t<i.length;t++)Ht(e[t],i[t]);return e}function Cp(r){this._resolve=Promise.resolve(r)}function yp(r){this._reject=Promise.reject(r)}var Or=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=Rp;let t=Or.instances.get(i);t?t.set(e,this):Or.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=Or.instances.get(i);return t&&t.get(e)||new Or(i,e)}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 be("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Cp,reject:yp};try{switch(this.state){case 1:if(i===0)throw new be("already started");break;case 4:if(i===2)throw new be("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 be("already start");break;case 3:switch(i.type){case 2:throw new be("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new be("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new be("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 be("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new be("start not allowed after update");case 0:throw new be("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new be("keep start")),new be("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}},ei=Or;ei.instances=new WeakMap;var go=new WeakMap,To=(r,i)=>{if(i instanceof be){let{stack:e}=i;i=new M({code:k.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
33
33
|
`)))}throw i};function Si(r,i){return F((e,t)=>function(...s){let n=ei.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(To.bind(null,t))})}function Fi(r,i){let{merge:e,debounce:t}=i||{};return F((s,n)=>function(...o){let a=ei.get(this,typeof r=="string"?r:r.call(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,y;let _=(R=go.get(this))==null?void 0:R.get(d(...o));if(_){let{timeoutId:x,resolve:ie}=_;clearTimeout(x),ie()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(To.bind(null,n)).then(l,m)},c);go.has(this)?(y=go.get(this))==null||y.set(d(...o),{timeoutId:g,resolve:l}):go.set(this,new Map([[d(...o),{timeoutId:g,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(To.bind(null,n))})}function Ii(r){return F((i,e)=>function(...t){return ei.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(To.bind(null,e))})}var $={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 Us(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Gi(r){return r===Ze.QOS_PREFERENCE_CLEAR?"detail":r===Ze.QOS_PREFERENCE_SMOOTH?"motion":""}function sl(r,i,e){return{room:r,assetsPath:e,innerEmitter:T,constants:oa,environment:lr,utils:Me,eventLogger:ee,log:r.getLogger(),errorModule:i,kvStatManager:w,clearStarted(t,s){let n=t.getAlias(),o=ei.instances.get(r);if(!!o)if(s){let a=o.get(n+s);if(!a)return;a.started=!1}else o.forEach((a,c)=>{c.startsWith(n)&&(a.started=!1)})}}}var nl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=D({key:v.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${n}
|
|
34
34
|
|
|
35
|
-
${s.stack}`),!1}},r};var So=new WeakMap;function ol(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=So.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);So.has(this)?(c=So.get(this))==null||c.set(i(...s),o):So.set(this,new Map([[i(...s),o]]))})}var al="5.6.0";function ve(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Fc(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ao(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)Io.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Io.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Io({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:k.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new M(n(5001));if(E(r.defaultValue)){X(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),X(r.type[d])&&i instanceof r.type[d]&&(c=!0),Q(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new M({code:k.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>ps(d)?wn(d):Q(d)?d:he(d))},value:i}})}else if(!E(r.type)&&he(i)!==r.type)throw new M(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=Q(i)&&i.trim()==="";if(c||d)throw new M(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new M(n(5006));if(!E(r.min)&&re(i)&&i<r.min)throw new M(n(5007));if(!E(r.max)&&re(i)&&i>r.max)throw new M(n(5008));if(Q(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new M(n(5004))}else if(X(r.instanceOf)&&!(i instanceof r.instanceOf))throw new M(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new M(n(5005));let{properties:o}=r;Be(o)&&ct(i)&&Object.keys(o).forEach(c=>{Io.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Be(a)&&de(i)&&i.forEach((c,d)=>{Io.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),X(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let g=e(...o);if(o[g.argIndex]===m)return g.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${he(m)}`:(JSON.stringify(m),m)}catch(g){return`type:${he(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):qa[n];try{let l=s.apply(this,o),m=B();return ms(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),w.addSuccessEvent({key:d,cost:B()-m}),_)).catch(_=>{throw _=M.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:_}),_}):(w.addSuccessEvent({key:d}),l)}catch(l){throw l=M.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:l}),l}})}var Ro=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new M({code:k.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ao.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Co=0,Gc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Sr(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),i.loop&&(this.loop=i.loop),i.volume&&(this.volume=i.volume),this.mixInput.connect()}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)}},Dr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Co=Co+1,this.log=i.log.createChild({id:`${this.getAlias()}${Co}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Co}`),this.core=i}getName(){return Dr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Dr.startValidateRule;case"update":return Dr.updateValidateRule;case"stop":return Dr.stopValidateRule}}start(i){return p(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 Gc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),w.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(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()})}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()}},Ai=Dr;u(Ai,"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 M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ai,"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"]}}}),u(Ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ai,"Name","AudioMixer");var cl=r=>(r=Number(r),r>0&&r<14e8);var yo=0,Mr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",$e("denoiser"));u(this,"workletNode");yo=yo+1,this.log=i.log.createChild({id:`${this.getAlias()}${yo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${yo}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}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 M({code:k.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield vp(L(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new M({code:k.INVALID_PARAMETER,message:a});yield this.workletReady,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 p(this,null,function*(){})}stop(){return p(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(){}},Wi=Mr;u(Wi,"updateValidateRule",{type:"object"}),u(Wi,"stopValidateRule",{type:"object"}),u(Wi,"Name","AIDenoiser");var dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function bp(r){let i;return cl(r)?i=dl.MAIN_OVERSEA:i=dl.MAIN,i}function vp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${bp(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${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 _="Init RTCAIDenoiser failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:g="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${_} Reason: ${d}. ${g}`:`${_}, ${g}`}})}var ul=0,Wc=new Set,Oe=null;jo(al);var Op={RtcError:M,ErrorCode:k,ErrorCodeDictionary:Dt},Bs=class extends hl.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",A.createLogger({id:`t${++ul}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Bs.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(Ai,t.assetsPath),this._use(Wi,t.assetsPath),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($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new M({code:k.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),nl(this,"trtc")}static create(e){}static _create(e,t){Ku();let s=new Bs(e,t||{});return Wc.add(s),s}_listenEvents(){we(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,M.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{we(s,s).add("player-state-changed",n=>{let o=L(N({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Us(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===I.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(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?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.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?$.REMOTE_VIDEO_AVAILABLE:$.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($.ERROR,new M({code:k.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,L(N({},e),{streamType:Us(e.streamType)}))}).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)/st},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/st},video:_.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),we(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Xr){let t=(yield Ui()).find(s=>s.deviceId===Xr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Ui())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Xr&&Oe.groupId!==t.groupId)&&(Oe=t,this.emit($.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(sl(this._room,Op,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(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),!Q(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,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,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,Bs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Wc.delete(this),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 p(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 Ne(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(Q(n.profile)?un[n.profile]&&o.setProfile(un[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=M.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),we(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,L(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=L(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(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):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ht(this._localAudioConfig,e)})}stopLocalAudio(){return p(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),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(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 ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(Q(o.profile)?qe[o.profile]&&a.setProfile(qe[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Is()?Q(o.small)?a.small=qe[o.small]:o.small===!0?a.small=qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=M.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Gi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_SMOOTH));we(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(Q(o.profile)?qe[o.profile]&&this._localVideoTrack.setProfile(qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Gi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Is()?(o.small===!0?this._localVideoTrack.small=qe["120p"]:Q(o.small)?this._localVideoTrack.small=qe[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&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ht(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(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 Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=M.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(Q(n.profile)?ln[n.profile]&&o.setProfile(ln[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(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=Gi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new vt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),we(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},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=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Gi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(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}),Ht(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(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&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(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&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var x,ie;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&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(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:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),Ht(_,e);let g=E(o==null?void 0:o.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:o.receiveWhenViewVisible,R=E(t)?_.view:t,y=E(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:g,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(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 p(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&&(yield this._startRemoteAudio({userId:n.userId}))}else t?yield this._stopRemoteAudio({userId: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 p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(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:(super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return 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(Q(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 p(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&&(E(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 p(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 p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!ya(t)){let a=fs(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=fs(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(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))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Us(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(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Us(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(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(_=>{_.forEach(g=>{d.set(g.target,g.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(fs(t));d.forEach((_,g)=>{m.has(g)||(a.unobserve(g),d.delete(g))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(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),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Ir(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield Ui();if(e[0]&&!Ir(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Ir(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){!this._room.autoReceiveAudio||this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e)||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){this._room.sendSEI(e,t||{seiPayloadType:243})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e)}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Hn()}static getCameraList(){return He(!0)}static getMicrophoneList(){return Ve(!0)}static getSpeakerList(){return Ui(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield Ui()).forEach(s=>{s.deviceId===e&&(Wc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(wi.version=a),e){case"count":wi.addCount({key:t,useUV:o});break;case"enum":wi.addEnum({key:t,value:s,useUV:o});break;case"number":wi.addNumber({key:t,value:s,split:n});break}}},K=Bs;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",k),u(K,"TYPE",Ze),u(K,"frameWorkType",30),b([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"}})})],K.prototype,"use",1),b([ve(Te.TRTC.enterRoom),Si("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ve(Te.TRTC.switchRole),Fi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ve(Te.TRTC.startLocalAudio),Si("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()],K.prototype,"startLocalAudio",1),b([ve(Te.TRTC.updateLocalAudio),Fi("audio",{debounce:{delay:200,getKey:()=>`${ul}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ii("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ve(Te.TRTC.startLocalVideo),Si("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()],K.prototype,"startLocalVideo",1),b([ve(Te.TRTC.updateLocalVideo),Fi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ii("video"),ne()],K.prototype,"stopLocalVideo",1),b([ve(Te.TRTC.startScreenShare),Si("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ve(Te.TRTC.updateScreenShare),Fi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ve(Te.TRTC.startRemoteVideo),Si(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ve(Te.TRTC.updateRemoteVideo),Fi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ve(Te.TRTC.stopRemoteVideo),F(r=>function(i){return p(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}`})],K.prototype,"stopRemoteVideo",1),b([Ii(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ve(...Te.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([Fc(...Te.TRTC.setRemoteAudioVolume),ol(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Ro("start"),Si((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Ro("update"),Fi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Ro("stop"),Ii((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Qa[r.getName()]})],K.prototype,"stopPlugin",1),b([Fc(...Te.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Si(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Ii(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ii("room")],K.prototype,"_exitRoom",1),b([Ii("screen")],K.prototype,"_stopScreenShare",1),b([ve(...Te.TRTC.sendSEIMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ve(Te.TRTC.sendCustomMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],K.prototype,"sendCustomMessage",1),b([ve(Te.TRTC.create)],K,"_create",1);var $s=K;var Jc=class{constructor(){this._set=new Set;T.on(f.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 Dp(){return p(this,null,function*(){let r,i;try{let m=yield Ve();r=m&&m.length}catch(m){}try{let m=yield He();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=jt.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};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function ml(){return F(r=>{let i=new Jc;return function(e,t,s){return p(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 C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:I.INVALID_OPERATION,message:D({key:v.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(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield jt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Me.getEnv();o||(o=xt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(hn.OLD_CLOUD_LADDER)?o=xt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(hn.WEBRTC)&&(o=xt.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Dp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!jt.isWebRTCSupported()||!a&&!c)throw new C({code:I.NOT_SUPPORTED,message:D({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Me.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Me.performanceNow(),T.emit(f.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(at)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var pl=()=>F(r=>function(...i){return p(this,null,function*(){T.emit(f.LEAVE_START,{room:this}),yield r.call(this),T.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _l(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var El=Ae(ke(),1);var fl=Symbol("instance"),hb=Symbol("abortCtrl"),jc=Symbol("cacheResult"),Ji=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Gs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Hs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Mp(r){return typeof r=="object"&&r&&"then"in r}var Fs=new Map;function qc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Fs.get(t)||[];Fs.has(t)||Fs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[jc];d.state instanceof Ji&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof Ji&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new Ji(m,i,o);Gs.call(d,_);let g=y=>{var x;return d[jc]=y,_.aborted||(Gs.call(d,i),(x=e.success)===null||x===void 0||x.call(this,d[jc])),y},R=y=>{let x=y instanceof Error?y.message:String(y);if(Gs.call(d,m,y),e.fail)e.fail.call(this,new Hs(d._state,`action '${o}' failed :${x}`,y instanceof Error?y:new Error(x)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Mp(y)?y.then(g).catch(R):g(y)}catch(y){R(y)}}}}var kp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function Gs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends El.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[fl];s?this.name=s.name+"-"+s.count++:t[fl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Fs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Fs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){kp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Gs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Tl=Ae(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var ht={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},gl=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG],P={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"},W={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 ti=new WeakMap;function Ri({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=Tt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ti.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;X(e)&&e.call(this,c,d),(l=ti.get(s))!=null&&l.has(n)&&(ti.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ti.get(s);return d?d.set(n,{args:c}):ti.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ti.get(s))==null?void 0:l.delete(n)})},o}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ti.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ti.get(t).get(r),_=!0;if(e){for(let g of m)if(!a.find(R=>R===g)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ti.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var No=new Set;function Sl(r){let i=[...No.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var kr=class extends Tl.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);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-No.size>0&&this.room.enableSPC&&(this.keepAlive=!0,No.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.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.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 p(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=B();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 ls(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 C({code:I.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`),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+=Vn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(ht),c=Object.keys(ht)[o.indexOf(s)],d=P[c];switch(gl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Cd(n.svrTime),this._log.info("ChannelSetup Success"),w.addSuccessEvent({key:521701,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),w.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case ht.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(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{It(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(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:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:P.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),w.addSuccessEvent({key:521702,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(w.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+=Vn(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 g=new C({code:I.API_CALL_TIMEOUT,message:D({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(g),d(g)},s),m=g=>{g.data.seq===_&&(clearTimeout(l),this.off(n,m),c(g))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Tt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.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"),No.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()},e*1e3),s=n=>{n instanceof Ji&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([Ri({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())}})],kr.prototype,"connect",1);var Il=Ae(ke());var Kc=0,Xc=!1,vo=new Set,xp=r=>Kc>2&&!Xc&&vo.size===0&&r,Qc=!1,We=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 Il.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=A.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=B())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,w.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&w.addSuccessEvent({key:521706,cost:B()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,w.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&w.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Ei,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),vo.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 C({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return it;let i=null;if(this._isUplink){if(!gr()||this._peerConnection.getSenders().length===0)return it;i=this._peerConnection.getSenders()[0].transport}else{if(!xi()||this._peerConnection.getReceivers().length===0)return it;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:it}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 C({message:s,code:I.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(),ee.logSuccessEvent({userId:this._room.userId,eventType:Le.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Kc=0,Xc=!1,Qc=!0,vo.add(this)):vo.delete(this),T.emit(f.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 p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(fi(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 C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Kc+=1,xp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);T.on(f.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=wt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.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(le.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 ed=Ae(Zc());var ce=function(r){return ed.default.parse(r)},et=function(r){return ed.default.write(r)},Ol=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"})}),et(i)};function Dl(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(" ")}}),et(i)}function Oo(r){return Object.keys(r).filter(i=>r[i])}var id=class extends We{constructor(e){super(L(N({},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 zt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ot(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cr(this._room,this)}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 _i(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===qr?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
|
|
35
|
+
${s.stack}`),!1}},r};var So=new WeakMap;function ol(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=So.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);So.has(this)?(c=So.get(this))==null||c.set(i(...s),o):So.set(this,new Map([[i(...s),o]]))})}var al="5.6.2-beta.1";function ve(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Fc(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ao(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)Io.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Io.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Io({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:k.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new M(n(5001));if(E(r.defaultValue)){X(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),X(r.type[d])&&i instanceof r.type[d]&&(c=!0),Q(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new M({code:k.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>ps(d)?wn(d):Q(d)?d:he(d))},value:i}})}else if(!E(r.type)&&he(i)!==r.type)throw new M(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=Q(i)&&i.trim()==="";if(c||d)throw new M(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new M(n(5006));if(!E(r.min)&&re(i)&&i<r.min)throw new M(n(5007));if(!E(r.max)&&re(i)&&i>r.max)throw new M(n(5008));if(Q(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new M(n(5004))}else if(X(r.instanceOf)&&!(i instanceof r.instanceOf))throw new M(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new M(n(5005));let{properties:o}=r;Be(o)&&ct(i)&&Object.keys(o).forEach(c=>{Io.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Be(a)&&de(i)&&i.forEach((c,d)=>{Io.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),X(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let g=e(...o);if(o[g.argIndex]===m)return g.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${he(m)}`:(JSON.stringify(m),m)}catch(g){return`type:${he(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):qa[n];try{let l=s.apply(this,o),m=B();return ms(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),w.addSuccessEvent({key:d,cost:B()-m}),_)).catch(_=>{throw _=M.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:_}),_}):(w.addSuccessEvent({key:d}),l)}catch(l){throw l=M.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:l}),l}})}var Ro=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new M({code:k.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ao.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Co=0,Gc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Sr(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),i.loop&&(this.loop=i.loop),i.volume&&(this.volume=i.volume),this.mixInput.connect()}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)}},Dr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Co=Co+1,this.log=i.log.createChild({id:`${this.getAlias()}${Co}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Co}`),this.core=i}getName(){return Dr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Dr.startValidateRule;case"update":return Dr.updateValidateRule;case"stop":return Dr.stopValidateRule}}start(i){return p(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 Gc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),w.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(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()})}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()}},Ai=Dr;u(Ai,"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 M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ai,"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"]}}}),u(Ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ai,"Name","AudioMixer");var cl=r=>(r=Number(r),r>0&&r<14e8);var yo=0,Mr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",$e("denoiser"));u(this,"workletNode");yo=yo+1,this.log=i.log.createChild({id:`${this.getAlias()}${yo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${yo}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}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 M({code:k.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield vp(L(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new M({code:k.INVALID_PARAMETER,message:a});yield this.workletReady,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 p(this,null,function*(){})}stop(){return p(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(){}},Wi=Mr;u(Wi,"updateValidateRule",{type:"object"}),u(Wi,"stopValidateRule",{type:"object"}),u(Wi,"Name","AIDenoiser");var dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function bp(r){let i;return cl(r)?i=dl.MAIN_OVERSEA:i=dl.MAIN,i}function vp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${bp(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${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 _="Init RTCAIDenoiser failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:g="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${_} Reason: ${d}. ${g}`:`${_}, ${g}`}})}var ul=0,Wc=new Set,Oe=null;jo(al);var Op={RtcError:M,ErrorCode:k,ErrorCodeDictionary:Dt},Bs=class extends hl.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",A.createLogger({id:`t${++ul}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Bs.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(Ai,t.assetsPath),this._use(Wi,t.assetsPath),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($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new M({code:k.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),nl(this,"trtc")}static create(e){}static _create(e,t){Ku();let s=new Bs(e,t||{});return Wc.add(s),s}_listenEvents(){we(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,M.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{we(s,s).add("player-state-changed",n=>{let o=L(N({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Us(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===I.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(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?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.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?$.REMOTE_VIDEO_AVAILABLE:$.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($.ERROR,new M({code:k.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,L(N({},e),{streamType:Us(e.streamType)}))}).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)/st},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/st},video:_.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),we(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Xr){let t=(yield Ui()).find(s=>s.deviceId===Xr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Ui())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Xr&&Oe.groupId!==t.groupId)&&(Oe=t,this.emit($.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(sl(this._room,Op,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(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),!Q(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,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,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,Bs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Wc.delete(this),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 p(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 Ne(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(Q(n.profile)?un[n.profile]&&o.setProfile(un[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=M.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),we(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,L(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=L(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(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):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ht(this._localAudioConfig,e)})}stopLocalAudio(){return p(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),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(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 ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(Q(o.profile)?qe[o.profile]&&a.setProfile(qe[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Is()?Q(o.small)?a.small=qe[o.small]:o.small===!0?a.small=qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=M.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Gi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_SMOOTH));we(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(Q(o.profile)?qe[o.profile]&&this._localVideoTrack.setProfile(qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Gi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Is()?(o.small===!0?this._localVideoTrack.small=qe["120p"]:Q(o.small)?this._localVideoTrack.small=qe[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&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ht(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(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 Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=M.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(Q(n.profile)?ln[n.profile]&&o.setProfile(ln[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(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=Gi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new vt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),we(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},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=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Gi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(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}),Ht(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(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&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(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&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var x,ie;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&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(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:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),Ht(_,e);let g=E(o==null?void 0:o.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:o.receiveWhenViewVisible,R=E(t)?_.view:t,y=E(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:g,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(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 p(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 p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(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:(super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return 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(Q(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 p(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&&(E(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 p(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 p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!ya(t)){let a=fs(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=fs(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(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))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Us(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(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Us(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(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(_=>{_.forEach(g=>{d.set(g.target,g.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(fs(t));d.forEach((_,g)=>{m.has(g)||(a.unobserve(g),d.delete(g))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(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),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Ir(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield Ui();if(e[0]&&!Ir(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Ir(Oe))&&(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){this._room.sendSEI(e,t||{seiPayloadType:243})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e)}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Hn()}static getCameraList(){return He(!0)}static getMicrophoneList(){return Ve(!0)}static getSpeakerList(){return Ui(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield Ui()).forEach(s=>{s.deviceId===e&&(Wc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(wi.version=a),e){case"count":wi.addCount({key:t,useUV:o});break;case"enum":wi.addEnum({key:t,value:s,useUV:o});break;case"number":wi.addNumber({key:t,value:s,split:n});break}}},K=Bs;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",k),u(K,"TYPE",Ze),u(K,"frameWorkType",30),b([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"}})})],K.prototype,"use",1),b([ve(Te.TRTC.enterRoom),Si("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ve(Te.TRTC.switchRole),Fi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ve(Te.TRTC.startLocalAudio),Si("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()],K.prototype,"startLocalAudio",1),b([ve(Te.TRTC.updateLocalAudio),Fi("audio",{debounce:{delay:200,getKey:()=>`${ul}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ii("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ve(Te.TRTC.startLocalVideo),Si("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()],K.prototype,"startLocalVideo",1),b([ve(Te.TRTC.updateLocalVideo),Fi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ii("video"),ne()],K.prototype,"stopLocalVideo",1),b([ve(Te.TRTC.startScreenShare),Si("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ve(Te.TRTC.updateScreenShare),Fi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ve(Te.TRTC.startRemoteVideo),Si(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ve(Te.TRTC.updateRemoteVideo),Fi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ve(Te.TRTC.stopRemoteVideo),F(r=>function(i){return p(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}`})],K.prototype,"stopRemoteVideo",1),b([Ii(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ve(...Te.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([Fc(...Te.TRTC.setRemoteAudioVolume),ol(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Ro("start"),Si((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Ro("update"),Fi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Ro("stop"),Ii((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Qa[r.getName()]})],K.prototype,"stopPlugin",1),b([Fc(...Te.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Si(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Ii(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ii("room")],K.prototype,"_exitRoom",1),b([Ii("screen")],K.prototype,"_stopScreenShare",1),b([ve(...Te.TRTC.sendSEIMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ve(Te.TRTC.sendCustomMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],K.prototype,"sendCustomMessage",1),b([ve(Te.TRTC.create)],K,"_create",1);var $s=K;var Jc=class{constructor(){this._set=new Set;T.on(f.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 Dp(){return p(this,null,function*(){let r,i;try{let m=yield Ve();r=m&&m.length}catch(m){}try{let m=yield He();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=jt.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};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function ml(){return F(r=>{let i=new Jc;return function(e,t,s){return p(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 C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:I.INVALID_OPERATION,message:D({key:v.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(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield jt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Me.getEnv();o||(o=xt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(hn.OLD_CLOUD_LADDER)?o=xt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(hn.WEBRTC)&&(o=xt.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Dp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!jt.isWebRTCSupported()||!a&&!c)throw new C({code:I.NOT_SUPPORTED,message:D({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Me.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Me.performanceNow(),T.emit(f.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(at)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var pl=()=>F(r=>function(...i){return p(this,null,function*(){T.emit(f.LEAVE_START,{room:this}),yield r.call(this),T.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _l(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var El=Ae(ke(),1);var fl=Symbol("instance"),hb=Symbol("abortCtrl"),jc=Symbol("cacheResult"),Ji=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Gs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Hs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Mp(r){return typeof r=="object"&&r&&"then"in r}var Fs=new Map;function qc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Fs.get(t)||[];Fs.has(t)||Fs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[jc];d.state instanceof Ji&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof Ji&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new Ji(m,i,o);Gs.call(d,_);let g=y=>{var x;return d[jc]=y,_.aborted||(Gs.call(d,i),(x=e.success)===null||x===void 0||x.call(this,d[jc])),y},R=y=>{let x=y instanceof Error?y.message:String(y);if(Gs.call(d,m,y),e.fail)e.fail.call(this,new Hs(d._state,`action '${o}' failed :${x}`,y instanceof Error?y:new Error(x)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Mp(y)?y.then(g).catch(R):g(y)}catch(y){R(y)}}}}var kp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function Gs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends El.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[fl];s?this.name=s.name+"-"+s.count++:t[fl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Fs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Fs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){kp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Gs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Tl=Ae(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var ht={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},gl=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG],P={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"},W={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 ti=new WeakMap;function Ri({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=Tt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ti.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;X(e)&&e.call(this,c,d),(l=ti.get(s))!=null&&l.has(n)&&(ti.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ti.get(s);return d?d.set(n,{args:c}):ti.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ti.get(s))==null?void 0:l.delete(n)})},o}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ti.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ti.get(t).get(r),_=!0;if(e){for(let g of m)if(!a.find(R=>R===g)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ti.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var No=new Set;function Sl(r){let i=[...No.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var kr=class extends Tl.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);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-No.size>0&&this.room.enableSPC&&(this.keepAlive=!0,No.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.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.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 p(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=B();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 ls(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 C({code:I.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`),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+=Vn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(ht),c=Object.keys(ht)[o.indexOf(s)],d=P[c];switch(gl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Cd(n.svrTime),this._log.info("ChannelSetup Success"),w.addSuccessEvent({key:521701,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),w.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case ht.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(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{It(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(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:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:P.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),w.addSuccessEvent({key:521702,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(w.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+=Vn(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 g=new C({code:I.API_CALL_TIMEOUT,message:D({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(g),d(g)},s),m=g=>{g.data.seq===_&&(clearTimeout(l),this.off(n,m),c(g))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Tt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.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"),No.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()},e*1e3),s=n=>{n instanceof Ji&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([Ri({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())}})],kr.prototype,"connect",1);var Il=Ae(ke());var Kc=0,Xc=!1,vo=new Set,xp=r=>Kc>2&&!Xc&&vo.size===0&&r,Qc=!1,We=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 Il.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=A.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=B())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,w.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&w.addSuccessEvent({key:521706,cost:B()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,w.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&w.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Ei,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),vo.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 C({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return it;let i=null;if(this._isUplink){if(!gr()||this._peerConnection.getSenders().length===0)return it;i=this._peerConnection.getSenders()[0].transport}else{if(!xi()||this._peerConnection.getReceivers().length===0)return it;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:it}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 C({message:s,code:I.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(),ee.logSuccessEvent({userId:this._room.userId,eventType:Le.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Kc=0,Xc=!1,Qc=!0,vo.add(this)):vo.delete(this),T.emit(f.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 p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(fi(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 C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Kc+=1,xp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);T.on(f.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=wt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.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(le.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 ed=Ae(Zc());var ce=function(r){return ed.default.parse(r)},et=function(r){return ed.default.write(r)},Ol=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"})}),et(i)};function Dl(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(" ")}}),et(i)}function Oo(r){return Object.keys(r).filter(i=>r[i])}var id=class extends We{constructor(e){super(L(N({},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 zt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ot(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cr(this._room,this)}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 _i(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===qr?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
|
|
36
36
|
`),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
|
|
37
37
|
`)}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"})}),et(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)))}),et(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(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 C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(s){return p(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=N({},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} [${Oo(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=W.UNSUBSCRIBE,o=P.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=W.SUBSCRIBE_CHANGE,o=P.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(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:W.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:P.SUBSCRIBE_RESULT,timeout:ra});if(!this._peerConnection){let a=new C({code:I.INVALID_OPERATION,message:D({key:v.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};Qe()&&this._sdpSemantics===ci?(this._peerConnection.addTransceiver(h.AUDIO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield $n();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Dl(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Ol(t.sdp),this._sdpSemantics===ci&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===bi)throw new C({code:I.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new C({code:t,message:D({key:v.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",L(N({},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(qr)});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(qr)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yo)});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 p(this,null,function*(){if(!(Re(id.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=At(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}},js=id;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],js.prototype,"subscribe",1),b([to(We.prototype.afterConnect),eo(We.prototype.beforeConnect)],js.prototype,"connect",1);var td=js;var kl={voiceActivityDetection:!1},rd=class extends We{constructor(e){super(L(N({},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 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&&(Rt()?(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 p(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(),Qe()?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 p(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:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:j.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 _=n?3:1;yield l[_].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(_),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(j.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 p(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 p(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(j.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(j.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 p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Rt()){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=L(N({},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=L(N({},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(j.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 p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:P.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:P.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.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),Ct){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:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:P.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(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(),Qe()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(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===j.INACTIVE&&(yield this.setTransceiverDirection(j.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Rt()&&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 ae&&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===Yi||!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;Rt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&X(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(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`),Qe()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(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(j.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)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
|
|
38
38
|
`).map(d=>{if(d.match(new RegExp(`a=(${j.INACTIVE}|${j.RECVONLY}|${j.SENDONLY})`))&&a++,t.includes(a)){if(e===j.INACTIVE&&d.includes(`a=${j.RECVONLY}`))return n=!0,`a=${e}`;if(e===j.SENDONLY&&d.includes(`a=${j.INACTIVE}`))return n=!0,`a=${j.RECVONLY}`}return d}).join(`\r
|